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, 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, RemoteConnectionOptions, 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 ActiveItemChanged,
1034 ItemRemoved {
1035 item_id: EntityId,
1036 },
1037 UserSavedItem {
1038 pane: WeakEntity<Pane>,
1039 item: Box<dyn WeakItemHandle>,
1040 save_intent: SaveIntent,
1041 },
1042 ContactRequestedJoin(u64),
1043 WorkspaceCreated(WeakEntity<Workspace>),
1044 OpenBundledFile {
1045 text: Cow<'static, str>,
1046 title: &'static str,
1047 language: &'static str,
1048 },
1049 ZoomChanged,
1050 ModalOpened,
1051}
1052
1053#[derive(Debug)]
1054pub enum OpenVisible {
1055 All,
1056 None,
1057 OnlyFiles,
1058 OnlyDirectories,
1059}
1060
1061enum WorkspaceLocation {
1062 // Valid local paths or SSH project to serialize
1063 Location(SerializedWorkspaceLocation, PathList),
1064 // No valid location found hence clear session id
1065 DetachFromSession,
1066 // No valid location found to serialize
1067 None,
1068}
1069
1070type PromptForNewPath = Box<
1071 dyn Fn(
1072 &mut Workspace,
1073 DirectoryLister,
1074 &mut Window,
1075 &mut Context<Workspace>,
1076 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1077>;
1078
1079type PromptForOpenPath = Box<
1080 dyn Fn(
1081 &mut Workspace,
1082 DirectoryLister,
1083 &mut Window,
1084 &mut Context<Workspace>,
1085 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1086>;
1087
1088#[derive(Default)]
1089struct DispatchingKeystrokes {
1090 dispatched: HashSet<Vec<Keystroke>>,
1091 queue: VecDeque<Keystroke>,
1092 task: Option<Shared<Task<()>>>,
1093}
1094
1095/// Collects everything project-related for a certain window opened.
1096/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
1097///
1098/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
1099/// The `Workspace` owns everybody's state and serves as a default, "global context",
1100/// that can be used to register a global action to be triggered from any place in the window.
1101pub struct Workspace {
1102 weak_self: WeakEntity<Self>,
1103 workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
1104 zoomed: Option<AnyWeakView>,
1105 previous_dock_drag_coordinates: Option<Point<Pixels>>,
1106 zoomed_position: Option<DockPosition>,
1107 center: PaneGroup,
1108 left_dock: Entity<Dock>,
1109 bottom_dock: Entity<Dock>,
1110 right_dock: Entity<Dock>,
1111 panes: Vec<Entity<Pane>>,
1112 panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
1113 active_pane: Entity<Pane>,
1114 last_active_center_pane: Option<WeakEntity<Pane>>,
1115 last_active_view_id: Option<proto::ViewId>,
1116 status_bar: Entity<StatusBar>,
1117 modal_layer: Entity<ModalLayer>,
1118 toast_layer: Entity<ToastLayer>,
1119 titlebar_item: Option<AnyView>,
1120 notifications: Notifications,
1121 suppressed_notifications: HashSet<NotificationId>,
1122 project: Entity<Project>,
1123 follower_states: HashMap<CollaboratorId, FollowerState>,
1124 last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
1125 window_edited: bool,
1126 last_window_title: Option<String>,
1127 dirty_items: HashMap<EntityId, Subscription>,
1128 active_call: Option<(Entity<ActiveCall>, Vec<Subscription>)>,
1129 leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
1130 database_id: Option<WorkspaceId>,
1131 app_state: Arc<AppState>,
1132 dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
1133 _subscriptions: Vec<Subscription>,
1134 _apply_leader_updates: Task<Result<()>>,
1135 _observe_current_user: Task<Result<()>>,
1136 _schedule_serialize_workspace: Option<Task<()>>,
1137 _schedule_serialize_ssh_paths: Option<Task<()>>,
1138 pane_history_timestamp: Arc<AtomicUsize>,
1139 bounds: Bounds<Pixels>,
1140 pub centered_layout: bool,
1141 bounds_save_task_queued: Option<Task<()>>,
1142 on_prompt_for_new_path: Option<PromptForNewPath>,
1143 on_prompt_for_open_path: Option<PromptForOpenPath>,
1144 terminal_provider: Option<Box<dyn TerminalProvider>>,
1145 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
1146 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
1147 _items_serializer: Task<Result<()>>,
1148 session_id: Option<String>,
1149 scheduled_tasks: Vec<Task<()>>,
1150}
1151
1152impl EventEmitter<Event> for Workspace {}
1153
1154#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1155pub struct ViewId {
1156 pub creator: CollaboratorId,
1157 pub id: u64,
1158}
1159
1160pub struct FollowerState {
1161 center_pane: Entity<Pane>,
1162 dock_pane: Option<Entity<Pane>>,
1163 active_view_id: Option<ViewId>,
1164 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1165}
1166
1167struct FollowerView {
1168 view: Box<dyn FollowableItemHandle>,
1169 location: Option<proto::PanelId>,
1170}
1171
1172impl Workspace {
1173 const DEFAULT_PADDING: f32 = 0.2;
1174 const MAX_PADDING: f32 = 0.4;
1175
1176 pub fn new(
1177 workspace_id: Option<WorkspaceId>,
1178 project: Entity<Project>,
1179 app_state: Arc<AppState>,
1180 window: &mut Window,
1181 cx: &mut Context<Self>,
1182 ) -> Self {
1183 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1184 match event {
1185 project::Event::RemoteIdChanged(_) => {
1186 this.update_window_title(window, cx);
1187 }
1188
1189 project::Event::CollaboratorLeft(peer_id) => {
1190 this.collaborator_left(*peer_id, window, cx);
1191 }
1192
1193 project::Event::WorktreeRemoved(_) | project::Event::WorktreeAdded(_) => {
1194 this.update_window_title(window, cx);
1195 this.serialize_workspace(window, cx);
1196 // This event could be triggered by `AddFolderToProject` or `RemoveFromProject`.
1197 this.update_history(cx);
1198 }
1199
1200 project::Event::DisconnectedFromHost => {
1201 this.update_window_edited(window, cx);
1202 let leaders_to_unfollow =
1203 this.follower_states.keys().copied().collect::<Vec<_>>();
1204 for leader_id in leaders_to_unfollow {
1205 this.unfollow(leader_id, window, cx);
1206 }
1207 }
1208
1209 project::Event::DisconnectedFromSshRemote => {
1210 this.update_window_edited(window, cx);
1211 }
1212
1213 project::Event::Closed => {
1214 window.remove_window();
1215 }
1216
1217 project::Event::DeletedEntry(_, entry_id) => {
1218 for pane in this.panes.iter() {
1219 pane.update(cx, |pane, cx| {
1220 pane.handle_deleted_project_item(*entry_id, window, cx)
1221 });
1222 }
1223 }
1224
1225 project::Event::Toast {
1226 notification_id,
1227 message,
1228 } => this.show_notification(
1229 NotificationId::named(notification_id.clone()),
1230 cx,
1231 |cx| cx.new(|cx| MessageNotification::new(message.clone(), cx)),
1232 ),
1233
1234 project::Event::HideToast { notification_id } => {
1235 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1236 }
1237
1238 project::Event::LanguageServerPrompt(request) => {
1239 struct LanguageServerPrompt;
1240
1241 let mut hasher = DefaultHasher::new();
1242 request.lsp_name.as_str().hash(&mut hasher);
1243 let id = hasher.finish();
1244
1245 this.show_notification(
1246 NotificationId::composite::<LanguageServerPrompt>(id as usize),
1247 cx,
1248 |cx| {
1249 cx.new(|cx| {
1250 notifications::LanguageServerPrompt::new(request.clone(), cx)
1251 })
1252 },
1253 );
1254 }
1255
1256 project::Event::AgentLocationChanged => {
1257 this.handle_agent_location_changed(window, cx)
1258 }
1259
1260 _ => {}
1261 }
1262 cx.notify()
1263 })
1264 .detach();
1265
1266 cx.subscribe_in(
1267 &project.read(cx).breakpoint_store(),
1268 window,
1269 |workspace, _, event, window, cx| match event {
1270 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1271 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1272 workspace.serialize_workspace(window, cx);
1273 }
1274 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1275 },
1276 )
1277 .detach();
1278
1279 cx.on_focus_lost(window, |this, window, cx| {
1280 let focus_handle = this.focus_handle(cx);
1281 window.focus(&focus_handle);
1282 })
1283 .detach();
1284
1285 let weak_handle = cx.entity().downgrade();
1286 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1287
1288 let center_pane = cx.new(|cx| {
1289 let mut center_pane = Pane::new(
1290 weak_handle.clone(),
1291 project.clone(),
1292 pane_history_timestamp.clone(),
1293 None,
1294 NewFile.boxed_clone(),
1295 window,
1296 cx,
1297 );
1298 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1299 center_pane
1300 });
1301 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1302 .detach();
1303
1304 window.focus(¢er_pane.focus_handle(cx));
1305
1306 cx.emit(Event::PaneAdded(center_pane.clone()));
1307
1308 let window_handle = window.window_handle().downcast::<Workspace>().unwrap();
1309 app_state.workspace_store.update(cx, |store, _| {
1310 store.workspaces.insert(window_handle);
1311 });
1312
1313 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1314 let mut connection_status = app_state.client.status();
1315 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1316 current_user.next().await;
1317 connection_status.next().await;
1318 let mut stream =
1319 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1320
1321 while stream.recv().await.is_some() {
1322 this.update(cx, |_, cx| cx.notify())?;
1323 }
1324 anyhow::Ok(())
1325 });
1326
1327 // All leader updates are enqueued and then processed in a single task, so
1328 // that each asynchronous operation can be run in order.
1329 let (leader_updates_tx, mut leader_updates_rx) =
1330 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1331 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1332 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1333 Self::process_leader_update(&this, leader_id, update, cx)
1334 .await
1335 .log_err();
1336 }
1337
1338 Ok(())
1339 });
1340
1341 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1342 let modal_layer = cx.new(|_| ModalLayer::new());
1343 let toast_layer = cx.new(|_| ToastLayer::new());
1344 cx.subscribe(
1345 &modal_layer,
1346 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1347 cx.emit(Event::ModalOpened);
1348 },
1349 )
1350 .detach();
1351
1352 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1353 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1354 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1355 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1356 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1357 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1358 let status_bar = cx.new(|cx| {
1359 let mut status_bar = StatusBar::new(¢er_pane.clone(), window, cx);
1360 status_bar.add_left_item(left_dock_buttons, window, cx);
1361 status_bar.add_right_item(right_dock_buttons, window, cx);
1362 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1363 status_bar
1364 });
1365
1366 let session_id = app_state.session.read(cx).id().to_owned();
1367
1368 let mut active_call = None;
1369 if let Some(call) = ActiveCall::try_global(cx) {
1370 let subscriptions = vec![cx.subscribe_in(&call, window, Self::on_active_call_event)];
1371 active_call = Some((call, subscriptions));
1372 }
1373
1374 let (serializable_items_tx, serializable_items_rx) =
1375 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1376 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1377 Self::serialize_items(&this, serializable_items_rx, cx).await
1378 });
1379
1380 let subscriptions = vec![
1381 cx.observe_window_activation(window, Self::on_window_activation_changed),
1382 cx.observe_window_bounds(window, move |this, window, cx| {
1383 if this.bounds_save_task_queued.is_some() {
1384 return;
1385 }
1386 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1387 cx.background_executor()
1388 .timer(Duration::from_millis(100))
1389 .await;
1390 this.update_in(cx, |this, window, cx| {
1391 if let Some(display) = window.display(cx)
1392 && let Ok(display_uuid) = display.uuid()
1393 {
1394 let window_bounds = window.inner_window_bounds();
1395 if let Some(database_id) = workspace_id {
1396 cx.background_executor()
1397 .spawn(DB.set_window_open_status(
1398 database_id,
1399 SerializedWindowBounds(window_bounds),
1400 display_uuid,
1401 ))
1402 .detach_and_log_err(cx);
1403 }
1404 }
1405 this.bounds_save_task_queued.take();
1406 })
1407 .ok();
1408 }));
1409 cx.notify();
1410 }),
1411 cx.observe_window_appearance(window, |_, window, cx| {
1412 let window_appearance = window.appearance();
1413
1414 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1415
1416 ThemeSettings::reload_current_theme(cx);
1417 ThemeSettings::reload_current_icon_theme(cx);
1418 }),
1419 cx.on_release(move |this, cx| {
1420 this.app_state.workspace_store.update(cx, move |store, _| {
1421 store.workspaces.remove(&window_handle.clone());
1422 })
1423 }),
1424 ];
1425
1426 cx.defer_in(window, |this, window, cx| {
1427 this.update_window_title(window, cx);
1428 this.show_initial_notifications(cx);
1429 });
1430 Workspace {
1431 weak_self: weak_handle.clone(),
1432 zoomed: None,
1433 zoomed_position: None,
1434 previous_dock_drag_coordinates: None,
1435 center: PaneGroup::new(center_pane.clone()),
1436 panes: vec![center_pane.clone()],
1437 panes_by_item: Default::default(),
1438 active_pane: center_pane.clone(),
1439 last_active_center_pane: Some(center_pane.downgrade()),
1440 last_active_view_id: None,
1441 status_bar,
1442 modal_layer,
1443 toast_layer,
1444 titlebar_item: None,
1445 notifications: Notifications::default(),
1446 suppressed_notifications: HashSet::default(),
1447 left_dock,
1448 bottom_dock,
1449 right_dock,
1450 project: project.clone(),
1451 follower_states: Default::default(),
1452 last_leaders_by_pane: Default::default(),
1453 dispatching_keystrokes: Default::default(),
1454 window_edited: false,
1455 last_window_title: None,
1456 dirty_items: Default::default(),
1457 active_call,
1458 database_id: workspace_id,
1459 app_state,
1460 _observe_current_user,
1461 _apply_leader_updates,
1462 _schedule_serialize_workspace: None,
1463 _schedule_serialize_ssh_paths: None,
1464 leader_updates_tx,
1465 _subscriptions: subscriptions,
1466 pane_history_timestamp,
1467 workspace_actions: Default::default(),
1468 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1469 bounds: Default::default(),
1470 centered_layout: false,
1471 bounds_save_task_queued: None,
1472 on_prompt_for_new_path: None,
1473 on_prompt_for_open_path: None,
1474 terminal_provider: None,
1475 debugger_provider: None,
1476 serializable_items_tx,
1477 _items_serializer,
1478 session_id: Some(session_id),
1479
1480 scheduled_tasks: Vec::new(),
1481 }
1482 }
1483
1484 pub fn new_local(
1485 abs_paths: Vec<PathBuf>,
1486 app_state: Arc<AppState>,
1487 requesting_window: Option<WindowHandle<Workspace>>,
1488 env: Option<HashMap<String, String>>,
1489 cx: &mut App,
1490 ) -> Task<
1491 anyhow::Result<(
1492 WindowHandle<Workspace>,
1493 Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
1494 )>,
1495 > {
1496 let project_handle = Project::local(
1497 app_state.client.clone(),
1498 app_state.node_runtime.clone(),
1499 app_state.user_store.clone(),
1500 app_state.languages.clone(),
1501 app_state.fs.clone(),
1502 env,
1503 cx,
1504 );
1505
1506 cx.spawn(async move |cx| {
1507 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1508 for path in abs_paths.into_iter() {
1509 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1510 paths_to_open.push(canonical)
1511 } else {
1512 paths_to_open.push(path)
1513 }
1514 }
1515
1516 let serialized_workspace =
1517 persistence::DB.workspace_for_roots(paths_to_open.as_slice());
1518
1519 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1520 paths_to_open = paths.paths().to_vec();
1521 if !paths.is_lexicographically_ordered() {
1522 project_handle
1523 .update(cx, |project, cx| {
1524 project.set_worktrees_reordered(true, cx);
1525 })
1526 .log_err();
1527 }
1528 }
1529
1530 // Get project paths for all of the abs_paths
1531 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1532 Vec::with_capacity(paths_to_open.len());
1533
1534 for path in paths_to_open.into_iter() {
1535 if let Some((_, project_entry)) = cx
1536 .update(|cx| {
1537 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1538 })?
1539 .await
1540 .log_err()
1541 {
1542 project_paths.push((path, Some(project_entry)));
1543 } else {
1544 project_paths.push((path, None));
1545 }
1546 }
1547
1548 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1549 serialized_workspace.id
1550 } else {
1551 DB.next_id().await.unwrap_or_else(|_| Default::default())
1552 };
1553
1554 let toolchains = DB.toolchains(workspace_id).await?;
1555
1556 for (toolchain, worktree_id, path) in toolchains {
1557 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1558 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1559 continue;
1560 }
1561
1562 project_handle
1563 .update(cx, |this, cx| {
1564 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1565 })?
1566 .await;
1567 }
1568 let window = if let Some(window) = requesting_window {
1569 let centered_layout = serialized_workspace
1570 .as_ref()
1571 .map(|w| w.centered_layout)
1572 .unwrap_or(false);
1573
1574 cx.update_window(window.into(), |_, window, cx| {
1575 window.replace_root(cx, |window, cx| {
1576 let mut workspace = Workspace::new(
1577 Some(workspace_id),
1578 project_handle.clone(),
1579 app_state.clone(),
1580 window,
1581 cx,
1582 );
1583
1584 workspace.centered_layout = centered_layout;
1585 workspace
1586 });
1587 })?;
1588 window
1589 } else {
1590 let window_bounds_override = window_bounds_env_override();
1591
1592 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1593 (Some(WindowBounds::Windowed(bounds)), None)
1594 } else {
1595 let restorable_bounds = serialized_workspace
1596 .as_ref()
1597 .and_then(|workspace| Some((workspace.display?, workspace.window_bounds?)))
1598 .or_else(|| {
1599 let (display, window_bounds) = DB.last_window().log_err()?;
1600 Some((display?, window_bounds?))
1601 });
1602
1603 if let Some((serialized_display, serialized_status)) = restorable_bounds {
1604 (Some(serialized_status.0), Some(serialized_display))
1605 } else {
1606 (None, None)
1607 }
1608 };
1609
1610 // Use the serialized workspace to construct the new window
1611 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx))?;
1612 options.window_bounds = window_bounds;
1613 let centered_layout = serialized_workspace
1614 .as_ref()
1615 .map(|w| w.centered_layout)
1616 .unwrap_or(false);
1617 cx.open_window(options, {
1618 let app_state = app_state.clone();
1619 let project_handle = project_handle.clone();
1620 move |window, cx| {
1621 cx.new(|cx| {
1622 let mut workspace = Workspace::new(
1623 Some(workspace_id),
1624 project_handle,
1625 app_state,
1626 window,
1627 cx,
1628 );
1629 workspace.centered_layout = centered_layout;
1630 workspace
1631 })
1632 }
1633 })?
1634 };
1635
1636 notify_if_database_failed(window, cx);
1637 let opened_items = window
1638 .update(cx, |_workspace, window, cx| {
1639 open_items(serialized_workspace, project_paths, window, cx)
1640 })?
1641 .await
1642 .unwrap_or_default();
1643
1644 window
1645 .update(cx, |workspace, window, cx| {
1646 window.activate_window();
1647 workspace.update_history(cx);
1648 })
1649 .log_err();
1650 Ok((window, opened_items))
1651 })
1652 }
1653
1654 pub fn weak_handle(&self) -> WeakEntity<Self> {
1655 self.weak_self.clone()
1656 }
1657
1658 pub fn left_dock(&self) -> &Entity<Dock> {
1659 &self.left_dock
1660 }
1661
1662 pub fn bottom_dock(&self) -> &Entity<Dock> {
1663 &self.bottom_dock
1664 }
1665
1666 pub fn set_bottom_dock_layout(
1667 &mut self,
1668 layout: BottomDockLayout,
1669 window: &mut Window,
1670 cx: &mut Context<Self>,
1671 ) {
1672 let fs = self.project().read(cx).fs();
1673 settings::update_settings_file::<WorkspaceSettings>(fs.clone(), cx, move |content, _cx| {
1674 content.bottom_dock_layout = Some(layout);
1675 });
1676
1677 cx.notify();
1678 self.serialize_workspace(window, cx);
1679 }
1680
1681 pub fn right_dock(&self) -> &Entity<Dock> {
1682 &self.right_dock
1683 }
1684
1685 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
1686 [&self.left_dock, &self.bottom_dock, &self.right_dock]
1687 }
1688
1689 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
1690 match position {
1691 DockPosition::Left => &self.left_dock,
1692 DockPosition::Bottom => &self.bottom_dock,
1693 DockPosition::Right => &self.right_dock,
1694 }
1695 }
1696
1697 pub fn is_edited(&self) -> bool {
1698 self.window_edited
1699 }
1700
1701 pub fn add_panel<T: Panel>(
1702 &mut self,
1703 panel: Entity<T>,
1704 window: &mut Window,
1705 cx: &mut Context<Self>,
1706 ) {
1707 let focus_handle = panel.panel_focus_handle(cx);
1708 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
1709 .detach();
1710
1711 let dock_position = panel.position(window, cx);
1712 let dock = self.dock_at_position(dock_position);
1713
1714 dock.update(cx, |dock, cx| {
1715 dock.add_panel(panel, self.weak_self.clone(), window, cx)
1716 });
1717 }
1718
1719 pub fn status_bar(&self) -> &Entity<StatusBar> {
1720 &self.status_bar
1721 }
1722
1723 pub fn app_state(&self) -> &Arc<AppState> {
1724 &self.app_state
1725 }
1726
1727 pub fn user_store(&self) -> &Entity<UserStore> {
1728 &self.app_state.user_store
1729 }
1730
1731 pub fn project(&self) -> &Entity<Project> {
1732 &self.project
1733 }
1734
1735 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
1736 let mut history: HashMap<EntityId, usize> = HashMap::default();
1737
1738 for pane_handle in &self.panes {
1739 let pane = pane_handle.read(cx);
1740
1741 for entry in pane.activation_history() {
1742 history.insert(
1743 entry.entity_id,
1744 history
1745 .get(&entry.entity_id)
1746 .cloned()
1747 .unwrap_or(0)
1748 .max(entry.timestamp),
1749 );
1750 }
1751 }
1752
1753 history
1754 }
1755
1756 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
1757 let mut recent_item: Option<Entity<T>> = None;
1758 let mut recent_timestamp = 0;
1759 for pane_handle in &self.panes {
1760 let pane = pane_handle.read(cx);
1761 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
1762 pane.items().map(|item| (item.item_id(), item)).collect();
1763 for entry in pane.activation_history() {
1764 if entry.timestamp > recent_timestamp
1765 && let Some(&item) = item_map.get(&entry.entity_id)
1766 && let Some(typed_item) = item.act_as::<T>(cx)
1767 {
1768 recent_timestamp = entry.timestamp;
1769 recent_item = Some(typed_item);
1770 }
1771 }
1772 }
1773 recent_item
1774 }
1775
1776 pub fn recent_navigation_history_iter(
1777 &self,
1778 cx: &App,
1779 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> {
1780 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
1781 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
1782
1783 for pane in &self.panes {
1784 let pane = pane.read(cx);
1785
1786 pane.nav_history()
1787 .for_each_entry(cx, |entry, (project_path, fs_path)| {
1788 if let Some(fs_path) = &fs_path {
1789 abs_paths_opened
1790 .entry(fs_path.clone())
1791 .or_default()
1792 .insert(project_path.clone());
1793 }
1794 let timestamp = entry.timestamp;
1795 match history.entry(project_path) {
1796 hash_map::Entry::Occupied(mut entry) => {
1797 let (_, old_timestamp) = entry.get();
1798 if ×tamp > old_timestamp {
1799 entry.insert((fs_path, timestamp));
1800 }
1801 }
1802 hash_map::Entry::Vacant(entry) => {
1803 entry.insert((fs_path, timestamp));
1804 }
1805 }
1806 });
1807
1808 if let Some(item) = pane.active_item()
1809 && let Some(project_path) = item.project_path(cx)
1810 {
1811 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
1812
1813 if let Some(fs_path) = &fs_path {
1814 abs_paths_opened
1815 .entry(fs_path.clone())
1816 .or_default()
1817 .insert(project_path.clone());
1818 }
1819
1820 history.insert(project_path, (fs_path, std::usize::MAX));
1821 }
1822 }
1823
1824 history
1825 .into_iter()
1826 .sorted_by_key(|(_, (_, order))| *order)
1827 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
1828 .rev()
1829 .filter(move |(history_path, abs_path)| {
1830 let latest_project_path_opened = abs_path
1831 .as_ref()
1832 .and_then(|abs_path| abs_paths_opened.get(abs_path))
1833 .and_then(|project_paths| {
1834 project_paths
1835 .iter()
1836 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
1837 });
1838
1839 latest_project_path_opened.is_none_or(|path| path == history_path)
1840 })
1841 }
1842
1843 pub fn recent_navigation_history(
1844 &self,
1845 limit: Option<usize>,
1846 cx: &App,
1847 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
1848 self.recent_navigation_history_iter(cx)
1849 .take(limit.unwrap_or(usize::MAX))
1850 .collect()
1851 }
1852
1853 fn navigate_history(
1854 &mut self,
1855 pane: WeakEntity<Pane>,
1856 mode: NavigationMode,
1857 window: &mut Window,
1858 cx: &mut Context<Workspace>,
1859 ) -> Task<Result<()>> {
1860 let to_load = if let Some(pane) = pane.upgrade() {
1861 pane.update(cx, |pane, cx| {
1862 window.focus(&pane.focus_handle(cx));
1863 loop {
1864 // Retrieve the weak item handle from the history.
1865 let entry = pane.nav_history_mut().pop(mode, cx)?;
1866
1867 // If the item is still present in this pane, then activate it.
1868 if let Some(index) = entry
1869 .item
1870 .upgrade()
1871 .and_then(|v| pane.index_for_item(v.as_ref()))
1872 {
1873 let prev_active_item_index = pane.active_item_index();
1874 pane.nav_history_mut().set_mode(mode);
1875 pane.activate_item(index, true, true, window, cx);
1876 pane.nav_history_mut().set_mode(NavigationMode::Normal);
1877
1878 let mut navigated = prev_active_item_index != pane.active_item_index();
1879 if let Some(data) = entry.data {
1880 navigated |= pane.active_item()?.navigate(data, window, cx);
1881 }
1882
1883 if navigated {
1884 break None;
1885 }
1886 } else {
1887 // If the item is no longer present in this pane, then retrieve its
1888 // path info in order to reopen it.
1889 break pane
1890 .nav_history()
1891 .path_for_item(entry.item.id())
1892 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
1893 }
1894 }
1895 })
1896 } else {
1897 None
1898 };
1899
1900 if let Some((project_path, abs_path, entry)) = to_load {
1901 // If the item was no longer present, then load it again from its previous path, first try the local path
1902 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
1903
1904 cx.spawn_in(window, async move |workspace, cx| {
1905 let open_by_project_path = open_by_project_path.await;
1906 let mut navigated = false;
1907 match open_by_project_path
1908 .with_context(|| format!("Navigating to {project_path:?}"))
1909 {
1910 Ok((project_entry_id, build_item)) => {
1911 let prev_active_item_id = pane.update(cx, |pane, _| {
1912 pane.nav_history_mut().set_mode(mode);
1913 pane.active_item().map(|p| p.item_id())
1914 })?;
1915
1916 pane.update_in(cx, |pane, window, cx| {
1917 let item = pane.open_item(
1918 project_entry_id,
1919 project_path,
1920 true,
1921 entry.is_preview,
1922 true,
1923 None,
1924 window, cx,
1925 build_item,
1926 );
1927 navigated |= Some(item.item_id()) != prev_active_item_id;
1928 pane.nav_history_mut().set_mode(NavigationMode::Normal);
1929 if let Some(data) = entry.data {
1930 navigated |= item.navigate(data, window, cx);
1931 }
1932 })?;
1933 }
1934 Err(open_by_project_path_e) => {
1935 // Fall back to opening by abs path, in case an external file was opened and closed,
1936 // and its worktree is now dropped
1937 if let Some(abs_path) = abs_path {
1938 let prev_active_item_id = pane.update(cx, |pane, _| {
1939 pane.nav_history_mut().set_mode(mode);
1940 pane.active_item().map(|p| p.item_id())
1941 })?;
1942 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
1943 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
1944 })?;
1945 match open_by_abs_path
1946 .await
1947 .with_context(|| format!("Navigating to {abs_path:?}"))
1948 {
1949 Ok(item) => {
1950 pane.update_in(cx, |pane, window, cx| {
1951 navigated |= Some(item.item_id()) != prev_active_item_id;
1952 pane.nav_history_mut().set_mode(NavigationMode::Normal);
1953 if let Some(data) = entry.data {
1954 navigated |= item.navigate(data, window, cx);
1955 }
1956 })?;
1957 }
1958 Err(open_by_abs_path_e) => {
1959 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
1960 }
1961 }
1962 }
1963 }
1964 }
1965
1966 if !navigated {
1967 workspace
1968 .update_in(cx, |workspace, window, cx| {
1969 Self::navigate_history(workspace, pane, mode, window, cx)
1970 })?
1971 .await?;
1972 }
1973
1974 Ok(())
1975 })
1976 } else {
1977 Task::ready(Ok(()))
1978 }
1979 }
1980
1981 pub fn go_back(
1982 &mut self,
1983 pane: WeakEntity<Pane>,
1984 window: &mut Window,
1985 cx: &mut Context<Workspace>,
1986 ) -> Task<Result<()>> {
1987 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
1988 }
1989
1990 pub fn go_forward(
1991 &mut self,
1992 pane: WeakEntity<Pane>,
1993 window: &mut Window,
1994 cx: &mut Context<Workspace>,
1995 ) -> Task<Result<()>> {
1996 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
1997 }
1998
1999 pub fn reopen_closed_item(
2000 &mut self,
2001 window: &mut Window,
2002 cx: &mut Context<Workspace>,
2003 ) -> Task<Result<()>> {
2004 self.navigate_history(
2005 self.active_pane().downgrade(),
2006 NavigationMode::ReopeningClosedItem,
2007 window,
2008 cx,
2009 )
2010 }
2011
2012 pub fn client(&self) -> &Arc<Client> {
2013 &self.app_state.client
2014 }
2015
2016 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2017 self.titlebar_item = Some(item);
2018 cx.notify();
2019 }
2020
2021 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2022 self.on_prompt_for_new_path = Some(prompt)
2023 }
2024
2025 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2026 self.on_prompt_for_open_path = Some(prompt)
2027 }
2028
2029 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2030 self.terminal_provider = Some(Box::new(provider));
2031 }
2032
2033 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2034 self.debugger_provider = Some(Arc::new(provider));
2035 }
2036
2037 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2038 self.debugger_provider.clone()
2039 }
2040
2041 pub fn prompt_for_open_path(
2042 &mut self,
2043 path_prompt_options: PathPromptOptions,
2044 lister: DirectoryLister,
2045 window: &mut Window,
2046 cx: &mut Context<Self>,
2047 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2048 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2049 let prompt = self.on_prompt_for_open_path.take().unwrap();
2050 let rx = prompt(self, lister, window, cx);
2051 self.on_prompt_for_open_path = Some(prompt);
2052 rx
2053 } else {
2054 let (tx, rx) = oneshot::channel();
2055 let abs_path = cx.prompt_for_paths(path_prompt_options);
2056
2057 cx.spawn_in(window, async move |workspace, cx| {
2058 let Ok(result) = abs_path.await else {
2059 return Ok(());
2060 };
2061
2062 match result {
2063 Ok(result) => {
2064 tx.send(result).ok();
2065 }
2066 Err(err) => {
2067 let rx = workspace.update_in(cx, |workspace, window, cx| {
2068 workspace.show_portal_error(err.to_string(), cx);
2069 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2070 let rx = prompt(workspace, lister, window, cx);
2071 workspace.on_prompt_for_open_path = Some(prompt);
2072 rx
2073 })?;
2074 if let Ok(path) = rx.await {
2075 tx.send(path).ok();
2076 }
2077 }
2078 };
2079 anyhow::Ok(())
2080 })
2081 .detach();
2082
2083 rx
2084 }
2085 }
2086
2087 pub fn prompt_for_new_path(
2088 &mut self,
2089 lister: DirectoryLister,
2090 suggested_name: Option<String>,
2091 window: &mut Window,
2092 cx: &mut Context<Self>,
2093 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2094 if self.project.read(cx).is_via_collab()
2095 || self.project.read(cx).is_via_remote_server()
2096 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2097 {
2098 let prompt = self.on_prompt_for_new_path.take().unwrap();
2099 let rx = prompt(self, lister, window, cx);
2100 self.on_prompt_for_new_path = Some(prompt);
2101 return rx;
2102 }
2103
2104 let (tx, rx) = oneshot::channel();
2105 cx.spawn_in(window, async move |workspace, cx| {
2106 let abs_path = workspace.update(cx, |workspace, cx| {
2107 let relative_to = workspace
2108 .most_recent_active_path(cx)
2109 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2110 .or_else(|| {
2111 let project = workspace.project.read(cx);
2112 project.visible_worktrees(cx).find_map(|worktree| {
2113 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2114 })
2115 })
2116 .or_else(std::env::home_dir)
2117 .unwrap_or_else(|| PathBuf::from(""));
2118 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2119 })?;
2120 let abs_path = match abs_path.await? {
2121 Ok(path) => path,
2122 Err(err) => {
2123 let rx = workspace.update_in(cx, |workspace, window, cx| {
2124 workspace.show_portal_error(err.to_string(), cx);
2125
2126 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2127 let rx = prompt(workspace, lister, window, cx);
2128 workspace.on_prompt_for_new_path = Some(prompt);
2129 rx
2130 })?;
2131 if let Ok(path) = rx.await {
2132 tx.send(path).ok();
2133 }
2134 return anyhow::Ok(());
2135 }
2136 };
2137
2138 tx.send(abs_path.map(|path| vec![path])).ok();
2139 anyhow::Ok(())
2140 })
2141 .detach();
2142
2143 rx
2144 }
2145
2146 pub fn titlebar_item(&self) -> Option<AnyView> {
2147 self.titlebar_item.clone()
2148 }
2149
2150 /// Call the given callback with a workspace whose project is local.
2151 ///
2152 /// If the given workspace has a local project, then it will be passed
2153 /// to the callback. Otherwise, a new empty window will be created.
2154 pub fn with_local_workspace<T, F>(
2155 &mut self,
2156 window: &mut Window,
2157 cx: &mut Context<Self>,
2158 callback: F,
2159 ) -> Task<Result<T>>
2160 where
2161 T: 'static,
2162 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2163 {
2164 if self.project.read(cx).is_local() {
2165 Task::ready(Ok(callback(self, window, cx)))
2166 } else {
2167 let env = self.project.read(cx).cli_environment(cx);
2168 let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, cx);
2169 cx.spawn_in(window, async move |_vh, cx| {
2170 let (workspace, _) = task.await?;
2171 workspace.update(cx, callback)
2172 })
2173 }
2174 }
2175
2176 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2177 self.project.read(cx).worktrees(cx)
2178 }
2179
2180 pub fn visible_worktrees<'a>(
2181 &self,
2182 cx: &'a App,
2183 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2184 self.project.read(cx).visible_worktrees(cx)
2185 }
2186
2187 #[cfg(any(test, feature = "test-support"))]
2188 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
2189 let futures = self
2190 .worktrees(cx)
2191 .filter_map(|worktree| worktree.read(cx).as_local())
2192 .map(|worktree| worktree.scan_complete())
2193 .collect::<Vec<_>>();
2194 async move {
2195 for future in futures {
2196 future.await;
2197 }
2198 }
2199 }
2200
2201 pub fn close_global(cx: &mut App) {
2202 cx.defer(|cx| {
2203 cx.windows().iter().find(|window| {
2204 window
2205 .update(cx, |_, window, _| {
2206 if window.is_window_active() {
2207 //This can only get called when the window's project connection has been lost
2208 //so we don't need to prompt the user for anything and instead just close the window
2209 window.remove_window();
2210 true
2211 } else {
2212 false
2213 }
2214 })
2215 .unwrap_or(false)
2216 });
2217 });
2218 }
2219
2220 pub fn close_window(&mut self, _: &CloseWindow, window: &mut Window, cx: &mut Context<Self>) {
2221 let prepare = self.prepare_to_close(CloseIntent::CloseWindow, window, cx);
2222 cx.spawn_in(window, async move |_, cx| {
2223 if prepare.await? {
2224 cx.update(|window, _cx| window.remove_window())?;
2225 }
2226 anyhow::Ok(())
2227 })
2228 .detach_and_log_err(cx)
2229 }
2230
2231 pub fn move_focused_panel_to_next_position(
2232 &mut self,
2233 _: &MoveFocusedPanelToNextPosition,
2234 window: &mut Window,
2235 cx: &mut Context<Self>,
2236 ) {
2237 let docks = self.all_docks();
2238 let active_dock = docks
2239 .into_iter()
2240 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
2241
2242 if let Some(dock) = active_dock {
2243 dock.update(cx, |dock, cx| {
2244 let active_panel = dock
2245 .active_panel()
2246 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
2247
2248 if let Some(panel) = active_panel {
2249 panel.move_to_next_position(window, cx);
2250 }
2251 })
2252 }
2253 }
2254
2255 pub fn prepare_to_close(
2256 &mut self,
2257 close_intent: CloseIntent,
2258 window: &mut Window,
2259 cx: &mut Context<Self>,
2260 ) -> Task<Result<bool>> {
2261 let active_call = self.active_call().cloned();
2262
2263 // On Linux and Windows, closing the last window should restore the last workspace.
2264 let save_last_workspace = cfg!(not(target_os = "macos"))
2265 && close_intent != CloseIntent::ReplaceWindow
2266 && cx.windows().len() == 1;
2267
2268 cx.spawn_in(window, async move |this, cx| {
2269 let workspace_count = cx.update(|_window, cx| {
2270 cx.windows()
2271 .iter()
2272 .filter(|window| window.downcast::<Workspace>().is_some())
2273 .count()
2274 })?;
2275
2276 if let Some(active_call) = active_call
2277 && workspace_count == 1
2278 && active_call.read_with(cx, |call, _| call.room().is_some())?
2279 {
2280 if close_intent == CloseIntent::CloseWindow {
2281 let answer = cx.update(|window, cx| {
2282 window.prompt(
2283 PromptLevel::Warning,
2284 "Do you want to leave the current call?",
2285 None,
2286 &["Close window and hang up", "Cancel"],
2287 cx,
2288 )
2289 })?;
2290
2291 if answer.await.log_err() == Some(1) {
2292 return anyhow::Ok(false);
2293 } else {
2294 active_call
2295 .update(cx, |call, cx| call.hang_up(cx))?
2296 .await
2297 .log_err();
2298 }
2299 }
2300 if close_intent == CloseIntent::ReplaceWindow {
2301 _ = active_call.update(cx, |this, cx| {
2302 let workspace = cx
2303 .windows()
2304 .iter()
2305 .filter_map(|window| window.downcast::<Workspace>())
2306 .next()
2307 .unwrap();
2308 let project = workspace.read(cx)?.project.clone();
2309 if project.read(cx).is_shared() {
2310 this.unshare_project(project, cx)?;
2311 }
2312 Ok::<_, anyhow::Error>(())
2313 })?;
2314 }
2315 }
2316
2317 let save_result = this
2318 .update_in(cx, |this, window, cx| {
2319 this.save_all_internal(SaveIntent::Close, window, cx)
2320 })?
2321 .await;
2322
2323 // If we're not quitting, but closing, we remove the workspace from
2324 // the current session.
2325 if close_intent != CloseIntent::Quit
2326 && !save_last_workspace
2327 && save_result.as_ref().is_ok_and(|&res| res)
2328 {
2329 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
2330 .await;
2331 }
2332
2333 save_result
2334 })
2335 }
2336
2337 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
2338 self.save_all_internal(
2339 action.save_intent.unwrap_or(SaveIntent::SaveAll),
2340 window,
2341 cx,
2342 )
2343 .detach_and_log_err(cx);
2344 }
2345
2346 fn send_keystrokes(
2347 &mut self,
2348 action: &SendKeystrokes,
2349 window: &mut Window,
2350 cx: &mut Context<Self>,
2351 ) {
2352 let keystrokes: Vec<Keystroke> = action
2353 .0
2354 .split(' ')
2355 .flat_map(|k| Keystroke::parse(k).log_err())
2356 .collect();
2357 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
2358 }
2359
2360 pub fn send_keystrokes_impl(
2361 &mut self,
2362 keystrokes: Vec<Keystroke>,
2363 window: &mut Window,
2364 cx: &mut Context<Self>,
2365 ) -> Shared<Task<()>> {
2366 let mut state = self.dispatching_keystrokes.borrow_mut();
2367 if !state.dispatched.insert(keystrokes.clone()) {
2368 cx.propagate();
2369 return state.task.clone().unwrap();
2370 }
2371
2372 state.queue.extend(keystrokes);
2373
2374 let keystrokes = self.dispatching_keystrokes.clone();
2375 if state.task.is_none() {
2376 state.task = Some(
2377 window
2378 .spawn(cx, async move |cx| {
2379 // limit to 100 keystrokes to avoid infinite recursion.
2380 for _ in 0..100 {
2381 let mut state = keystrokes.borrow_mut();
2382 let Some(keystroke) = state.queue.pop_front() else {
2383 state.dispatched.clear();
2384 state.task.take();
2385 return;
2386 };
2387 drop(state);
2388 cx.update(|window, cx| {
2389 let focused = window.focused(cx);
2390 window.dispatch_keystroke(keystroke.clone(), cx);
2391 if window.focused(cx) != focused {
2392 // dispatch_keystroke may cause the focus to change.
2393 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
2394 // And we need that to happen before the next keystroke to keep vim mode happy...
2395 // (Note that the tests always do this implicitly, so you must manually test with something like:
2396 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
2397 // )
2398 window.draw(cx).clear();
2399 }
2400 })
2401 .ok();
2402 }
2403
2404 *keystrokes.borrow_mut() = Default::default();
2405 log::error!("over 100 keystrokes passed to send_keystrokes");
2406 })
2407 .shared(),
2408 );
2409 }
2410 state.task.clone().unwrap()
2411 }
2412
2413 fn save_all_internal(
2414 &mut self,
2415 mut save_intent: SaveIntent,
2416 window: &mut Window,
2417 cx: &mut Context<Self>,
2418 ) -> Task<Result<bool>> {
2419 if self.project.read(cx).is_disconnected(cx) {
2420 return Task::ready(Ok(true));
2421 }
2422 let dirty_items = self
2423 .panes
2424 .iter()
2425 .flat_map(|pane| {
2426 pane.read(cx).items().filter_map(|item| {
2427 if item.is_dirty(cx) {
2428 item.tab_content_text(0, cx);
2429 Some((pane.downgrade(), item.boxed_clone()))
2430 } else {
2431 None
2432 }
2433 })
2434 })
2435 .collect::<Vec<_>>();
2436
2437 let project = self.project.clone();
2438 cx.spawn_in(window, async move |workspace, cx| {
2439 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
2440 let (serialize_tasks, remaining_dirty_items) =
2441 workspace.update_in(cx, |workspace, window, cx| {
2442 let mut remaining_dirty_items = Vec::new();
2443 let mut serialize_tasks = Vec::new();
2444 for (pane, item) in dirty_items {
2445 if let Some(task) = item
2446 .to_serializable_item_handle(cx)
2447 .and_then(|handle| handle.serialize(workspace, true, window, cx))
2448 {
2449 serialize_tasks.push(task);
2450 } else {
2451 remaining_dirty_items.push((pane, item));
2452 }
2453 }
2454 (serialize_tasks, remaining_dirty_items)
2455 })?;
2456
2457 futures::future::try_join_all(serialize_tasks).await?;
2458
2459 if remaining_dirty_items.len() > 1 {
2460 let answer = workspace.update_in(cx, |_, window, cx| {
2461 let detail = Pane::file_names_for_prompt(
2462 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
2463 cx,
2464 );
2465 window.prompt(
2466 PromptLevel::Warning,
2467 "Do you want to save all changes in the following files?",
2468 Some(&detail),
2469 &["Save all", "Discard all", "Cancel"],
2470 cx,
2471 )
2472 })?;
2473 match answer.await.log_err() {
2474 Some(0) => save_intent = SaveIntent::SaveAll,
2475 Some(1) => save_intent = SaveIntent::Skip,
2476 Some(2) => return Ok(false),
2477 _ => {}
2478 }
2479 }
2480
2481 remaining_dirty_items
2482 } else {
2483 dirty_items
2484 };
2485
2486 for (pane, item) in dirty_items {
2487 let (singleton, project_entry_ids) =
2488 cx.update(|_, cx| (item.is_singleton(cx), item.project_entry_ids(cx)))?;
2489 if (singleton || !project_entry_ids.is_empty())
2490 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
2491 {
2492 return Ok(false);
2493 }
2494 }
2495 Ok(true)
2496 })
2497 }
2498
2499 pub fn open_workspace_for_paths(
2500 &mut self,
2501 replace_current_window: bool,
2502 paths: Vec<PathBuf>,
2503 window: &mut Window,
2504 cx: &mut Context<Self>,
2505 ) -> Task<Result<()>> {
2506 let window_handle = window.window_handle().downcast::<Self>();
2507 let is_remote = self.project.read(cx).is_via_collab();
2508 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
2509 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
2510
2511 let window_to_replace = if replace_current_window {
2512 window_handle
2513 } else if is_remote || has_worktree || has_dirty_items {
2514 None
2515 } else {
2516 window_handle
2517 };
2518 let app_state = self.app_state.clone();
2519
2520 cx.spawn(async move |_, cx| {
2521 cx.update(|cx| {
2522 open_paths(
2523 &paths,
2524 app_state,
2525 OpenOptions {
2526 replace_window: window_to_replace,
2527 ..Default::default()
2528 },
2529 cx,
2530 )
2531 })?
2532 .await?;
2533 Ok(())
2534 })
2535 }
2536
2537 #[allow(clippy::type_complexity)]
2538 pub fn open_paths(
2539 &mut self,
2540 mut abs_paths: Vec<PathBuf>,
2541 options: OpenOptions,
2542 pane: Option<WeakEntity<Pane>>,
2543 window: &mut Window,
2544 cx: &mut Context<Self>,
2545 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
2546 let fs = self.app_state.fs.clone();
2547
2548 // Sort the paths to ensure we add worktrees for parents before their children.
2549 abs_paths.sort_unstable();
2550 cx.spawn_in(window, async move |this, cx| {
2551 let mut tasks = Vec::with_capacity(abs_paths.len());
2552
2553 for abs_path in &abs_paths {
2554 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
2555 OpenVisible::All => Some(true),
2556 OpenVisible::None => Some(false),
2557 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
2558 Some(Some(metadata)) => Some(!metadata.is_dir),
2559 Some(None) => Some(true),
2560 None => None,
2561 },
2562 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
2563 Some(Some(metadata)) => Some(metadata.is_dir),
2564 Some(None) => Some(false),
2565 None => None,
2566 },
2567 };
2568 let project_path = match visible {
2569 Some(visible) => match this
2570 .update(cx, |this, cx| {
2571 Workspace::project_path_for_path(
2572 this.project.clone(),
2573 abs_path,
2574 visible,
2575 cx,
2576 )
2577 })
2578 .log_err()
2579 {
2580 Some(project_path) => project_path.await.log_err(),
2581 None => None,
2582 },
2583 None => None,
2584 };
2585
2586 let this = this.clone();
2587 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
2588 let fs = fs.clone();
2589 let pane = pane.clone();
2590 let task = cx.spawn(async move |cx| {
2591 let (worktree, project_path) = project_path?;
2592 if fs.is_dir(&abs_path).await {
2593 this.update(cx, |workspace, cx| {
2594 let worktree = worktree.read(cx);
2595 let worktree_abs_path = worktree.abs_path();
2596 let entry_id = if abs_path.as_ref() == worktree_abs_path.as_ref() {
2597 worktree.root_entry()
2598 } else {
2599 abs_path
2600 .strip_prefix(worktree_abs_path.as_ref())
2601 .ok()
2602 .and_then(|relative_path| {
2603 worktree.entry_for_path(relative_path)
2604 })
2605 }
2606 .map(|entry| entry.id);
2607 if let Some(entry_id) = entry_id {
2608 workspace.project.update(cx, |_, cx| {
2609 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
2610 })
2611 }
2612 })
2613 .ok()?;
2614 None
2615 } else {
2616 Some(
2617 this.update_in(cx, |this, window, cx| {
2618 this.open_path(
2619 project_path,
2620 pane,
2621 options.focus.unwrap_or(true),
2622 window,
2623 cx,
2624 )
2625 })
2626 .ok()?
2627 .await,
2628 )
2629 }
2630 });
2631 tasks.push(task);
2632 }
2633
2634 futures::future::join_all(tasks).await
2635 })
2636 }
2637
2638 pub fn open_resolved_path(
2639 &mut self,
2640 path: ResolvedPath,
2641 window: &mut Window,
2642 cx: &mut Context<Self>,
2643 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
2644 match path {
2645 ResolvedPath::ProjectPath { project_path, .. } => {
2646 self.open_path(project_path, None, true, window, cx)
2647 }
2648 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
2649 path,
2650 OpenOptions {
2651 visible: Some(OpenVisible::None),
2652 ..Default::default()
2653 },
2654 window,
2655 cx,
2656 ),
2657 }
2658 }
2659
2660 pub fn absolute_path_of_worktree(
2661 &self,
2662 worktree_id: WorktreeId,
2663 cx: &mut Context<Self>,
2664 ) -> Option<PathBuf> {
2665 self.project
2666 .read(cx)
2667 .worktree_for_id(worktree_id, cx)
2668 // TODO: use `abs_path` or `root_dir`
2669 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
2670 }
2671
2672 fn add_folder_to_project(
2673 &mut self,
2674 _: &AddFolderToProject,
2675 window: &mut Window,
2676 cx: &mut Context<Self>,
2677 ) {
2678 let project = self.project.read(cx);
2679 if project.is_via_collab() {
2680 self.show_error(
2681 &anyhow!("You cannot add folders to someone else's project"),
2682 cx,
2683 );
2684 return;
2685 }
2686 let paths = self.prompt_for_open_path(
2687 PathPromptOptions {
2688 files: false,
2689 directories: true,
2690 multiple: true,
2691 prompt: None,
2692 },
2693 DirectoryLister::Project(self.project.clone()),
2694 window,
2695 cx,
2696 );
2697 cx.spawn_in(window, async move |this, cx| {
2698 if let Some(paths) = paths.await.log_err().flatten() {
2699 let results = this
2700 .update_in(cx, |this, window, cx| {
2701 this.open_paths(
2702 paths,
2703 OpenOptions {
2704 visible: Some(OpenVisible::All),
2705 ..Default::default()
2706 },
2707 None,
2708 window,
2709 cx,
2710 )
2711 })?
2712 .await;
2713 for result in results.into_iter().flatten() {
2714 result.log_err();
2715 }
2716 }
2717 anyhow::Ok(())
2718 })
2719 .detach_and_log_err(cx);
2720 }
2721
2722 pub fn project_path_for_path(
2723 project: Entity<Project>,
2724 abs_path: &Path,
2725 visible: bool,
2726 cx: &mut App,
2727 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
2728 let entry = project.update(cx, |project, cx| {
2729 project.find_or_create_worktree(abs_path, visible, cx)
2730 });
2731 cx.spawn(async move |cx| {
2732 let (worktree, path) = entry.await?;
2733 let worktree_id = worktree.read_with(cx, |t, _| t.id())?;
2734 Ok((
2735 worktree,
2736 ProjectPath {
2737 worktree_id,
2738 path: path.into(),
2739 },
2740 ))
2741 })
2742 }
2743
2744 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
2745 self.panes.iter().flat_map(|pane| pane.read(cx).items())
2746 }
2747
2748 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
2749 self.items_of_type(cx).max_by_key(|item| item.item_id())
2750 }
2751
2752 pub fn items_of_type<'a, T: Item>(
2753 &'a self,
2754 cx: &'a App,
2755 ) -> impl 'a + Iterator<Item = Entity<T>> {
2756 self.panes
2757 .iter()
2758 .flat_map(|pane| pane.read(cx).items_of_type())
2759 }
2760
2761 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
2762 self.active_pane().read(cx).active_item()
2763 }
2764
2765 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
2766 let item = self.active_item(cx)?;
2767 item.to_any().downcast::<I>().ok()
2768 }
2769
2770 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
2771 self.active_item(cx).and_then(|item| item.project_path(cx))
2772 }
2773
2774 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
2775 self.recent_navigation_history_iter(cx)
2776 .filter_map(|(path, abs_path)| {
2777 let worktree = self
2778 .project
2779 .read(cx)
2780 .worktree_for_id(path.worktree_id, cx)?;
2781 if worktree.read(cx).is_visible() {
2782 abs_path
2783 } else {
2784 None
2785 }
2786 })
2787 .next()
2788 }
2789
2790 pub fn save_active_item(
2791 &mut self,
2792 save_intent: SaveIntent,
2793 window: &mut Window,
2794 cx: &mut App,
2795 ) -> Task<Result<()>> {
2796 let project = self.project.clone();
2797 let pane = self.active_pane();
2798 let item = pane.read(cx).active_item();
2799 let pane = pane.downgrade();
2800
2801 window.spawn(cx, async move |cx| {
2802 if let Some(item) = item {
2803 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
2804 .await
2805 .map(|_| ())
2806 } else {
2807 Ok(())
2808 }
2809 })
2810 }
2811
2812 pub fn close_inactive_items_and_panes(
2813 &mut self,
2814 action: &CloseInactiveTabsAndPanes,
2815 window: &mut Window,
2816 cx: &mut Context<Self>,
2817 ) {
2818 if let Some(task) = self.close_all_internal(
2819 true,
2820 action.save_intent.unwrap_or(SaveIntent::Close),
2821 window,
2822 cx,
2823 ) {
2824 task.detach_and_log_err(cx)
2825 }
2826 }
2827
2828 pub fn close_all_items_and_panes(
2829 &mut self,
2830 action: &CloseAllItemsAndPanes,
2831 window: &mut Window,
2832 cx: &mut Context<Self>,
2833 ) {
2834 if let Some(task) = self.close_all_internal(
2835 false,
2836 action.save_intent.unwrap_or(SaveIntent::Close),
2837 window,
2838 cx,
2839 ) {
2840 task.detach_and_log_err(cx)
2841 }
2842 }
2843
2844 fn close_all_internal(
2845 &mut self,
2846 retain_active_pane: bool,
2847 save_intent: SaveIntent,
2848 window: &mut Window,
2849 cx: &mut Context<Self>,
2850 ) -> Option<Task<Result<()>>> {
2851 let current_pane = self.active_pane();
2852
2853 let mut tasks = Vec::new();
2854
2855 if retain_active_pane {
2856 let current_pane_close = current_pane.update(cx, |pane, cx| {
2857 pane.close_other_items(
2858 &CloseOtherItems {
2859 save_intent: None,
2860 close_pinned: false,
2861 },
2862 None,
2863 window,
2864 cx,
2865 )
2866 });
2867
2868 tasks.push(current_pane_close);
2869 }
2870
2871 for pane in self.panes() {
2872 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
2873 continue;
2874 }
2875
2876 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
2877 pane.close_all_items(
2878 &CloseAllItems {
2879 save_intent: Some(save_intent),
2880 close_pinned: false,
2881 },
2882 window,
2883 cx,
2884 )
2885 });
2886
2887 tasks.push(close_pane_items)
2888 }
2889
2890 if tasks.is_empty() {
2891 None
2892 } else {
2893 Some(cx.spawn_in(window, async move |_, _| {
2894 for task in tasks {
2895 task.await?
2896 }
2897 Ok(())
2898 }))
2899 }
2900 }
2901
2902 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
2903 self.dock_at_position(position).read(cx).is_open()
2904 }
2905
2906 pub fn toggle_dock(
2907 &mut self,
2908 dock_side: DockPosition,
2909 window: &mut Window,
2910 cx: &mut Context<Self>,
2911 ) {
2912 let dock = self.dock_at_position(dock_side);
2913 let mut focus_center = false;
2914 let mut reveal_dock = false;
2915 dock.update(cx, |dock, cx| {
2916 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
2917 let was_visible = dock.is_open() && !other_is_zoomed;
2918 dock.set_open(!was_visible, window, cx);
2919
2920 if dock.active_panel().is_none() {
2921 let Some(panel_ix) = dock
2922 .first_enabled_panel_idx(cx)
2923 .log_with_level(log::Level::Info)
2924 else {
2925 return;
2926 };
2927 dock.activate_panel(panel_ix, window, cx);
2928 }
2929
2930 if let Some(active_panel) = dock.active_panel() {
2931 if was_visible {
2932 if active_panel
2933 .panel_focus_handle(cx)
2934 .contains_focused(window, cx)
2935 {
2936 focus_center = true;
2937 }
2938 } else {
2939 let focus_handle = &active_panel.panel_focus_handle(cx);
2940 window.focus(focus_handle);
2941 reveal_dock = true;
2942 }
2943 }
2944 });
2945
2946 if reveal_dock {
2947 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
2948 }
2949
2950 if focus_center {
2951 self.active_pane
2952 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)))
2953 }
2954
2955 cx.notify();
2956 self.serialize_workspace(window, cx);
2957 }
2958
2959 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
2960 self.all_docks().into_iter().find(|&dock| {
2961 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
2962 })
2963 }
2964
2965 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
2966 if let Some(dock) = self.active_dock(window, cx) {
2967 dock.update(cx, |dock, cx| {
2968 dock.set_open(false, window, cx);
2969 });
2970 return true;
2971 }
2972 false
2973 }
2974
2975 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2976 for dock in self.all_docks() {
2977 dock.update(cx, |dock, cx| {
2978 dock.set_open(false, window, cx);
2979 });
2980 }
2981
2982 cx.focus_self(window);
2983 cx.notify();
2984 self.serialize_workspace(window, cx);
2985 }
2986
2987 /// Transfer focus to the panel of the given type.
2988 pub fn focus_panel<T: Panel>(
2989 &mut self,
2990 window: &mut Window,
2991 cx: &mut Context<Self>,
2992 ) -> Option<Entity<T>> {
2993 let panel = self.focus_or_unfocus_panel::<T>(window, cx, |_, _, _| true)?;
2994 panel.to_any().downcast().ok()
2995 }
2996
2997 /// Focus the panel of the given type if it isn't already focused. If it is
2998 /// already focused, then transfer focus back to the workspace center.
2999 pub fn toggle_panel_focus<T: Panel>(
3000 &mut self,
3001 window: &mut Window,
3002 cx: &mut Context<Self>,
3003 ) -> bool {
3004 let mut did_focus_panel = false;
3005 self.focus_or_unfocus_panel::<T>(window, cx, |panel, window, cx| {
3006 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
3007 did_focus_panel
3008 });
3009 did_focus_panel
3010 }
3011
3012 pub fn activate_panel_for_proto_id(
3013 &mut self,
3014 panel_id: PanelId,
3015 window: &mut Window,
3016 cx: &mut Context<Self>,
3017 ) -> Option<Arc<dyn PanelHandle>> {
3018 let mut panel = None;
3019 for dock in self.all_docks() {
3020 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
3021 panel = dock.update(cx, |dock, cx| {
3022 dock.activate_panel(panel_index, window, cx);
3023 dock.set_open(true, window, cx);
3024 dock.active_panel().cloned()
3025 });
3026 break;
3027 }
3028 }
3029
3030 if panel.is_some() {
3031 cx.notify();
3032 self.serialize_workspace(window, cx);
3033 }
3034
3035 panel
3036 }
3037
3038 /// Focus or unfocus the given panel type, depending on the given callback.
3039 fn focus_or_unfocus_panel<T: Panel>(
3040 &mut self,
3041 window: &mut Window,
3042 cx: &mut Context<Self>,
3043 mut should_focus: impl FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
3044 ) -> Option<Arc<dyn PanelHandle>> {
3045 let mut result_panel = None;
3046 let mut serialize = false;
3047 for dock in self.all_docks() {
3048 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3049 let mut focus_center = false;
3050 let panel = dock.update(cx, |dock, cx| {
3051 dock.activate_panel(panel_index, window, cx);
3052
3053 let panel = dock.active_panel().cloned();
3054 if let Some(panel) = panel.as_ref() {
3055 if should_focus(&**panel, window, cx) {
3056 dock.set_open(true, window, cx);
3057 panel.panel_focus_handle(cx).focus(window);
3058 } else {
3059 focus_center = true;
3060 }
3061 }
3062 panel
3063 });
3064
3065 if focus_center {
3066 self.active_pane
3067 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)))
3068 }
3069
3070 result_panel = panel;
3071 serialize = true;
3072 break;
3073 }
3074 }
3075
3076 if serialize {
3077 self.serialize_workspace(window, cx);
3078 }
3079
3080 cx.notify();
3081 result_panel
3082 }
3083
3084 /// Open the panel of the given type
3085 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3086 for dock in self.all_docks() {
3087 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3088 dock.update(cx, |dock, cx| {
3089 dock.activate_panel(panel_index, window, cx);
3090 dock.set_open(true, window, cx);
3091 });
3092 }
3093 }
3094 }
3095
3096 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
3097 for dock in self.all_docks().iter() {
3098 dock.update(cx, |dock, cx| {
3099 if dock.panel::<T>().is_some() {
3100 dock.set_open(false, window, cx)
3101 }
3102 })
3103 }
3104 }
3105
3106 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
3107 self.all_docks()
3108 .iter()
3109 .find_map(|dock| dock.read(cx).panel::<T>())
3110 }
3111
3112 fn dismiss_zoomed_items_to_reveal(
3113 &mut self,
3114 dock_to_reveal: Option<DockPosition>,
3115 window: &mut Window,
3116 cx: &mut Context<Self>,
3117 ) {
3118 // If a center pane is zoomed, unzoom it.
3119 for pane in &self.panes {
3120 if pane != &self.active_pane || dock_to_reveal.is_some() {
3121 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
3122 }
3123 }
3124
3125 // If another dock is zoomed, hide it.
3126 let mut focus_center = false;
3127 for dock in self.all_docks() {
3128 dock.update(cx, |dock, cx| {
3129 if Some(dock.position()) != dock_to_reveal
3130 && let Some(panel) = dock.active_panel()
3131 && panel.is_zoomed(window, cx)
3132 {
3133 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
3134 dock.set_open(false, window, cx);
3135 }
3136 });
3137 }
3138
3139 if focus_center {
3140 self.active_pane
3141 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)))
3142 }
3143
3144 if self.zoomed_position != dock_to_reveal {
3145 self.zoomed = None;
3146 self.zoomed_position = None;
3147 cx.emit(Event::ZoomChanged);
3148 }
3149
3150 cx.notify();
3151 }
3152
3153 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
3154 let pane = cx.new(|cx| {
3155 let mut pane = Pane::new(
3156 self.weak_handle(),
3157 self.project.clone(),
3158 self.pane_history_timestamp.clone(),
3159 None,
3160 NewFile.boxed_clone(),
3161 window,
3162 cx,
3163 );
3164 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
3165 pane
3166 });
3167 cx.subscribe_in(&pane, window, Self::handle_pane_event)
3168 .detach();
3169 self.panes.push(pane.clone());
3170
3171 window.focus(&pane.focus_handle(cx));
3172
3173 cx.emit(Event::PaneAdded(pane.clone()));
3174 pane
3175 }
3176
3177 pub fn add_item_to_center(
3178 &mut self,
3179 item: Box<dyn ItemHandle>,
3180 window: &mut Window,
3181 cx: &mut Context<Self>,
3182 ) -> bool {
3183 if let Some(center_pane) = self.last_active_center_pane.clone() {
3184 if let Some(center_pane) = center_pane.upgrade() {
3185 center_pane.update(cx, |pane, cx| {
3186 pane.add_item(item, true, true, None, window, cx)
3187 });
3188 true
3189 } else {
3190 false
3191 }
3192 } else {
3193 false
3194 }
3195 }
3196
3197 pub fn add_item_to_active_pane(
3198 &mut self,
3199 item: Box<dyn ItemHandle>,
3200 destination_index: Option<usize>,
3201 focus_item: bool,
3202 window: &mut Window,
3203 cx: &mut App,
3204 ) {
3205 self.add_item(
3206 self.active_pane.clone(),
3207 item,
3208 destination_index,
3209 false,
3210 focus_item,
3211 window,
3212 cx,
3213 )
3214 }
3215
3216 pub fn add_item(
3217 &mut self,
3218 pane: Entity<Pane>,
3219 item: Box<dyn ItemHandle>,
3220 destination_index: Option<usize>,
3221 activate_pane: bool,
3222 focus_item: bool,
3223 window: &mut Window,
3224 cx: &mut App,
3225 ) {
3226 if let Some(text) = item.telemetry_event_text(cx) {
3227 telemetry::event!(text);
3228 }
3229
3230 pane.update(cx, |pane, cx| {
3231 pane.add_item(
3232 item,
3233 activate_pane,
3234 focus_item,
3235 destination_index,
3236 window,
3237 cx,
3238 )
3239 });
3240 }
3241
3242 pub fn split_item(
3243 &mut self,
3244 split_direction: SplitDirection,
3245 item: Box<dyn ItemHandle>,
3246 window: &mut Window,
3247 cx: &mut Context<Self>,
3248 ) {
3249 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
3250 self.add_item(new_pane, item, None, true, true, window, cx);
3251 }
3252
3253 pub fn open_abs_path(
3254 &mut self,
3255 abs_path: PathBuf,
3256 options: OpenOptions,
3257 window: &mut Window,
3258 cx: &mut Context<Self>,
3259 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3260 cx.spawn_in(window, async move |workspace, cx| {
3261 let open_paths_task_result = workspace
3262 .update_in(cx, |workspace, window, cx| {
3263 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
3264 })
3265 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
3266 .await;
3267 anyhow::ensure!(
3268 open_paths_task_result.len() == 1,
3269 "open abs path {abs_path:?} task returned incorrect number of results"
3270 );
3271 match open_paths_task_result
3272 .into_iter()
3273 .next()
3274 .expect("ensured single task result")
3275 {
3276 Some(open_result) => {
3277 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
3278 }
3279 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
3280 }
3281 })
3282 }
3283
3284 pub fn split_abs_path(
3285 &mut self,
3286 abs_path: PathBuf,
3287 visible: bool,
3288 window: &mut Window,
3289 cx: &mut Context<Self>,
3290 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3291 let project_path_task =
3292 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
3293 cx.spawn_in(window, async move |this, cx| {
3294 let (_, path) = project_path_task.await?;
3295 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
3296 .await
3297 })
3298 }
3299
3300 pub fn open_path(
3301 &mut self,
3302 path: impl Into<ProjectPath>,
3303 pane: Option<WeakEntity<Pane>>,
3304 focus_item: bool,
3305 window: &mut Window,
3306 cx: &mut App,
3307 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3308 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
3309 }
3310
3311 pub fn open_path_preview(
3312 &mut self,
3313 path: impl Into<ProjectPath>,
3314 pane: Option<WeakEntity<Pane>>,
3315 focus_item: bool,
3316 allow_preview: bool,
3317 activate: bool,
3318 window: &mut Window,
3319 cx: &mut App,
3320 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3321 let pane = pane.unwrap_or_else(|| {
3322 self.last_active_center_pane.clone().unwrap_or_else(|| {
3323 self.panes
3324 .first()
3325 .expect("There must be an active pane")
3326 .downgrade()
3327 })
3328 });
3329
3330 let project_path = path.into();
3331 let task = self.load_path(project_path.clone(), window, cx);
3332 window.spawn(cx, async move |cx| {
3333 let (project_entry_id, build_item) = task.await?;
3334
3335 pane.update_in(cx, |pane, window, cx| {
3336 pane.open_item(
3337 project_entry_id,
3338 project_path,
3339 focus_item,
3340 allow_preview,
3341 activate,
3342 None,
3343 window,
3344 cx,
3345 build_item,
3346 )
3347 })
3348 })
3349 }
3350
3351 pub fn split_path(
3352 &mut self,
3353 path: impl Into<ProjectPath>,
3354 window: &mut Window,
3355 cx: &mut Context<Self>,
3356 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3357 self.split_path_preview(path, false, None, window, cx)
3358 }
3359
3360 pub fn split_path_preview(
3361 &mut self,
3362 path: impl Into<ProjectPath>,
3363 allow_preview: bool,
3364 split_direction: Option<SplitDirection>,
3365 window: &mut Window,
3366 cx: &mut Context<Self>,
3367 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3368 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
3369 self.panes
3370 .first()
3371 .expect("There must be an active pane")
3372 .downgrade()
3373 });
3374
3375 if let Member::Pane(center_pane) = &self.center.root
3376 && center_pane.read(cx).items_len() == 0
3377 {
3378 return self.open_path(path, Some(pane), true, window, cx);
3379 }
3380
3381 let project_path = path.into();
3382 let task = self.load_path(project_path.clone(), window, cx);
3383 cx.spawn_in(window, async move |this, cx| {
3384 let (project_entry_id, build_item) = task.await?;
3385 this.update_in(cx, move |this, window, cx| -> Option<_> {
3386 let pane = pane.upgrade()?;
3387 let new_pane = this.split_pane(
3388 pane,
3389 split_direction.unwrap_or(SplitDirection::Right),
3390 window,
3391 cx,
3392 );
3393 new_pane.update(cx, |new_pane, cx| {
3394 Some(new_pane.open_item(
3395 project_entry_id,
3396 project_path,
3397 true,
3398 allow_preview,
3399 true,
3400 None,
3401 window,
3402 cx,
3403 build_item,
3404 ))
3405 })
3406 })
3407 .map(|option| option.context("pane was dropped"))?
3408 })
3409 }
3410
3411 fn load_path(
3412 &mut self,
3413 path: ProjectPath,
3414 window: &mut Window,
3415 cx: &mut App,
3416 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
3417 let registry = cx.default_global::<ProjectItemRegistry>().clone();
3418 registry.open_path(self.project(), &path, window, cx)
3419 }
3420
3421 pub fn find_project_item<T>(
3422 &self,
3423 pane: &Entity<Pane>,
3424 project_item: &Entity<T::Item>,
3425 cx: &App,
3426 ) -> Option<Entity<T>>
3427 where
3428 T: ProjectItem,
3429 {
3430 use project::ProjectItem as _;
3431 let project_item = project_item.read(cx);
3432 let entry_id = project_item.entry_id(cx);
3433 let project_path = project_item.project_path(cx);
3434
3435 let mut item = None;
3436 if let Some(entry_id) = entry_id {
3437 item = pane.read(cx).item_for_entry(entry_id, cx);
3438 }
3439 if item.is_none()
3440 && let Some(project_path) = project_path
3441 {
3442 item = pane.read(cx).item_for_path(project_path, cx);
3443 }
3444
3445 item.and_then(|item| item.downcast::<T>())
3446 }
3447
3448 pub fn is_project_item_open<T>(
3449 &self,
3450 pane: &Entity<Pane>,
3451 project_item: &Entity<T::Item>,
3452 cx: &App,
3453 ) -> bool
3454 where
3455 T: ProjectItem,
3456 {
3457 self.find_project_item::<T>(pane, project_item, cx)
3458 .is_some()
3459 }
3460
3461 pub fn open_project_item<T>(
3462 &mut self,
3463 pane: Entity<Pane>,
3464 project_item: Entity<T::Item>,
3465 activate_pane: bool,
3466 focus_item: bool,
3467 window: &mut Window,
3468 cx: &mut Context<Self>,
3469 ) -> Entity<T>
3470 where
3471 T: ProjectItem,
3472 {
3473 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
3474 self.activate_item(&item, activate_pane, focus_item, window, cx);
3475 return item;
3476 }
3477
3478 let item = pane.update(cx, |pane, cx| {
3479 cx.new(|cx| {
3480 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
3481 })
3482 });
3483 let item_id = item.item_id();
3484 let mut destination_index = None;
3485 pane.update(cx, |pane, cx| {
3486 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation
3487 && let Some(preview_item_id) = pane.preview_item_id()
3488 && preview_item_id != item_id
3489 {
3490 destination_index = pane.close_current_preview_item(window, cx);
3491 }
3492 pane.set_preview_item_id(Some(item.item_id()), cx)
3493 });
3494
3495 self.add_item(
3496 pane,
3497 Box::new(item.clone()),
3498 destination_index,
3499 activate_pane,
3500 focus_item,
3501 window,
3502 cx,
3503 );
3504 item
3505 }
3506
3507 pub fn open_shared_screen(
3508 &mut self,
3509 peer_id: PeerId,
3510 window: &mut Window,
3511 cx: &mut Context<Self>,
3512 ) {
3513 if let Some(shared_screen) =
3514 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
3515 {
3516 self.active_pane.update(cx, |pane, cx| {
3517 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
3518 });
3519 }
3520 }
3521
3522 pub fn activate_item(
3523 &mut self,
3524 item: &dyn ItemHandle,
3525 activate_pane: bool,
3526 focus_item: bool,
3527 window: &mut Window,
3528 cx: &mut App,
3529 ) -> bool {
3530 let result = self.panes.iter().find_map(|pane| {
3531 pane.read(cx)
3532 .index_for_item(item)
3533 .map(|ix| (pane.clone(), ix))
3534 });
3535 if let Some((pane, ix)) = result {
3536 pane.update(cx, |pane, cx| {
3537 pane.activate_item(ix, activate_pane, focus_item, window, cx)
3538 });
3539 true
3540 } else {
3541 false
3542 }
3543 }
3544
3545 fn activate_pane_at_index(
3546 &mut self,
3547 action: &ActivatePane,
3548 window: &mut Window,
3549 cx: &mut Context<Self>,
3550 ) {
3551 let panes = self.center.panes();
3552 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
3553 window.focus(&pane.focus_handle(cx));
3554 } else {
3555 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx);
3556 }
3557 }
3558
3559 fn move_item_to_pane_at_index(
3560 &mut self,
3561 action: &MoveItemToPane,
3562 window: &mut Window,
3563 cx: &mut Context<Self>,
3564 ) {
3565 let panes = self.center.panes();
3566 let destination = match panes.get(action.destination) {
3567 Some(&destination) => destination.clone(),
3568 None => {
3569 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
3570 return;
3571 }
3572 let direction = SplitDirection::Right;
3573 let split_off_pane = self
3574 .find_pane_in_direction(direction, cx)
3575 .unwrap_or_else(|| self.active_pane.clone());
3576 let new_pane = self.add_pane(window, cx);
3577 if self
3578 .center
3579 .split(&split_off_pane, &new_pane, direction)
3580 .log_err()
3581 .is_none()
3582 {
3583 return;
3584 };
3585 new_pane
3586 }
3587 };
3588
3589 if action.clone {
3590 clone_active_item(
3591 self.database_id(),
3592 &self.active_pane,
3593 &destination,
3594 action.focus,
3595 window,
3596 cx,
3597 )
3598 } else {
3599 move_active_item(
3600 &self.active_pane,
3601 &destination,
3602 action.focus,
3603 true,
3604 window,
3605 cx,
3606 )
3607 }
3608 }
3609
3610 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
3611 let panes = self.center.panes();
3612 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
3613 let next_ix = (ix + 1) % panes.len();
3614 let next_pane = panes[next_ix].clone();
3615 window.focus(&next_pane.focus_handle(cx));
3616 }
3617 }
3618
3619 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
3620 let panes = self.center.panes();
3621 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
3622 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
3623 let prev_pane = panes[prev_ix].clone();
3624 window.focus(&prev_pane.focus_handle(cx));
3625 }
3626 }
3627
3628 pub fn activate_pane_in_direction(
3629 &mut self,
3630 direction: SplitDirection,
3631 window: &mut Window,
3632 cx: &mut App,
3633 ) {
3634 use ActivateInDirectionTarget as Target;
3635 enum Origin {
3636 LeftDock,
3637 RightDock,
3638 BottomDock,
3639 Center,
3640 }
3641
3642 let origin: Origin = [
3643 (&self.left_dock, Origin::LeftDock),
3644 (&self.right_dock, Origin::RightDock),
3645 (&self.bottom_dock, Origin::BottomDock),
3646 ]
3647 .into_iter()
3648 .find_map(|(dock, origin)| {
3649 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
3650 Some(origin)
3651 } else {
3652 None
3653 }
3654 })
3655 .unwrap_or(Origin::Center);
3656
3657 let get_last_active_pane = || {
3658 let pane = self
3659 .last_active_center_pane
3660 .clone()
3661 .unwrap_or_else(|| {
3662 self.panes
3663 .first()
3664 .expect("There must be an active pane")
3665 .downgrade()
3666 })
3667 .upgrade()?;
3668 (pane.read(cx).items_len() != 0).then_some(pane)
3669 };
3670
3671 let try_dock =
3672 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
3673
3674 let target = match (origin, direction) {
3675 // We're in the center, so we first try to go to a different pane,
3676 // otherwise try to go to a dock.
3677 (Origin::Center, direction) => {
3678 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
3679 Some(Target::Pane(pane))
3680 } else {
3681 match direction {
3682 SplitDirection::Up => None,
3683 SplitDirection::Down => try_dock(&self.bottom_dock),
3684 SplitDirection::Left => try_dock(&self.left_dock),
3685 SplitDirection::Right => try_dock(&self.right_dock),
3686 }
3687 }
3688 }
3689
3690 (Origin::LeftDock, SplitDirection::Right) => {
3691 if let Some(last_active_pane) = get_last_active_pane() {
3692 Some(Target::Pane(last_active_pane))
3693 } else {
3694 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
3695 }
3696 }
3697
3698 (Origin::LeftDock, SplitDirection::Down)
3699 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
3700
3701 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
3702 (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
3703 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
3704
3705 (Origin::RightDock, SplitDirection::Left) => {
3706 if let Some(last_active_pane) = get_last_active_pane() {
3707 Some(Target::Pane(last_active_pane))
3708 } else {
3709 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
3710 }
3711 }
3712
3713 _ => None,
3714 };
3715
3716 match target {
3717 Some(ActivateInDirectionTarget::Pane(pane)) => {
3718 let pane = pane.read(cx);
3719 if let Some(item) = pane.active_item() {
3720 item.item_focus_handle(cx).focus(window);
3721 } else {
3722 log::error!(
3723 "Could not find a focus target when in switching focus in {direction} direction for a pane",
3724 );
3725 }
3726 }
3727 Some(ActivateInDirectionTarget::Dock(dock)) => {
3728 // Defer this to avoid a panic when the dock's active panel is already on the stack.
3729 window.defer(cx, move |window, cx| {
3730 let dock = dock.read(cx);
3731 if let Some(panel) = dock.active_panel() {
3732 panel.panel_focus_handle(cx).focus(window);
3733 } else {
3734 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
3735 }
3736 })
3737 }
3738 None => {}
3739 }
3740 }
3741
3742 pub fn move_item_to_pane_in_direction(
3743 &mut self,
3744 action: &MoveItemToPaneInDirection,
3745 window: &mut Window,
3746 cx: &mut Context<Self>,
3747 ) {
3748 let destination = match self.find_pane_in_direction(action.direction, cx) {
3749 Some(destination) => destination,
3750 None => {
3751 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
3752 return;
3753 }
3754 let new_pane = self.add_pane(window, cx);
3755 if self
3756 .center
3757 .split(&self.active_pane, &new_pane, action.direction)
3758 .log_err()
3759 .is_none()
3760 {
3761 return;
3762 };
3763 new_pane
3764 }
3765 };
3766
3767 if action.clone {
3768 clone_active_item(
3769 self.database_id(),
3770 &self.active_pane,
3771 &destination,
3772 action.focus,
3773 window,
3774 cx,
3775 )
3776 } else {
3777 move_active_item(
3778 &self.active_pane,
3779 &destination,
3780 action.focus,
3781 true,
3782 window,
3783 cx,
3784 );
3785 }
3786 }
3787
3788 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
3789 self.center.bounding_box_for_pane(pane)
3790 }
3791
3792 pub fn find_pane_in_direction(
3793 &mut self,
3794 direction: SplitDirection,
3795 cx: &App,
3796 ) -> Option<Entity<Pane>> {
3797 self.center
3798 .find_pane_in_direction(&self.active_pane, direction, cx)
3799 .cloned()
3800 }
3801
3802 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
3803 if let Some(to) = self.find_pane_in_direction(direction, cx) {
3804 self.center.swap(&self.active_pane, &to);
3805 cx.notify();
3806 }
3807 }
3808
3809 pub fn resize_pane(
3810 &mut self,
3811 axis: gpui::Axis,
3812 amount: Pixels,
3813 window: &mut Window,
3814 cx: &mut Context<Self>,
3815 ) {
3816 let docks = self.all_docks();
3817 let active_dock = docks
3818 .into_iter()
3819 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
3820
3821 if let Some(dock) = active_dock {
3822 let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
3823 return;
3824 };
3825 match dock.read(cx).position() {
3826 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
3827 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
3828 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
3829 }
3830 } else {
3831 self.center
3832 .resize(&self.active_pane, axis, amount, &self.bounds);
3833 }
3834 cx.notify();
3835 }
3836
3837 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
3838 self.center.reset_pane_sizes();
3839 cx.notify();
3840 }
3841
3842 fn handle_pane_focused(
3843 &mut self,
3844 pane: Entity<Pane>,
3845 window: &mut Window,
3846 cx: &mut Context<Self>,
3847 ) {
3848 // This is explicitly hoisted out of the following check for pane identity as
3849 // terminal panel panes are not registered as a center panes.
3850 self.status_bar.update(cx, |status_bar, cx| {
3851 status_bar.set_active_pane(&pane, window, cx);
3852 });
3853 if self.active_pane != pane {
3854 self.set_active_pane(&pane, window, cx);
3855 }
3856
3857 if self.last_active_center_pane.is_none() {
3858 self.last_active_center_pane = Some(pane.downgrade());
3859 }
3860
3861 self.dismiss_zoomed_items_to_reveal(None, window, cx);
3862 if pane.read(cx).is_zoomed() {
3863 self.zoomed = Some(pane.downgrade().into());
3864 } else {
3865 self.zoomed = None;
3866 }
3867 self.zoomed_position = None;
3868 cx.emit(Event::ZoomChanged);
3869 self.update_active_view_for_followers(window, cx);
3870 pane.update(cx, |pane, _| {
3871 pane.track_alternate_file_items();
3872 });
3873
3874 cx.notify();
3875 }
3876
3877 fn set_active_pane(
3878 &mut self,
3879 pane: &Entity<Pane>,
3880 window: &mut Window,
3881 cx: &mut Context<Self>,
3882 ) {
3883 self.active_pane = pane.clone();
3884 self.active_item_path_changed(window, cx);
3885 self.last_active_center_pane = Some(pane.downgrade());
3886 }
3887
3888 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3889 self.update_active_view_for_followers(window, cx);
3890 }
3891
3892 fn handle_pane_event(
3893 &mut self,
3894 pane: &Entity<Pane>,
3895 event: &pane::Event,
3896 window: &mut Window,
3897 cx: &mut Context<Self>,
3898 ) {
3899 let mut serialize_workspace = true;
3900 match event {
3901 pane::Event::AddItem { item } => {
3902 item.added_to_pane(self, pane.clone(), window, cx);
3903 cx.emit(Event::ItemAdded {
3904 item: item.boxed_clone(),
3905 });
3906 }
3907 pane::Event::Split(direction) => {
3908 self.split_and_clone(pane.clone(), *direction, window, cx);
3909 }
3910 pane::Event::JoinIntoNext => {
3911 self.join_pane_into_next(pane.clone(), window, cx);
3912 }
3913 pane::Event::JoinAll => {
3914 self.join_all_panes(window, cx);
3915 }
3916 pane::Event::Remove { focus_on_pane } => {
3917 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
3918 }
3919 pane::Event::ActivateItem {
3920 local,
3921 focus_changed,
3922 } => {
3923 window.invalidate_character_coordinates();
3924
3925 pane.update(cx, |pane, _| {
3926 pane.track_alternate_file_items();
3927 });
3928 if *local {
3929 self.unfollow_in_pane(pane, window, cx);
3930 }
3931 serialize_workspace = *focus_changed || pane != self.active_pane();
3932 if pane == self.active_pane() {
3933 self.active_item_path_changed(window, cx);
3934 self.update_active_view_for_followers(window, cx);
3935 } else if *local {
3936 self.set_active_pane(pane, window, cx);
3937 }
3938 }
3939 pane::Event::UserSavedItem { item, save_intent } => {
3940 cx.emit(Event::UserSavedItem {
3941 pane: pane.downgrade(),
3942 item: item.boxed_clone(),
3943 save_intent: *save_intent,
3944 });
3945 serialize_workspace = false;
3946 }
3947 pane::Event::ChangeItemTitle => {
3948 if *pane == self.active_pane {
3949 self.active_item_path_changed(window, cx);
3950 }
3951 serialize_workspace = false;
3952 }
3953 pane::Event::RemovedItem { item } => {
3954 cx.emit(Event::ActiveItemChanged);
3955 self.update_window_edited(window, cx);
3956 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
3957 && entry.get().entity_id() == pane.entity_id()
3958 {
3959 entry.remove();
3960 }
3961 cx.emit(Event::ItemRemoved {
3962 item_id: item.item_id(),
3963 });
3964 }
3965 pane::Event::Focus => {
3966 window.invalidate_character_coordinates();
3967 self.handle_pane_focused(pane.clone(), window, cx);
3968 }
3969 pane::Event::ZoomIn => {
3970 if *pane == self.active_pane {
3971 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
3972 if pane.read(cx).has_focus(window, cx) {
3973 self.zoomed = Some(pane.downgrade().into());
3974 self.zoomed_position = None;
3975 cx.emit(Event::ZoomChanged);
3976 }
3977 cx.notify();
3978 }
3979 }
3980 pane::Event::ZoomOut => {
3981 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
3982 if self.zoomed_position.is_none() {
3983 self.zoomed = None;
3984 cx.emit(Event::ZoomChanged);
3985 }
3986 cx.notify();
3987 }
3988 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
3989 }
3990
3991 if serialize_workspace {
3992 self.serialize_workspace(window, cx);
3993 }
3994 }
3995
3996 pub fn unfollow_in_pane(
3997 &mut self,
3998 pane: &Entity<Pane>,
3999 window: &mut Window,
4000 cx: &mut Context<Workspace>,
4001 ) -> Option<CollaboratorId> {
4002 let leader_id = self.leader_for_pane(pane)?;
4003 self.unfollow(leader_id, window, cx);
4004 Some(leader_id)
4005 }
4006
4007 pub fn split_pane(
4008 &mut self,
4009 pane_to_split: Entity<Pane>,
4010 split_direction: SplitDirection,
4011 window: &mut Window,
4012 cx: &mut Context<Self>,
4013 ) -> Entity<Pane> {
4014 let new_pane = self.add_pane(window, cx);
4015 self.center
4016 .split(&pane_to_split, &new_pane, split_direction)
4017 .unwrap();
4018 cx.notify();
4019 new_pane
4020 }
4021
4022 pub fn split_and_clone(
4023 &mut self,
4024 pane: Entity<Pane>,
4025 direction: SplitDirection,
4026 window: &mut Window,
4027 cx: &mut Context<Self>,
4028 ) -> Option<Entity<Pane>> {
4029 let item = pane.read(cx).active_item()?;
4030 let maybe_pane_handle =
4031 if let Some(clone) = item.clone_on_split(self.database_id(), window, cx) {
4032 let new_pane = self.add_pane(window, cx);
4033 new_pane.update(cx, |pane, cx| {
4034 pane.add_item(clone, true, true, None, window, cx)
4035 });
4036 self.center.split(&pane, &new_pane, direction).unwrap();
4037 Some(new_pane)
4038 } else {
4039 None
4040 };
4041 cx.notify();
4042 maybe_pane_handle
4043 }
4044
4045 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4046 let active_item = self.active_pane.read(cx).active_item();
4047 for pane in &self.panes {
4048 join_pane_into_active(&self.active_pane, pane, window, cx);
4049 }
4050 if let Some(active_item) = active_item {
4051 self.activate_item(active_item.as_ref(), true, true, window, cx);
4052 }
4053 cx.notify();
4054 }
4055
4056 pub fn join_pane_into_next(
4057 &mut self,
4058 pane: Entity<Pane>,
4059 window: &mut Window,
4060 cx: &mut Context<Self>,
4061 ) {
4062 let next_pane = self
4063 .find_pane_in_direction(SplitDirection::Right, cx)
4064 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
4065 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
4066 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
4067 let Some(next_pane) = next_pane else {
4068 return;
4069 };
4070 move_all_items(&pane, &next_pane, window, cx);
4071 cx.notify();
4072 }
4073
4074 fn remove_pane(
4075 &mut self,
4076 pane: Entity<Pane>,
4077 focus_on: Option<Entity<Pane>>,
4078 window: &mut Window,
4079 cx: &mut Context<Self>,
4080 ) {
4081 if self.center.remove(&pane).unwrap() {
4082 self.force_remove_pane(&pane, &focus_on, window, cx);
4083 self.unfollow_in_pane(&pane, window, cx);
4084 self.last_leaders_by_pane.remove(&pane.downgrade());
4085 for removed_item in pane.read(cx).items() {
4086 self.panes_by_item.remove(&removed_item.item_id());
4087 }
4088
4089 cx.notify();
4090 } else {
4091 self.active_item_path_changed(window, cx);
4092 }
4093 cx.emit(Event::PaneRemoved);
4094 }
4095
4096 pub fn panes(&self) -> &[Entity<Pane>] {
4097 &self.panes
4098 }
4099
4100 pub fn active_pane(&self) -> &Entity<Pane> {
4101 &self.active_pane
4102 }
4103
4104 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
4105 for dock in self.all_docks() {
4106 if dock.focus_handle(cx).contains_focused(window, cx)
4107 && let Some(pane) = dock
4108 .read(cx)
4109 .active_panel()
4110 .and_then(|panel| panel.pane(cx))
4111 {
4112 return pane;
4113 }
4114 }
4115 self.active_pane().clone()
4116 }
4117
4118 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
4119 self.find_pane_in_direction(SplitDirection::Right, cx)
4120 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
4121 .unwrap_or_else(|| {
4122 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
4123 })
4124 }
4125
4126 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
4127 let weak_pane = self.panes_by_item.get(&handle.item_id())?;
4128 weak_pane.upgrade()
4129 }
4130
4131 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
4132 self.follower_states.retain(|leader_id, state| {
4133 if *leader_id == CollaboratorId::PeerId(peer_id) {
4134 for item in state.items_by_leader_view_id.values() {
4135 item.view.set_leader_id(None, window, cx);
4136 }
4137 false
4138 } else {
4139 true
4140 }
4141 });
4142 cx.notify();
4143 }
4144
4145 pub fn start_following(
4146 &mut self,
4147 leader_id: impl Into<CollaboratorId>,
4148 window: &mut Window,
4149 cx: &mut Context<Self>,
4150 ) -> Option<Task<Result<()>>> {
4151 let leader_id = leader_id.into();
4152 let pane = self.active_pane().clone();
4153
4154 self.last_leaders_by_pane
4155 .insert(pane.downgrade(), leader_id);
4156 self.unfollow(leader_id, window, cx);
4157 self.unfollow_in_pane(&pane, window, cx);
4158 self.follower_states.insert(
4159 leader_id,
4160 FollowerState {
4161 center_pane: pane.clone(),
4162 dock_pane: None,
4163 active_view_id: None,
4164 items_by_leader_view_id: Default::default(),
4165 },
4166 );
4167 cx.notify();
4168
4169 match leader_id {
4170 CollaboratorId::PeerId(leader_peer_id) => {
4171 let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
4172 let project_id = self.project.read(cx).remote_id();
4173 let request = self.app_state.client.request(proto::Follow {
4174 room_id,
4175 project_id,
4176 leader_id: Some(leader_peer_id),
4177 });
4178
4179 Some(cx.spawn_in(window, async move |this, cx| {
4180 let response = request.await?;
4181 this.update(cx, |this, _| {
4182 let state = this
4183 .follower_states
4184 .get_mut(&leader_id)
4185 .context("following interrupted")?;
4186 state.active_view_id = response
4187 .active_view
4188 .as_ref()
4189 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
4190 anyhow::Ok(())
4191 })??;
4192 if let Some(view) = response.active_view {
4193 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
4194 }
4195 this.update_in(cx, |this, window, cx| {
4196 this.leader_updated(leader_id, window, cx)
4197 })?;
4198 Ok(())
4199 }))
4200 }
4201 CollaboratorId::Agent => {
4202 self.leader_updated(leader_id, window, cx)?;
4203 Some(Task::ready(Ok(())))
4204 }
4205 }
4206 }
4207
4208 pub fn follow_next_collaborator(
4209 &mut self,
4210 _: &FollowNextCollaborator,
4211 window: &mut Window,
4212 cx: &mut Context<Self>,
4213 ) {
4214 let collaborators = self.project.read(cx).collaborators();
4215 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
4216 let mut collaborators = collaborators.keys().copied();
4217 for peer_id in collaborators.by_ref() {
4218 if CollaboratorId::PeerId(peer_id) == leader_id {
4219 break;
4220 }
4221 }
4222 collaborators.next().map(CollaboratorId::PeerId)
4223 } else if let Some(last_leader_id) =
4224 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
4225 {
4226 match last_leader_id {
4227 CollaboratorId::PeerId(peer_id) => {
4228 if collaborators.contains_key(peer_id) {
4229 Some(*last_leader_id)
4230 } else {
4231 None
4232 }
4233 }
4234 CollaboratorId::Agent => Some(CollaboratorId::Agent),
4235 }
4236 } else {
4237 None
4238 };
4239
4240 let pane = self.active_pane.clone();
4241 let Some(leader_id) = next_leader_id.or_else(|| {
4242 Some(CollaboratorId::PeerId(
4243 collaborators.keys().copied().next()?,
4244 ))
4245 }) else {
4246 return;
4247 };
4248 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
4249 return;
4250 }
4251 if let Some(task) = self.start_following(leader_id, window, cx) {
4252 task.detach_and_log_err(cx)
4253 }
4254 }
4255
4256 pub fn follow(
4257 &mut self,
4258 leader_id: impl Into<CollaboratorId>,
4259 window: &mut Window,
4260 cx: &mut Context<Self>,
4261 ) {
4262 let leader_id = leader_id.into();
4263
4264 if let CollaboratorId::PeerId(peer_id) = leader_id {
4265 let Some(room) = ActiveCall::global(cx).read(cx).room() else {
4266 return;
4267 };
4268 let room = room.read(cx);
4269 let Some(remote_participant) = room.remote_participant_for_peer_id(peer_id) else {
4270 return;
4271 };
4272
4273 let project = self.project.read(cx);
4274
4275 let other_project_id = match remote_participant.location {
4276 call::ParticipantLocation::External => None,
4277 call::ParticipantLocation::UnsharedProject => None,
4278 call::ParticipantLocation::SharedProject { project_id } => {
4279 if Some(project_id) == project.remote_id() {
4280 None
4281 } else {
4282 Some(project_id)
4283 }
4284 }
4285 };
4286
4287 // if they are active in another project, follow there.
4288 if let Some(project_id) = other_project_id {
4289 let app_state = self.app_state.clone();
4290 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
4291 .detach_and_log_err(cx);
4292 }
4293 }
4294
4295 // if you're already following, find the right pane and focus it.
4296 if let Some(follower_state) = self.follower_states.get(&leader_id) {
4297 window.focus(&follower_state.pane().focus_handle(cx));
4298
4299 return;
4300 }
4301
4302 // Otherwise, follow.
4303 if let Some(task) = self.start_following(leader_id, window, cx) {
4304 task.detach_and_log_err(cx)
4305 }
4306 }
4307
4308 pub fn unfollow(
4309 &mut self,
4310 leader_id: impl Into<CollaboratorId>,
4311 window: &mut Window,
4312 cx: &mut Context<Self>,
4313 ) -> Option<()> {
4314 cx.notify();
4315
4316 let leader_id = leader_id.into();
4317 let state = self.follower_states.remove(&leader_id)?;
4318 for (_, item) in state.items_by_leader_view_id {
4319 item.view.set_leader_id(None, window, cx);
4320 }
4321
4322 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
4323 let project_id = self.project.read(cx).remote_id();
4324 let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
4325 self.app_state
4326 .client
4327 .send(proto::Unfollow {
4328 room_id,
4329 project_id,
4330 leader_id: Some(leader_peer_id),
4331 })
4332 .log_err();
4333 }
4334
4335 Some(())
4336 }
4337
4338 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
4339 self.follower_states.contains_key(&id.into())
4340 }
4341
4342 fn active_item_path_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4343 cx.emit(Event::ActiveItemChanged);
4344 let active_entry = self.active_project_path(cx);
4345 self.project
4346 .update(cx, |project, cx| project.set_active_path(active_entry, cx));
4347
4348 self.update_window_title(window, cx);
4349 }
4350
4351 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
4352 let project = self.project().read(cx);
4353 let mut title = String::new();
4354
4355 for (i, name) in project.worktree_root_names(cx).enumerate() {
4356 if i > 0 {
4357 title.push_str(", ");
4358 }
4359 title.push_str(name);
4360 }
4361
4362 if title.is_empty() {
4363 title = "empty project".to_string();
4364 }
4365
4366 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
4367 let filename = path
4368 .path
4369 .file_name()
4370 .map(|s| s.to_string_lossy())
4371 .or_else(|| {
4372 Some(Cow::Borrowed(
4373 project
4374 .worktree_for_id(path.worktree_id, cx)?
4375 .read(cx)
4376 .root_name(),
4377 ))
4378 });
4379
4380 if let Some(filename) = filename {
4381 title.push_str(" — ");
4382 title.push_str(filename.as_ref());
4383 }
4384 }
4385
4386 if project.is_via_collab() {
4387 title.push_str(" ↙");
4388 } else if project.is_shared() {
4389 title.push_str(" ↗");
4390 }
4391
4392 if let Some(last_title) = self.last_window_title.as_ref()
4393 && &title == last_title
4394 {
4395 return;
4396 }
4397 window.set_window_title(&title);
4398 SystemWindowTabController::update_tab_title(
4399 cx,
4400 window.window_handle().window_id(),
4401 SharedString::from(&title),
4402 );
4403 self.last_window_title = Some(title);
4404 }
4405
4406 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
4407 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
4408 if is_edited != self.window_edited {
4409 self.window_edited = is_edited;
4410 window.set_window_edited(self.window_edited)
4411 }
4412 }
4413
4414 fn update_item_dirty_state(
4415 &mut self,
4416 item: &dyn ItemHandle,
4417 window: &mut Window,
4418 cx: &mut App,
4419 ) {
4420 let is_dirty = item.is_dirty(cx);
4421 let item_id = item.item_id();
4422 let was_dirty = self.dirty_items.contains_key(&item_id);
4423 if is_dirty == was_dirty {
4424 return;
4425 }
4426 if was_dirty {
4427 self.dirty_items.remove(&item_id);
4428 self.update_window_edited(window, cx);
4429 return;
4430 }
4431 if let Some(window_handle) = window.window_handle().downcast::<Self>() {
4432 let s = item.on_release(
4433 cx,
4434 Box::new(move |cx| {
4435 window_handle
4436 .update(cx, |this, window, cx| {
4437 this.dirty_items.remove(&item_id);
4438 this.update_window_edited(window, cx)
4439 })
4440 .ok();
4441 }),
4442 );
4443 self.dirty_items.insert(item_id, s);
4444 self.update_window_edited(window, cx);
4445 }
4446 }
4447
4448 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
4449 if self.notifications.is_empty() {
4450 None
4451 } else {
4452 Some(
4453 div()
4454 .absolute()
4455 .right_3()
4456 .bottom_3()
4457 .w_112()
4458 .h_full()
4459 .flex()
4460 .flex_col()
4461 .justify_end()
4462 .gap_2()
4463 .children(
4464 self.notifications
4465 .iter()
4466 .map(|(_, notification)| notification.clone().into_any()),
4467 ),
4468 )
4469 }
4470 }
4471
4472 // RPC handlers
4473
4474 fn active_view_for_follower(
4475 &self,
4476 follower_project_id: Option<u64>,
4477 window: &mut Window,
4478 cx: &mut Context<Self>,
4479 ) -> Option<proto::View> {
4480 let (item, panel_id) = self.active_item_for_followers(window, cx);
4481 let item = item?;
4482 let leader_id = self
4483 .pane_for(&*item)
4484 .and_then(|pane| self.leader_for_pane(&pane));
4485 let leader_peer_id = match leader_id {
4486 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
4487 Some(CollaboratorId::Agent) | None => None,
4488 };
4489
4490 let item_handle = item.to_followable_item_handle(cx)?;
4491 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
4492 let variant = item_handle.to_state_proto(window, cx)?;
4493
4494 if item_handle.is_project_item(window, cx)
4495 && (follower_project_id.is_none()
4496 || follower_project_id != self.project.read(cx).remote_id())
4497 {
4498 return None;
4499 }
4500
4501 Some(proto::View {
4502 id: id.to_proto(),
4503 leader_id: leader_peer_id,
4504 variant: Some(variant),
4505 panel_id: panel_id.map(|id| id as i32),
4506 })
4507 }
4508
4509 fn handle_follow(
4510 &mut self,
4511 follower_project_id: Option<u64>,
4512 window: &mut Window,
4513 cx: &mut Context<Self>,
4514 ) -> proto::FollowResponse {
4515 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
4516
4517 cx.notify();
4518 proto::FollowResponse {
4519 // TODO: Remove after version 0.145.x stabilizes.
4520 active_view_id: active_view.as_ref().and_then(|view| view.id.clone()),
4521 views: active_view.iter().cloned().collect(),
4522 active_view,
4523 }
4524 }
4525
4526 fn handle_update_followers(
4527 &mut self,
4528 leader_id: PeerId,
4529 message: proto::UpdateFollowers,
4530 _window: &mut Window,
4531 _cx: &mut Context<Self>,
4532 ) {
4533 self.leader_updates_tx
4534 .unbounded_send((leader_id, message))
4535 .ok();
4536 }
4537
4538 async fn process_leader_update(
4539 this: &WeakEntity<Self>,
4540 leader_id: PeerId,
4541 update: proto::UpdateFollowers,
4542 cx: &mut AsyncWindowContext,
4543 ) -> Result<()> {
4544 match update.variant.context("invalid update")? {
4545 proto::update_followers::Variant::CreateView(view) => {
4546 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
4547 let should_add_view = this.update(cx, |this, _| {
4548 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
4549 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
4550 } else {
4551 anyhow::Ok(false)
4552 }
4553 })??;
4554
4555 if should_add_view {
4556 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
4557 }
4558 }
4559 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
4560 let should_add_view = this.update(cx, |this, _| {
4561 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
4562 state.active_view_id = update_active_view
4563 .view
4564 .as_ref()
4565 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
4566
4567 if state.active_view_id.is_some_and(|view_id| {
4568 !state.items_by_leader_view_id.contains_key(&view_id)
4569 }) {
4570 anyhow::Ok(true)
4571 } else {
4572 anyhow::Ok(false)
4573 }
4574 } else {
4575 anyhow::Ok(false)
4576 }
4577 })??;
4578
4579 if should_add_view && let Some(view) = update_active_view.view {
4580 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
4581 }
4582 }
4583 proto::update_followers::Variant::UpdateView(update_view) => {
4584 let variant = update_view.variant.context("missing update view variant")?;
4585 let id = update_view.id.context("missing update view id")?;
4586 let mut tasks = Vec::new();
4587 this.update_in(cx, |this, window, cx| {
4588 let project = this.project.clone();
4589 if let Some(state) = this.follower_states.get(&leader_id.into()) {
4590 let view_id = ViewId::from_proto(id.clone())?;
4591 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
4592 tasks.push(item.view.apply_update_proto(
4593 &project,
4594 variant.clone(),
4595 window,
4596 cx,
4597 ));
4598 }
4599 }
4600 anyhow::Ok(())
4601 })??;
4602 try_join_all(tasks).await.log_err();
4603 }
4604 }
4605 this.update_in(cx, |this, window, cx| {
4606 this.leader_updated(leader_id, window, cx)
4607 })?;
4608 Ok(())
4609 }
4610
4611 async fn add_view_from_leader(
4612 this: WeakEntity<Self>,
4613 leader_id: PeerId,
4614 view: &proto::View,
4615 cx: &mut AsyncWindowContext,
4616 ) -> Result<()> {
4617 let this = this.upgrade().context("workspace dropped")?;
4618
4619 let Some(id) = view.id.clone() else {
4620 anyhow::bail!("no id for view");
4621 };
4622 let id = ViewId::from_proto(id)?;
4623 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
4624
4625 let pane = this.update(cx, |this, _cx| {
4626 let state = this
4627 .follower_states
4628 .get(&leader_id.into())
4629 .context("stopped following")?;
4630 anyhow::Ok(state.pane().clone())
4631 })??;
4632 let existing_item = pane.update_in(cx, |pane, window, cx| {
4633 let client = this.read(cx).client().clone();
4634 pane.items().find_map(|item| {
4635 let item = item.to_followable_item_handle(cx)?;
4636 if item.remote_id(&client, window, cx) == Some(id) {
4637 Some(item)
4638 } else {
4639 None
4640 }
4641 })
4642 })?;
4643 let item = if let Some(existing_item) = existing_item {
4644 existing_item
4645 } else {
4646 let variant = view.variant.clone();
4647 anyhow::ensure!(variant.is_some(), "missing view variant");
4648
4649 let task = cx.update(|window, cx| {
4650 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
4651 })?;
4652
4653 let Some(task) = task else {
4654 anyhow::bail!(
4655 "failed to construct view from leader (maybe from a different version of zed?)"
4656 );
4657 };
4658
4659 let mut new_item = task.await?;
4660 pane.update_in(cx, |pane, window, cx| {
4661 let mut item_to_remove = None;
4662 for (ix, item) in pane.items().enumerate() {
4663 if let Some(item) = item.to_followable_item_handle(cx) {
4664 match new_item.dedup(item.as_ref(), window, cx) {
4665 Some(item::Dedup::KeepExisting) => {
4666 new_item =
4667 item.boxed_clone().to_followable_item_handle(cx).unwrap();
4668 break;
4669 }
4670 Some(item::Dedup::ReplaceExisting) => {
4671 item_to_remove = Some((ix, item.item_id()));
4672 break;
4673 }
4674 None => {}
4675 }
4676 }
4677 }
4678
4679 if let Some((ix, id)) = item_to_remove {
4680 pane.remove_item(id, false, false, window, cx);
4681 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
4682 }
4683 })?;
4684
4685 new_item
4686 };
4687
4688 this.update_in(cx, |this, window, cx| {
4689 let state = this.follower_states.get_mut(&leader_id.into())?;
4690 item.set_leader_id(Some(leader_id.into()), window, cx);
4691 state.items_by_leader_view_id.insert(
4692 id,
4693 FollowerView {
4694 view: item,
4695 location: panel_id,
4696 },
4697 );
4698
4699 Some(())
4700 })?;
4701
4702 Ok(())
4703 }
4704
4705 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4706 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
4707 return;
4708 };
4709
4710 if let Some(agent_location) = self.project.read(cx).agent_location() {
4711 let buffer_entity_id = agent_location.buffer.entity_id();
4712 let view_id = ViewId {
4713 creator: CollaboratorId::Agent,
4714 id: buffer_entity_id.as_u64(),
4715 };
4716 follower_state.active_view_id = Some(view_id);
4717
4718 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
4719 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
4720 hash_map::Entry::Vacant(entry) => {
4721 let existing_view =
4722 follower_state
4723 .center_pane
4724 .read(cx)
4725 .items()
4726 .find_map(|item| {
4727 let item = item.to_followable_item_handle(cx)?;
4728 if item.is_singleton(cx)
4729 && item.project_item_model_ids(cx).as_slice()
4730 == [buffer_entity_id]
4731 {
4732 Some(item)
4733 } else {
4734 None
4735 }
4736 });
4737 let view = existing_view.or_else(|| {
4738 agent_location.buffer.upgrade().and_then(|buffer| {
4739 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
4740 registry.build_item(buffer, self.project.clone(), None, window, cx)
4741 })?
4742 .to_followable_item_handle(cx)
4743 })
4744 });
4745
4746 view.map(|view| {
4747 entry.insert(FollowerView {
4748 view,
4749 location: None,
4750 })
4751 })
4752 }
4753 };
4754
4755 if let Some(item) = item {
4756 item.view
4757 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
4758 item.view
4759 .update_agent_location(agent_location.position, window, cx);
4760 }
4761 } else {
4762 follower_state.active_view_id = None;
4763 }
4764
4765 self.leader_updated(CollaboratorId::Agent, window, cx);
4766 }
4767
4768 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
4769 let mut is_project_item = true;
4770 let mut update = proto::UpdateActiveView::default();
4771 if window.is_window_active() {
4772 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
4773
4774 if let Some(item) = active_item
4775 && item.item_focus_handle(cx).contains_focused(window, cx)
4776 {
4777 let leader_id = self
4778 .pane_for(&*item)
4779 .and_then(|pane| self.leader_for_pane(&pane));
4780 let leader_peer_id = match leader_id {
4781 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
4782 Some(CollaboratorId::Agent) | None => None,
4783 };
4784
4785 if let Some(item) = item.to_followable_item_handle(cx) {
4786 let id = item
4787 .remote_id(&self.app_state.client, window, cx)
4788 .map(|id| id.to_proto());
4789
4790 if let Some(id) = id
4791 && let Some(variant) = item.to_state_proto(window, cx)
4792 {
4793 let view = Some(proto::View {
4794 id: id.clone(),
4795 leader_id: leader_peer_id,
4796 variant: Some(variant),
4797 panel_id: panel_id.map(|id| id as i32),
4798 });
4799
4800 is_project_item = item.is_project_item(window, cx);
4801 update = proto::UpdateActiveView {
4802 view,
4803 // TODO: Remove after version 0.145.x stabilizes.
4804 id,
4805 leader_id: leader_peer_id,
4806 };
4807 };
4808 }
4809 }
4810 }
4811
4812 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
4813 if active_view_id != self.last_active_view_id.as_ref() {
4814 self.last_active_view_id = active_view_id.cloned();
4815 self.update_followers(
4816 is_project_item,
4817 proto::update_followers::Variant::UpdateActiveView(update),
4818 window,
4819 cx,
4820 );
4821 }
4822 }
4823
4824 fn active_item_for_followers(
4825 &self,
4826 window: &mut Window,
4827 cx: &mut App,
4828 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
4829 let mut active_item = None;
4830 let mut panel_id = None;
4831 for dock in self.all_docks() {
4832 if dock.focus_handle(cx).contains_focused(window, cx)
4833 && let Some(panel) = dock.read(cx).active_panel()
4834 && let Some(pane) = panel.pane(cx)
4835 && let Some(item) = pane.read(cx).active_item()
4836 {
4837 active_item = Some(item);
4838 panel_id = panel.remote_id();
4839 break;
4840 }
4841 }
4842
4843 if active_item.is_none() {
4844 active_item = self.active_pane().read(cx).active_item();
4845 }
4846 (active_item, panel_id)
4847 }
4848
4849 fn update_followers(
4850 &self,
4851 project_only: bool,
4852 update: proto::update_followers::Variant,
4853 _: &mut Window,
4854 cx: &mut App,
4855 ) -> Option<()> {
4856 // If this update only applies to for followers in the current project,
4857 // then skip it unless this project is shared. If it applies to all
4858 // followers, regardless of project, then set `project_id` to none,
4859 // indicating that it goes to all followers.
4860 let project_id = if project_only {
4861 Some(self.project.read(cx).remote_id()?)
4862 } else {
4863 None
4864 };
4865 self.app_state().workspace_store.update(cx, |store, cx| {
4866 store.update_followers(project_id, update, cx)
4867 })
4868 }
4869
4870 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
4871 self.follower_states.iter().find_map(|(leader_id, state)| {
4872 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
4873 Some(*leader_id)
4874 } else {
4875 None
4876 }
4877 })
4878 }
4879
4880 fn leader_updated(
4881 &mut self,
4882 leader_id: impl Into<CollaboratorId>,
4883 window: &mut Window,
4884 cx: &mut Context<Self>,
4885 ) -> Option<Box<dyn ItemHandle>> {
4886 cx.notify();
4887
4888 let leader_id = leader_id.into();
4889 let (panel_id, item) = match leader_id {
4890 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
4891 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
4892 };
4893
4894 let state = self.follower_states.get(&leader_id)?;
4895 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
4896 let pane;
4897 if let Some(panel_id) = panel_id {
4898 pane = self
4899 .activate_panel_for_proto_id(panel_id, window, cx)?
4900 .pane(cx)?;
4901 let state = self.follower_states.get_mut(&leader_id)?;
4902 state.dock_pane = Some(pane.clone());
4903 } else {
4904 pane = state.center_pane.clone();
4905 let state = self.follower_states.get_mut(&leader_id)?;
4906 if let Some(dock_pane) = state.dock_pane.take() {
4907 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
4908 }
4909 }
4910
4911 pane.update(cx, |pane, cx| {
4912 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
4913 if let Some(index) = pane.index_for_item(item.as_ref()) {
4914 pane.activate_item(index, false, false, window, cx);
4915 } else {
4916 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
4917 }
4918
4919 if focus_active_item {
4920 pane.focus_active_item(window, cx)
4921 }
4922 });
4923
4924 Some(item)
4925 }
4926
4927 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
4928 let state = self.follower_states.get(&CollaboratorId::Agent)?;
4929 let active_view_id = state.active_view_id?;
4930 Some(
4931 state
4932 .items_by_leader_view_id
4933 .get(&active_view_id)?
4934 .view
4935 .boxed_clone(),
4936 )
4937 }
4938
4939 fn active_item_for_peer(
4940 &self,
4941 peer_id: PeerId,
4942 window: &mut Window,
4943 cx: &mut Context<Self>,
4944 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
4945 let call = self.active_call()?;
4946 let room = call.read(cx).room()?.read(cx);
4947 let participant = room.remote_participant_for_peer_id(peer_id)?;
4948 let leader_in_this_app;
4949 let leader_in_this_project;
4950 match participant.location {
4951 call::ParticipantLocation::SharedProject { project_id } => {
4952 leader_in_this_app = true;
4953 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
4954 }
4955 call::ParticipantLocation::UnsharedProject => {
4956 leader_in_this_app = true;
4957 leader_in_this_project = false;
4958 }
4959 call::ParticipantLocation::External => {
4960 leader_in_this_app = false;
4961 leader_in_this_project = false;
4962 }
4963 };
4964 let state = self.follower_states.get(&peer_id.into())?;
4965 let mut item_to_activate = None;
4966 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
4967 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
4968 && (leader_in_this_project || !item.view.is_project_item(window, cx))
4969 {
4970 item_to_activate = Some((item.location, item.view.boxed_clone()));
4971 }
4972 } else if let Some(shared_screen) =
4973 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
4974 {
4975 item_to_activate = Some((None, Box::new(shared_screen)));
4976 }
4977 item_to_activate
4978 }
4979
4980 fn shared_screen_for_peer(
4981 &self,
4982 peer_id: PeerId,
4983 pane: &Entity<Pane>,
4984 window: &mut Window,
4985 cx: &mut App,
4986 ) -> Option<Entity<SharedScreen>> {
4987 let call = self.active_call()?;
4988 let room = call.read(cx).room()?.clone();
4989 let participant = room.read(cx).remote_participant_for_peer_id(peer_id)?;
4990 let track = participant.video_tracks.values().next()?.clone();
4991 let user = participant.user.clone();
4992
4993 for item in pane.read(cx).items_of_type::<SharedScreen>() {
4994 if item.read(cx).peer_id == peer_id {
4995 return Some(item);
4996 }
4997 }
4998
4999 Some(cx.new(|cx| SharedScreen::new(track, peer_id, user.clone(), room.clone(), window, cx)))
5000 }
5001
5002 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5003 if window.is_window_active() {
5004 self.update_active_view_for_followers(window, cx);
5005
5006 if let Some(database_id) = self.database_id {
5007 cx.background_spawn(persistence::DB.update_timestamp(database_id))
5008 .detach();
5009 }
5010 } else {
5011 for pane in &self.panes {
5012 pane.update(cx, |pane, cx| {
5013 if let Some(item) = pane.active_item() {
5014 item.workspace_deactivated(window, cx);
5015 }
5016 for item in pane.items() {
5017 if matches!(
5018 item.workspace_settings(cx).autosave,
5019 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
5020 ) {
5021 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
5022 .detach_and_log_err(cx);
5023 }
5024 }
5025 });
5026 }
5027 }
5028 }
5029
5030 pub fn active_call(&self) -> Option<&Entity<ActiveCall>> {
5031 self.active_call.as_ref().map(|(call, _)| call)
5032 }
5033
5034 fn on_active_call_event(
5035 &mut self,
5036 _: &Entity<ActiveCall>,
5037 event: &call::room::Event,
5038 window: &mut Window,
5039 cx: &mut Context<Self>,
5040 ) {
5041 match event {
5042 call::room::Event::ParticipantLocationChanged { participant_id }
5043 | call::room::Event::RemoteVideoTracksChanged { participant_id } => {
5044 self.leader_updated(participant_id, window, cx);
5045 }
5046 _ => {}
5047 }
5048 }
5049
5050 pub fn database_id(&self) -> Option<WorkspaceId> {
5051 self.database_id
5052 }
5053
5054 pub fn session_id(&self) -> Option<String> {
5055 self.session_id.clone()
5056 }
5057
5058 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
5059 let project = self.project().read(cx);
5060 project
5061 .visible_worktrees(cx)
5062 .map(|worktree| worktree.read(cx).abs_path())
5063 .collect::<Vec<_>>()
5064 }
5065
5066 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
5067 match member {
5068 Member::Axis(PaneAxis { members, .. }) => {
5069 for child in members.iter() {
5070 self.remove_panes(child.clone(), window, cx)
5071 }
5072 }
5073 Member::Pane(pane) => {
5074 self.force_remove_pane(&pane, &None, window, cx);
5075 }
5076 }
5077 }
5078
5079 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
5080 self.session_id.take();
5081 self.serialize_workspace_internal(window, cx)
5082 }
5083
5084 fn force_remove_pane(
5085 &mut self,
5086 pane: &Entity<Pane>,
5087 focus_on: &Option<Entity<Pane>>,
5088 window: &mut Window,
5089 cx: &mut Context<Workspace>,
5090 ) {
5091 self.panes.retain(|p| p != pane);
5092 if let Some(focus_on) = focus_on {
5093 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
5094 } else if self.active_pane() == pane {
5095 self.panes
5096 .last()
5097 .unwrap()
5098 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
5099 }
5100 if self.last_active_center_pane == Some(pane.downgrade()) {
5101 self.last_active_center_pane = None;
5102 }
5103 cx.notify();
5104 }
5105
5106 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5107 if self._schedule_serialize_workspace.is_none() {
5108 self._schedule_serialize_workspace =
5109 Some(cx.spawn_in(window, async move |this, cx| {
5110 cx.background_executor()
5111 .timer(SERIALIZATION_THROTTLE_TIME)
5112 .await;
5113 this.update_in(cx, |this, window, cx| {
5114 this.serialize_workspace_internal(window, cx).detach();
5115 this._schedule_serialize_workspace.take();
5116 })
5117 .log_err();
5118 }));
5119 }
5120 }
5121
5122 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
5123 let Some(database_id) = self.database_id() else {
5124 return Task::ready(());
5125 };
5126
5127 fn serialize_pane_handle(
5128 pane_handle: &Entity<Pane>,
5129 window: &mut Window,
5130 cx: &mut App,
5131 ) -> SerializedPane {
5132 let (items, active, pinned_count) = {
5133 let pane = pane_handle.read(cx);
5134 let active_item_id = pane.active_item().map(|item| item.item_id());
5135 (
5136 pane.items()
5137 .filter_map(|handle| {
5138 let handle = handle.to_serializable_item_handle(cx)?;
5139
5140 Some(SerializedItem {
5141 kind: Arc::from(handle.serialized_item_kind()),
5142 item_id: handle.item_id().as_u64(),
5143 active: Some(handle.item_id()) == active_item_id,
5144 preview: pane.is_active_preview_item(handle.item_id()),
5145 })
5146 })
5147 .collect::<Vec<_>>(),
5148 pane.has_focus(window, cx),
5149 pane.pinned_count(),
5150 )
5151 };
5152
5153 SerializedPane::new(items, active, pinned_count)
5154 }
5155
5156 fn build_serialized_pane_group(
5157 pane_group: &Member,
5158 window: &mut Window,
5159 cx: &mut App,
5160 ) -> SerializedPaneGroup {
5161 match pane_group {
5162 Member::Axis(PaneAxis {
5163 axis,
5164 members,
5165 flexes,
5166 bounding_boxes: _,
5167 }) => SerializedPaneGroup::Group {
5168 axis: SerializedAxis(*axis),
5169 children: members
5170 .iter()
5171 .map(|member| build_serialized_pane_group(member, window, cx))
5172 .collect::<Vec<_>>(),
5173 flexes: Some(flexes.lock().clone()),
5174 },
5175 Member::Pane(pane_handle) => {
5176 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
5177 }
5178 }
5179 }
5180
5181 fn build_serialized_docks(
5182 this: &Workspace,
5183 window: &mut Window,
5184 cx: &mut App,
5185 ) -> DockStructure {
5186 let left_dock = this.left_dock.read(cx);
5187 let left_visible = left_dock.is_open();
5188 let left_active_panel = left_dock
5189 .active_panel()
5190 .map(|panel| panel.persistent_name().to_string());
5191 let left_dock_zoom = left_dock
5192 .active_panel()
5193 .map(|panel| panel.is_zoomed(window, cx))
5194 .unwrap_or(false);
5195
5196 let right_dock = this.right_dock.read(cx);
5197 let right_visible = right_dock.is_open();
5198 let right_active_panel = right_dock
5199 .active_panel()
5200 .map(|panel| panel.persistent_name().to_string());
5201 let right_dock_zoom = right_dock
5202 .active_panel()
5203 .map(|panel| panel.is_zoomed(window, cx))
5204 .unwrap_or(false);
5205
5206 let bottom_dock = this.bottom_dock.read(cx);
5207 let bottom_visible = bottom_dock.is_open();
5208 let bottom_active_panel = bottom_dock
5209 .active_panel()
5210 .map(|panel| panel.persistent_name().to_string());
5211 let bottom_dock_zoom = bottom_dock
5212 .active_panel()
5213 .map(|panel| panel.is_zoomed(window, cx))
5214 .unwrap_or(false);
5215
5216 DockStructure {
5217 left: DockData {
5218 visible: left_visible,
5219 active_panel: left_active_panel,
5220 zoom: left_dock_zoom,
5221 },
5222 right: DockData {
5223 visible: right_visible,
5224 active_panel: right_active_panel,
5225 zoom: right_dock_zoom,
5226 },
5227 bottom: DockData {
5228 visible: bottom_visible,
5229 active_panel: bottom_active_panel,
5230 zoom: bottom_dock_zoom,
5231 },
5232 }
5233 }
5234
5235 match self.serialize_workspace_location(cx) {
5236 WorkspaceLocation::Location(location, paths) => {
5237 let breakpoints = self.project.update(cx, |project, cx| {
5238 project
5239 .breakpoint_store()
5240 .read(cx)
5241 .all_source_breakpoints(cx)
5242 });
5243
5244 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
5245 let docks = build_serialized_docks(self, window, cx);
5246 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
5247 let serialized_workspace = SerializedWorkspace {
5248 id: database_id,
5249 location,
5250 paths,
5251 center_group,
5252 window_bounds,
5253 display: Default::default(),
5254 docks,
5255 centered_layout: self.centered_layout,
5256 session_id: self.session_id.clone(),
5257 breakpoints,
5258 window_id: Some(window.window_handle().window_id().as_u64()),
5259 };
5260
5261 window.spawn(cx, async move |_| {
5262 persistence::DB.save_workspace(serialized_workspace).await;
5263 })
5264 }
5265 WorkspaceLocation::DetachFromSession => window.spawn(cx, async move |_| {
5266 persistence::DB
5267 .set_session_id(database_id, None)
5268 .await
5269 .log_err();
5270 }),
5271 WorkspaceLocation::None => Task::ready(()),
5272 }
5273 }
5274
5275 fn serialize_workspace_location(&self, cx: &App) -> WorkspaceLocation {
5276 let paths = PathList::new(&self.root_paths(cx));
5277 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
5278 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
5279 } else if self.project.read(cx).is_local() {
5280 if !paths.is_empty() {
5281 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
5282 } else {
5283 WorkspaceLocation::DetachFromSession
5284 }
5285 } else {
5286 WorkspaceLocation::None
5287 }
5288 }
5289
5290 fn update_history(&self, cx: &mut App) {
5291 let Some(id) = self.database_id() else {
5292 return;
5293 };
5294 if !self.project.read(cx).is_local() {
5295 return;
5296 }
5297 if let Some(manager) = HistoryManager::global(cx) {
5298 let paths = PathList::new(&self.root_paths(cx));
5299 manager.update(cx, |this, cx| {
5300 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
5301 });
5302 }
5303 }
5304
5305 async fn serialize_items(
5306 this: &WeakEntity<Self>,
5307 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
5308 cx: &mut AsyncWindowContext,
5309 ) -> Result<()> {
5310 const CHUNK_SIZE: usize = 200;
5311
5312 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
5313
5314 while let Some(items_received) = serializable_items.next().await {
5315 let unique_items =
5316 items_received
5317 .into_iter()
5318 .fold(HashMap::default(), |mut acc, item| {
5319 acc.entry(item.item_id()).or_insert(item);
5320 acc
5321 });
5322
5323 // We use into_iter() here so that the references to the items are moved into
5324 // the tasks and not kept alive while we're sleeping.
5325 for (_, item) in unique_items.into_iter() {
5326 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
5327 item.serialize(workspace, false, window, cx)
5328 }) {
5329 cx.background_spawn(async move { task.await.log_err() })
5330 .detach();
5331 }
5332 }
5333
5334 cx.background_executor()
5335 .timer(SERIALIZATION_THROTTLE_TIME)
5336 .await;
5337 }
5338
5339 Ok(())
5340 }
5341
5342 pub(crate) fn enqueue_item_serialization(
5343 &mut self,
5344 item: Box<dyn SerializableItemHandle>,
5345 ) -> Result<()> {
5346 self.serializable_items_tx
5347 .unbounded_send(item)
5348 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
5349 }
5350
5351 pub(crate) fn load_workspace(
5352 serialized_workspace: SerializedWorkspace,
5353 paths_to_open: Vec<Option<ProjectPath>>,
5354 window: &mut Window,
5355 cx: &mut Context<Workspace>,
5356 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
5357 cx.spawn_in(window, async move |workspace, cx| {
5358 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
5359
5360 let mut center_group = None;
5361 let mut center_items = None;
5362
5363 // Traverse the splits tree and add to things
5364 if let Some((group, active_pane, items)) = serialized_workspace
5365 .center_group
5366 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
5367 .await
5368 {
5369 center_items = Some(items);
5370 center_group = Some((group, active_pane))
5371 }
5372
5373 let mut items_by_project_path = HashMap::default();
5374 let mut item_ids_by_kind = HashMap::default();
5375 let mut all_deserialized_items = Vec::default();
5376 cx.update(|_, cx| {
5377 for item in center_items.unwrap_or_default().into_iter().flatten() {
5378 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
5379 item_ids_by_kind
5380 .entry(serializable_item_handle.serialized_item_kind())
5381 .or_insert(Vec::new())
5382 .push(item.item_id().as_u64() as ItemId);
5383 }
5384
5385 if let Some(project_path) = item.project_path(cx) {
5386 items_by_project_path.insert(project_path, item.clone());
5387 }
5388 all_deserialized_items.push(item);
5389 }
5390 })?;
5391
5392 let opened_items = paths_to_open
5393 .into_iter()
5394 .map(|path_to_open| {
5395 path_to_open
5396 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
5397 })
5398 .collect::<Vec<_>>();
5399
5400 // Remove old panes from workspace panes list
5401 workspace.update_in(cx, |workspace, window, cx| {
5402 if let Some((center_group, active_pane)) = center_group {
5403 workspace.remove_panes(workspace.center.root.clone(), window, cx);
5404
5405 // Swap workspace center group
5406 workspace.center = PaneGroup::with_root(center_group);
5407 if let Some(active_pane) = active_pane {
5408 workspace.set_active_pane(&active_pane, window, cx);
5409 cx.focus_self(window);
5410 } else {
5411 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
5412 }
5413 }
5414
5415 let docks = serialized_workspace.docks;
5416
5417 for (dock, serialized_dock) in [
5418 (&mut workspace.right_dock, docks.right),
5419 (&mut workspace.left_dock, docks.left),
5420 (&mut workspace.bottom_dock, docks.bottom),
5421 ]
5422 .iter_mut()
5423 {
5424 dock.update(cx, |dock, cx| {
5425 dock.serialized_dock = Some(serialized_dock.clone());
5426 dock.restore_state(window, cx);
5427 });
5428 }
5429
5430 cx.notify();
5431 })?;
5432
5433 let _ = project
5434 .update(cx, |project, cx| {
5435 project
5436 .breakpoint_store()
5437 .update(cx, |breakpoint_store, cx| {
5438 breakpoint_store
5439 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
5440 })
5441 })?
5442 .await;
5443
5444 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
5445 // after loading the items, we might have different items and in order to avoid
5446 // the database filling up, we delete items that haven't been loaded now.
5447 //
5448 // The items that have been loaded, have been saved after they've been added to the workspace.
5449 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
5450 item_ids_by_kind
5451 .into_iter()
5452 .map(|(item_kind, loaded_items)| {
5453 SerializableItemRegistry::cleanup(
5454 item_kind,
5455 serialized_workspace.id,
5456 loaded_items,
5457 window,
5458 cx,
5459 )
5460 .log_err()
5461 })
5462 .collect::<Vec<_>>()
5463 })?;
5464
5465 futures::future::join_all(clean_up_tasks).await;
5466
5467 workspace
5468 .update_in(cx, |workspace, window, cx| {
5469 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
5470 workspace.serialize_workspace_internal(window, cx).detach();
5471
5472 // Ensure that we mark the window as edited if we did load dirty items
5473 workspace.update_window_edited(window, cx);
5474 })
5475 .ok();
5476
5477 Ok(opened_items)
5478 })
5479 }
5480
5481 fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
5482 self.add_workspace_actions_listeners(div, window, cx)
5483 .on_action(cx.listener(Self::close_inactive_items_and_panes))
5484 .on_action(cx.listener(Self::close_all_items_and_panes))
5485 .on_action(cx.listener(Self::save_all))
5486 .on_action(cx.listener(Self::send_keystrokes))
5487 .on_action(cx.listener(Self::add_folder_to_project))
5488 .on_action(cx.listener(Self::follow_next_collaborator))
5489 .on_action(cx.listener(Self::close_window))
5490 .on_action(cx.listener(Self::activate_pane_at_index))
5491 .on_action(cx.listener(Self::move_item_to_pane_at_index))
5492 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
5493 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
5494 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
5495 let pane = workspace.active_pane().clone();
5496 workspace.unfollow_in_pane(&pane, window, cx);
5497 }))
5498 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
5499 workspace
5500 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
5501 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
5502 }))
5503 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
5504 workspace
5505 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
5506 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
5507 }))
5508 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
5509 workspace
5510 .save_active_item(SaveIntent::SaveAs, window, cx)
5511 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
5512 }))
5513 .on_action(
5514 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
5515 workspace.activate_previous_pane(window, cx)
5516 }),
5517 )
5518 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
5519 workspace.activate_next_pane(window, cx)
5520 }))
5521 .on_action(
5522 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
5523 workspace.activate_next_window(cx)
5524 }),
5525 )
5526 .on_action(
5527 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
5528 workspace.activate_previous_window(cx)
5529 }),
5530 )
5531 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
5532 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
5533 }))
5534 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
5535 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
5536 }))
5537 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
5538 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
5539 }))
5540 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
5541 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
5542 }))
5543 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
5544 workspace.activate_next_pane(window, cx)
5545 }))
5546 .on_action(cx.listener(
5547 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
5548 workspace.move_item_to_pane_in_direction(action, window, cx)
5549 },
5550 ))
5551 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
5552 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
5553 }))
5554 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
5555 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
5556 }))
5557 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
5558 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
5559 }))
5560 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
5561 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
5562 }))
5563 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
5564 this.toggle_dock(DockPosition::Left, window, cx);
5565 }))
5566 .on_action(cx.listener(
5567 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
5568 workspace.toggle_dock(DockPosition::Right, window, cx);
5569 },
5570 ))
5571 .on_action(cx.listener(
5572 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
5573 workspace.toggle_dock(DockPosition::Bottom, window, cx);
5574 },
5575 ))
5576 .on_action(cx.listener(
5577 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
5578 if !workspace.close_active_dock(window, cx) {
5579 cx.propagate();
5580 }
5581 },
5582 ))
5583 .on_action(
5584 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
5585 workspace.close_all_docks(window, cx);
5586 }),
5587 )
5588 .on_action(cx.listener(
5589 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
5590 workspace.clear_all_notifications(cx);
5591 },
5592 ))
5593 .on_action(cx.listener(
5594 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
5595 if let Some((notification_id, _)) = workspace.notifications.pop() {
5596 workspace.suppress_notification(¬ification_id, cx);
5597 }
5598 },
5599 ))
5600 .on_action(cx.listener(
5601 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
5602 workspace.reopen_closed_item(window, cx).detach();
5603 },
5604 ))
5605 .on_action(cx.listener(
5606 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
5607 for dock in workspace.all_docks() {
5608 if dock.focus_handle(cx).contains_focused(window, cx) {
5609 let Some(panel) = dock.read(cx).active_panel() else {
5610 return;
5611 };
5612
5613 // Set to `None`, then the size will fall back to the default.
5614 panel.clone().set_size(None, window, cx);
5615
5616 return;
5617 }
5618 }
5619 },
5620 ))
5621 .on_action(cx.listener(
5622 |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
5623 for dock in workspace.all_docks() {
5624 if let Some(panel) = dock.read(cx).visible_panel() {
5625 // Set to `None`, then the size will fall back to the default.
5626 panel.clone().set_size(None, window, cx);
5627 }
5628 }
5629 },
5630 ))
5631 .on_action(cx.listener(
5632 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
5633 adjust_active_dock_size_by_px(
5634 px_with_ui_font_fallback(act.px, cx),
5635 workspace,
5636 window,
5637 cx,
5638 );
5639 },
5640 ))
5641 .on_action(cx.listener(
5642 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
5643 adjust_active_dock_size_by_px(
5644 px_with_ui_font_fallback(act.px, cx) * -1.,
5645 workspace,
5646 window,
5647 cx,
5648 );
5649 },
5650 ))
5651 .on_action(cx.listener(
5652 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
5653 adjust_open_docks_size_by_px(
5654 px_with_ui_font_fallback(act.px, cx),
5655 workspace,
5656 window,
5657 cx,
5658 );
5659 },
5660 ))
5661 .on_action(cx.listener(
5662 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
5663 adjust_open_docks_size_by_px(
5664 px_with_ui_font_fallback(act.px, cx) * -1.,
5665 workspace,
5666 window,
5667 cx,
5668 );
5669 },
5670 ))
5671 .on_action(cx.listener(Workspace::toggle_centered_layout))
5672 .on_action(cx.listener(Workspace::cancel))
5673 }
5674
5675 #[cfg(any(test, feature = "test-support"))]
5676 pub fn test_new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
5677 use node_runtime::NodeRuntime;
5678 use session::Session;
5679
5680 let client = project.read(cx).client();
5681 let user_store = project.read(cx).user_store();
5682 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
5683 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
5684 window.activate_window();
5685 let app_state = Arc::new(AppState {
5686 languages: project.read(cx).languages().clone(),
5687 workspace_store,
5688 client,
5689 user_store,
5690 fs: project.read(cx).fs().clone(),
5691 build_window_options: |_, _| Default::default(),
5692 node_runtime: NodeRuntime::unavailable(),
5693 session,
5694 });
5695 let workspace = Self::new(Default::default(), project, app_state, window, cx);
5696 workspace
5697 .active_pane
5698 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
5699 workspace
5700 }
5701
5702 pub fn register_action<A: Action>(
5703 &mut self,
5704 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
5705 ) -> &mut Self {
5706 let callback = Arc::new(callback);
5707
5708 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
5709 let callback = callback.clone();
5710 div.on_action(cx.listener(move |workspace, event, window, cx| {
5711 (callback)(workspace, event, window, cx)
5712 }))
5713 }));
5714 self
5715 }
5716 pub fn register_action_renderer(
5717 &mut self,
5718 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
5719 ) -> &mut Self {
5720 self.workspace_actions.push(Box::new(callback));
5721 self
5722 }
5723
5724 fn add_workspace_actions_listeners(
5725 &self,
5726 mut div: Div,
5727 window: &mut Window,
5728 cx: &mut Context<Self>,
5729 ) -> Div {
5730 for action in self.workspace_actions.iter() {
5731 div = (action)(div, self, window, cx)
5732 }
5733 div
5734 }
5735
5736 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
5737 self.modal_layer.read(cx).has_active_modal()
5738 }
5739
5740 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
5741 self.modal_layer.read(cx).active_modal()
5742 }
5743
5744 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
5745 where
5746 B: FnOnce(&mut Window, &mut Context<V>) -> V,
5747 {
5748 self.modal_layer.update(cx, |modal_layer, cx| {
5749 modal_layer.toggle_modal(window, cx, build)
5750 })
5751 }
5752
5753 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
5754 self.toast_layer
5755 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
5756 }
5757
5758 pub fn toggle_centered_layout(
5759 &mut self,
5760 _: &ToggleCenteredLayout,
5761 _: &mut Window,
5762 cx: &mut Context<Self>,
5763 ) {
5764 self.centered_layout = !self.centered_layout;
5765 if let Some(database_id) = self.database_id() {
5766 cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
5767 .detach_and_log_err(cx);
5768 }
5769 cx.notify();
5770 }
5771
5772 fn adjust_padding(padding: Option<f32>) -> f32 {
5773 padding
5774 .unwrap_or(Self::DEFAULT_PADDING)
5775 .clamp(0.0, Self::MAX_PADDING)
5776 }
5777
5778 fn render_dock(
5779 &self,
5780 position: DockPosition,
5781 dock: &Entity<Dock>,
5782 window: &mut Window,
5783 cx: &mut App,
5784 ) -> Option<Div> {
5785 if self.zoomed_position == Some(position) {
5786 return None;
5787 }
5788
5789 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
5790 let pane = panel.pane(cx)?;
5791 let follower_states = &self.follower_states;
5792 leader_border_for_pane(follower_states, &pane, window, cx)
5793 });
5794
5795 Some(
5796 div()
5797 .flex()
5798 .flex_none()
5799 .overflow_hidden()
5800 .child(dock.clone())
5801 .children(leader_border),
5802 )
5803 }
5804
5805 pub fn for_window(window: &mut Window, _: &mut App) -> Option<Entity<Workspace>> {
5806 window.root().flatten()
5807 }
5808
5809 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
5810 self.zoomed.as_ref()
5811 }
5812
5813 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
5814 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
5815 return;
5816 };
5817 let windows = cx.windows();
5818 let next_window =
5819 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
5820 || {
5821 windows
5822 .iter()
5823 .cycle()
5824 .skip_while(|window| window.window_id() != current_window_id)
5825 .nth(1)
5826 },
5827 );
5828
5829 if let Some(window) = next_window {
5830 window
5831 .update(cx, |_, window, _| window.activate_window())
5832 .ok();
5833 }
5834 }
5835
5836 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
5837 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
5838 return;
5839 };
5840 let windows = cx.windows();
5841 let prev_window =
5842 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
5843 || {
5844 windows
5845 .iter()
5846 .rev()
5847 .cycle()
5848 .skip_while(|window| window.window_id() != current_window_id)
5849 .nth(1)
5850 },
5851 );
5852
5853 if let Some(window) = prev_window {
5854 window
5855 .update(cx, |_, window, _| window.activate_window())
5856 .ok();
5857 }
5858 }
5859
5860 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
5861 if cx.stop_active_drag(window) {
5862 } else if let Some((notification_id, _)) = self.notifications.pop() {
5863 dismiss_app_notification(¬ification_id, cx);
5864 } else {
5865 cx.propagate();
5866 }
5867 }
5868
5869 fn adjust_dock_size_by_px(
5870 &mut self,
5871 panel_size: Pixels,
5872 dock_pos: DockPosition,
5873 px: Pixels,
5874 window: &mut Window,
5875 cx: &mut Context<Self>,
5876 ) {
5877 match dock_pos {
5878 DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
5879 DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
5880 DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
5881 }
5882 }
5883
5884 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
5885 let size = new_size.min(self.bounds.right() - RESIZE_HANDLE_SIZE);
5886
5887 self.left_dock.update(cx, |left_dock, cx| {
5888 if WorkspaceSettings::get_global(cx)
5889 .resize_all_panels_in_dock
5890 .contains(&DockPosition::Left)
5891 {
5892 left_dock.resize_all_panels(Some(size), window, cx);
5893 } else {
5894 left_dock.resize_active_panel(Some(size), window, cx);
5895 }
5896 });
5897 }
5898
5899 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
5900 let mut size = new_size.max(self.bounds.left() - RESIZE_HANDLE_SIZE);
5901 self.left_dock.read_with(cx, |left_dock, cx| {
5902 let left_dock_size = left_dock
5903 .active_panel_size(window, cx)
5904 .unwrap_or(Pixels(0.0));
5905 if left_dock_size + size > self.bounds.right() {
5906 size = self.bounds.right() - left_dock_size
5907 }
5908 });
5909 self.right_dock.update(cx, |right_dock, cx| {
5910 if WorkspaceSettings::get_global(cx)
5911 .resize_all_panels_in_dock
5912 .contains(&DockPosition::Right)
5913 {
5914 right_dock.resize_all_panels(Some(size), window, cx);
5915 } else {
5916 right_dock.resize_active_panel(Some(size), window, cx);
5917 }
5918 });
5919 }
5920
5921 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
5922 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
5923 self.bottom_dock.update(cx, |bottom_dock, cx| {
5924 if WorkspaceSettings::get_global(cx)
5925 .resize_all_panels_in_dock
5926 .contains(&DockPosition::Bottom)
5927 {
5928 bottom_dock.resize_all_panels(Some(size), window, cx);
5929 } else {
5930 bottom_dock.resize_active_panel(Some(size), window, cx);
5931 }
5932 });
5933 }
5934
5935 fn toggle_edit_predictions_all_files(
5936 &mut self,
5937 _: &ToggleEditPrediction,
5938 _window: &mut Window,
5939 cx: &mut Context<Self>,
5940 ) {
5941 let fs = self.project().read(cx).fs().clone();
5942 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
5943 update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
5944 file.defaults.show_edit_predictions = Some(!show_edit_predictions)
5945 });
5946 }
5947}
5948
5949fn leader_border_for_pane(
5950 follower_states: &HashMap<CollaboratorId, FollowerState>,
5951 pane: &Entity<Pane>,
5952 _: &Window,
5953 cx: &App,
5954) -> Option<Div> {
5955 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
5956 if state.pane() == pane {
5957 Some((*leader_id, state))
5958 } else {
5959 None
5960 }
5961 })?;
5962
5963 let mut leader_color = match leader_id {
5964 CollaboratorId::PeerId(leader_peer_id) => {
5965 let room = ActiveCall::try_global(cx)?.read(cx).room()?.read(cx);
5966 let leader = room.remote_participant_for_peer_id(leader_peer_id)?;
5967
5968 cx.theme()
5969 .players()
5970 .color_for_participant(leader.participant_index.0)
5971 .cursor
5972 }
5973 CollaboratorId::Agent => cx.theme().players().agent().cursor,
5974 };
5975 leader_color.fade_out(0.3);
5976 Some(
5977 div()
5978 .absolute()
5979 .size_full()
5980 .left_0()
5981 .top_0()
5982 .border_2()
5983 .border_color(leader_color),
5984 )
5985}
5986
5987fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
5988 ZED_WINDOW_POSITION
5989 .zip(*ZED_WINDOW_SIZE)
5990 .map(|(position, size)| Bounds {
5991 origin: position,
5992 size,
5993 })
5994}
5995
5996fn open_items(
5997 serialized_workspace: Option<SerializedWorkspace>,
5998 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
5999 window: &mut Window,
6000 cx: &mut Context<Workspace>,
6001) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
6002 let restored_items = serialized_workspace.map(|serialized_workspace| {
6003 Workspace::load_workspace(
6004 serialized_workspace,
6005 project_paths_to_open
6006 .iter()
6007 .map(|(_, project_path)| project_path)
6008 .cloned()
6009 .collect(),
6010 window,
6011 cx,
6012 )
6013 });
6014
6015 cx.spawn_in(window, async move |workspace, cx| {
6016 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
6017
6018 if let Some(restored_items) = restored_items {
6019 let restored_items = restored_items.await?;
6020
6021 let restored_project_paths = restored_items
6022 .iter()
6023 .filter_map(|item| {
6024 cx.update(|_, cx| item.as_ref()?.project_path(cx))
6025 .ok()
6026 .flatten()
6027 })
6028 .collect::<HashSet<_>>();
6029
6030 for restored_item in restored_items {
6031 opened_items.push(restored_item.map(Ok));
6032 }
6033
6034 project_paths_to_open
6035 .iter_mut()
6036 .for_each(|(_, project_path)| {
6037 if let Some(project_path_to_open) = project_path
6038 && restored_project_paths.contains(project_path_to_open)
6039 {
6040 *project_path = None;
6041 }
6042 });
6043 } else {
6044 for _ in 0..project_paths_to_open.len() {
6045 opened_items.push(None);
6046 }
6047 }
6048 assert!(opened_items.len() == project_paths_to_open.len());
6049
6050 let tasks =
6051 project_paths_to_open
6052 .into_iter()
6053 .enumerate()
6054 .map(|(ix, (abs_path, project_path))| {
6055 let workspace = workspace.clone();
6056 cx.spawn(async move |cx| {
6057 let file_project_path = project_path?;
6058 let abs_path_task = workspace.update(cx, |workspace, cx| {
6059 workspace.project().update(cx, |project, cx| {
6060 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
6061 })
6062 });
6063
6064 // We only want to open file paths here. If one of the items
6065 // here is a directory, it was already opened further above
6066 // with a `find_or_create_worktree`.
6067 if let Ok(task) = abs_path_task
6068 && task.await.is_none_or(|p| p.is_file())
6069 {
6070 return Some((
6071 ix,
6072 workspace
6073 .update_in(cx, |workspace, window, cx| {
6074 workspace.open_path(
6075 file_project_path,
6076 None,
6077 true,
6078 window,
6079 cx,
6080 )
6081 })
6082 .log_err()?
6083 .await,
6084 ));
6085 }
6086 None
6087 })
6088 });
6089
6090 let tasks = tasks.collect::<Vec<_>>();
6091
6092 let tasks = futures::future::join_all(tasks);
6093 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
6094 opened_items[ix] = Some(path_open_result);
6095 }
6096
6097 Ok(opened_items)
6098 })
6099}
6100
6101enum ActivateInDirectionTarget {
6102 Pane(Entity<Pane>),
6103 Dock(Entity<Dock>),
6104}
6105
6106fn notify_if_database_failed(workspace: WindowHandle<Workspace>, cx: &mut AsyncApp) {
6107 workspace
6108 .update(cx, |workspace, _, cx| {
6109 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
6110 struct DatabaseFailedNotification;
6111
6112 workspace.show_notification(
6113 NotificationId::unique::<DatabaseFailedNotification>(),
6114 cx,
6115 |cx| {
6116 cx.new(|cx| {
6117 MessageNotification::new("Failed to load the database file.", cx)
6118 .primary_message("File an Issue")
6119 .primary_icon(IconName::Plus)
6120 .primary_on_click(|window, cx| {
6121 window.dispatch_action(Box::new(FileBugReport), cx)
6122 })
6123 })
6124 },
6125 );
6126 }
6127 })
6128 .log_err();
6129}
6130
6131fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
6132 if val == 0 {
6133 ThemeSettings::get_global(cx).ui_font_size(cx)
6134 } else {
6135 px(val as f32)
6136 }
6137}
6138
6139fn adjust_active_dock_size_by_px(
6140 px: Pixels,
6141 workspace: &mut Workspace,
6142 window: &mut Window,
6143 cx: &mut Context<Workspace>,
6144) {
6145 let Some(active_dock) = workspace
6146 .all_docks()
6147 .into_iter()
6148 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
6149 else {
6150 return;
6151 };
6152 let dock = active_dock.read(cx);
6153 let Some(panel_size) = dock.active_panel_size(window, cx) else {
6154 return;
6155 };
6156 let dock_pos = dock.position();
6157 workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
6158}
6159
6160fn adjust_open_docks_size_by_px(
6161 px: Pixels,
6162 workspace: &mut Workspace,
6163 window: &mut Window,
6164 cx: &mut Context<Workspace>,
6165) {
6166 let docks = workspace
6167 .all_docks()
6168 .into_iter()
6169 .filter_map(|dock| {
6170 if dock.read(cx).is_open() {
6171 let dock = dock.read(cx);
6172 let panel_size = dock.active_panel_size(window, cx)?;
6173 let dock_pos = dock.position();
6174 Some((panel_size, dock_pos, px))
6175 } else {
6176 None
6177 }
6178 })
6179 .collect::<Vec<_>>();
6180
6181 docks
6182 .into_iter()
6183 .for_each(|(panel_size, dock_pos, offset)| {
6184 workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
6185 });
6186}
6187
6188impl Focusable for Workspace {
6189 fn focus_handle(&self, cx: &App) -> FocusHandle {
6190 self.active_pane.focus_handle(cx)
6191 }
6192}
6193
6194#[derive(Clone)]
6195struct DraggedDock(DockPosition);
6196
6197impl Render for DraggedDock {
6198 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
6199 gpui::Empty
6200 }
6201}
6202
6203impl Render for Workspace {
6204 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
6205 let mut context = KeyContext::new_with_defaults();
6206 context.add("Workspace");
6207 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6208 if let Some(status) = self
6209 .debugger_provider
6210 .as_ref()
6211 .and_then(|provider| provider.active_thread_state(cx))
6212 {
6213 match status {
6214 ThreadStatus::Running | ThreadStatus::Stepping => {
6215 context.add("debugger_running");
6216 }
6217 ThreadStatus::Stopped => context.add("debugger_stopped"),
6218 ThreadStatus::Exited | ThreadStatus::Ended => {}
6219 }
6220 }
6221
6222 let centered_layout = self.centered_layout
6223 && self.center.panes().len() == 1
6224 && self.active_item(cx).is_some();
6225 let render_padding = |size| {
6226 (size > 0.0).then(|| {
6227 div()
6228 .h_full()
6229 .w(relative(size))
6230 .bg(cx.theme().colors().editor_background)
6231 .border_color(cx.theme().colors().pane_group_border)
6232 })
6233 };
6234 let paddings = if centered_layout {
6235 let settings = WorkspaceSettings::get_global(cx).centered_layout;
6236 (
6237 render_padding(Self::adjust_padding(settings.left_padding)),
6238 render_padding(Self::adjust_padding(settings.right_padding)),
6239 )
6240 } else {
6241 (None, None)
6242 };
6243 let ui_font = theme::setup_ui_font(window, cx);
6244
6245 let theme = cx.theme().clone();
6246 let colors = theme.colors();
6247 let notification_entities = self
6248 .notifications
6249 .iter()
6250 .map(|(_, notification)| notification.entity_id())
6251 .collect::<Vec<_>>();
6252 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
6253
6254 client_side_decorations(
6255 self.actions(div(), window, cx)
6256 .key_context(context)
6257 .relative()
6258 .size_full()
6259 .flex()
6260 .flex_col()
6261 .font(ui_font)
6262 .gap_0()
6263 .justify_start()
6264 .items_start()
6265 .text_color(colors.text)
6266 .overflow_hidden()
6267 .children(self.titlebar_item.clone())
6268 .on_modifiers_changed(move |_, _, cx| {
6269 for &id in ¬ification_entities {
6270 cx.notify(id);
6271 }
6272 })
6273 .child(
6274 div()
6275 .size_full()
6276 .relative()
6277 .flex_1()
6278 .flex()
6279 .flex_col()
6280 .child(
6281 div()
6282 .id("workspace")
6283 .bg(colors.background)
6284 .relative()
6285 .flex_1()
6286 .w_full()
6287 .flex()
6288 .flex_col()
6289 .overflow_hidden()
6290 .border_t_1()
6291 .border_b_1()
6292 .border_color(colors.border)
6293 .child({
6294 let this = cx.entity();
6295 canvas(
6296 move |bounds, window, cx| {
6297 this.update(cx, |this, cx| {
6298 let bounds_changed = this.bounds != bounds;
6299 this.bounds = bounds;
6300
6301 if bounds_changed {
6302 this.left_dock.update(cx, |dock, cx| {
6303 dock.clamp_panel_size(
6304 bounds.size.width,
6305 window,
6306 cx,
6307 )
6308 });
6309
6310 this.right_dock.update(cx, |dock, cx| {
6311 dock.clamp_panel_size(
6312 bounds.size.width,
6313 window,
6314 cx,
6315 )
6316 });
6317
6318 this.bottom_dock.update(cx, |dock, cx| {
6319 dock.clamp_panel_size(
6320 bounds.size.height,
6321 window,
6322 cx,
6323 )
6324 });
6325 }
6326 })
6327 },
6328 |_, _, _, _| {},
6329 )
6330 .absolute()
6331 .size_full()
6332 })
6333 .when(self.zoomed.is_none(), |this| {
6334 this.on_drag_move(cx.listener(
6335 move |workspace,
6336 e: &DragMoveEvent<DraggedDock>,
6337 window,
6338 cx| {
6339 if workspace.previous_dock_drag_coordinates
6340 != Some(e.event.position)
6341 {
6342 workspace.previous_dock_drag_coordinates =
6343 Some(e.event.position);
6344 match e.drag(cx).0 {
6345 DockPosition::Left => {
6346 workspace.resize_left_dock(
6347 e.event.position.x
6348 - workspace.bounds.left(),
6349 window,
6350 cx,
6351 );
6352 }
6353 DockPosition::Right => {
6354 workspace.resize_right_dock(
6355 workspace.bounds.right()
6356 - e.event.position.x,
6357 window,
6358 cx,
6359 );
6360 }
6361 DockPosition::Bottom => {
6362 workspace.resize_bottom_dock(
6363 workspace.bounds.bottom()
6364 - e.event.position.y,
6365 window,
6366 cx,
6367 );
6368 }
6369 };
6370 workspace.serialize_workspace(window, cx);
6371 }
6372 },
6373 ))
6374 })
6375 .child({
6376 match bottom_dock_layout {
6377 BottomDockLayout::Full => div()
6378 .flex()
6379 .flex_col()
6380 .h_full()
6381 .child(
6382 div()
6383 .flex()
6384 .flex_row()
6385 .flex_1()
6386 .overflow_hidden()
6387 .children(self.render_dock(
6388 DockPosition::Left,
6389 &self.left_dock,
6390 window,
6391 cx,
6392 ))
6393 .child(
6394 div()
6395 .flex()
6396 .flex_col()
6397 .flex_1()
6398 .overflow_hidden()
6399 .child(
6400 h_flex()
6401 .flex_1()
6402 .when_some(
6403 paddings.0,
6404 |this, p| {
6405 this.child(
6406 p.border_r_1(),
6407 )
6408 },
6409 )
6410 .child(self.center.render(
6411 self.zoomed.as_ref(),
6412 &PaneRenderContext {
6413 follower_states:
6414 &self.follower_states,
6415 active_call: self.active_call(),
6416 active_pane: &self.active_pane,
6417 app_state: &self.app_state,
6418 project: &self.project,
6419 workspace: &self.weak_self,
6420 },
6421 window,
6422 cx,
6423 ))
6424 .when_some(
6425 paddings.1,
6426 |this, p| {
6427 this.child(
6428 p.border_l_1(),
6429 )
6430 },
6431 ),
6432 ),
6433 )
6434 .children(self.render_dock(
6435 DockPosition::Right,
6436 &self.right_dock,
6437 window,
6438 cx,
6439 )),
6440 )
6441 .child(div().w_full().children(self.render_dock(
6442 DockPosition::Bottom,
6443 &self.bottom_dock,
6444 window,
6445 cx
6446 ))),
6447
6448 BottomDockLayout::LeftAligned => div()
6449 .flex()
6450 .flex_row()
6451 .h_full()
6452 .child(
6453 div()
6454 .flex()
6455 .flex_col()
6456 .flex_1()
6457 .h_full()
6458 .child(
6459 div()
6460 .flex()
6461 .flex_row()
6462 .flex_1()
6463 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
6464 .child(
6465 div()
6466 .flex()
6467 .flex_col()
6468 .flex_1()
6469 .overflow_hidden()
6470 .child(
6471 h_flex()
6472 .flex_1()
6473 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
6474 .child(self.center.render(
6475 self.zoomed.as_ref(),
6476 &PaneRenderContext {
6477 follower_states:
6478 &self.follower_states,
6479 active_call: self.active_call(),
6480 active_pane: &self.active_pane,
6481 app_state: &self.app_state,
6482 project: &self.project,
6483 workspace: &self.weak_self,
6484 },
6485 window,
6486 cx,
6487 ))
6488 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
6489 )
6490 )
6491 )
6492 .child(
6493 div()
6494 .w_full()
6495 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
6496 ),
6497 )
6498 .children(self.render_dock(
6499 DockPosition::Right,
6500 &self.right_dock,
6501 window,
6502 cx,
6503 )),
6504
6505 BottomDockLayout::RightAligned => div()
6506 .flex()
6507 .flex_row()
6508 .h_full()
6509 .children(self.render_dock(
6510 DockPosition::Left,
6511 &self.left_dock,
6512 window,
6513 cx,
6514 ))
6515 .child(
6516 div()
6517 .flex()
6518 .flex_col()
6519 .flex_1()
6520 .h_full()
6521 .child(
6522 div()
6523 .flex()
6524 .flex_row()
6525 .flex_1()
6526 .child(
6527 div()
6528 .flex()
6529 .flex_col()
6530 .flex_1()
6531 .overflow_hidden()
6532 .child(
6533 h_flex()
6534 .flex_1()
6535 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
6536 .child(self.center.render(
6537 self.zoomed.as_ref(),
6538 &PaneRenderContext {
6539 follower_states:
6540 &self.follower_states,
6541 active_call: self.active_call(),
6542 active_pane: &self.active_pane,
6543 app_state: &self.app_state,
6544 project: &self.project,
6545 workspace: &self.weak_self,
6546 },
6547 window,
6548 cx,
6549 ))
6550 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
6551 )
6552 )
6553 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
6554 )
6555 .child(
6556 div()
6557 .w_full()
6558 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
6559 ),
6560 ),
6561
6562 BottomDockLayout::Contained => div()
6563 .flex()
6564 .flex_row()
6565 .h_full()
6566 .children(self.render_dock(
6567 DockPosition::Left,
6568 &self.left_dock,
6569 window,
6570 cx,
6571 ))
6572 .child(
6573 div()
6574 .flex()
6575 .flex_col()
6576 .flex_1()
6577 .overflow_hidden()
6578 .child(
6579 h_flex()
6580 .flex_1()
6581 .when_some(paddings.0, |this, p| {
6582 this.child(p.border_r_1())
6583 })
6584 .child(self.center.render(
6585 self.zoomed.as_ref(),
6586 &PaneRenderContext {
6587 follower_states:
6588 &self.follower_states,
6589 active_call: self.active_call(),
6590 active_pane: &self.active_pane,
6591 app_state: &self.app_state,
6592 project: &self.project,
6593 workspace: &self.weak_self,
6594 },
6595 window,
6596 cx,
6597 ))
6598 .when_some(paddings.1, |this, p| {
6599 this.child(p.border_l_1())
6600 }),
6601 )
6602 .children(self.render_dock(
6603 DockPosition::Bottom,
6604 &self.bottom_dock,
6605 window,
6606 cx,
6607 )),
6608 )
6609 .children(self.render_dock(
6610 DockPosition::Right,
6611 &self.right_dock,
6612 window,
6613 cx,
6614 )),
6615 }
6616 })
6617 .children(self.zoomed.as_ref().and_then(|view| {
6618 let zoomed_view = view.upgrade()?;
6619 let div = div()
6620 .occlude()
6621 .absolute()
6622 .overflow_hidden()
6623 .border_color(colors.border)
6624 .bg(colors.background)
6625 .child(zoomed_view)
6626 .inset_0()
6627 .shadow_lg();
6628
6629 if !WorkspaceSettings::get_global(cx).zoomed_padding {
6630 return Some(div);
6631 }
6632
6633 Some(match self.zoomed_position {
6634 Some(DockPosition::Left) => div.right_2().border_r_1(),
6635 Some(DockPosition::Right) => div.left_2().border_l_1(),
6636 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
6637 None => {
6638 div.top_2().bottom_2().left_2().right_2().border_1()
6639 }
6640 })
6641 }))
6642 .children(self.render_notifications(window, cx)),
6643 )
6644 .child(self.status_bar.clone())
6645 .child(self.modal_layer.clone())
6646 .child(self.toast_layer.clone()),
6647 ),
6648 window,
6649 cx,
6650 )
6651 }
6652}
6653
6654impl WorkspaceStore {
6655 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
6656 Self {
6657 workspaces: Default::default(),
6658 _subscriptions: vec![
6659 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
6660 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
6661 ],
6662 client,
6663 }
6664 }
6665
6666 pub fn update_followers(
6667 &self,
6668 project_id: Option<u64>,
6669 update: proto::update_followers::Variant,
6670 cx: &App,
6671 ) -> Option<()> {
6672 let active_call = ActiveCall::try_global(cx)?;
6673 let room_id = active_call.read(cx).room()?.read(cx).id();
6674 self.client
6675 .send(proto::UpdateFollowers {
6676 room_id,
6677 project_id,
6678 variant: Some(update),
6679 })
6680 .log_err()
6681 }
6682
6683 pub async fn handle_follow(
6684 this: Entity<Self>,
6685 envelope: TypedEnvelope<proto::Follow>,
6686 mut cx: AsyncApp,
6687 ) -> Result<proto::FollowResponse> {
6688 this.update(&mut cx, |this, cx| {
6689 let follower = Follower {
6690 project_id: envelope.payload.project_id,
6691 peer_id: envelope.original_sender_id()?,
6692 };
6693
6694 let mut response = proto::FollowResponse::default();
6695 this.workspaces.retain(|workspace| {
6696 workspace
6697 .update(cx, |workspace, window, cx| {
6698 let handler_response =
6699 workspace.handle_follow(follower.project_id, window, cx);
6700 if let Some(active_view) = handler_response.active_view
6701 && workspace.project.read(cx).remote_id() == follower.project_id
6702 {
6703 response.active_view = Some(active_view)
6704 }
6705 })
6706 .is_ok()
6707 });
6708
6709 Ok(response)
6710 })?
6711 }
6712
6713 async fn handle_update_followers(
6714 this: Entity<Self>,
6715 envelope: TypedEnvelope<proto::UpdateFollowers>,
6716 mut cx: AsyncApp,
6717 ) -> Result<()> {
6718 let leader_id = envelope.original_sender_id()?;
6719 let update = envelope.payload;
6720
6721 this.update(&mut cx, |this, cx| {
6722 this.workspaces.retain(|workspace| {
6723 workspace
6724 .update(cx, |workspace, window, cx| {
6725 let project_id = workspace.project.read(cx).remote_id();
6726 if update.project_id != project_id && update.project_id.is_some() {
6727 return;
6728 }
6729 workspace.handle_update_followers(leader_id, update.clone(), window, cx);
6730 })
6731 .is_ok()
6732 });
6733 Ok(())
6734 })?
6735 }
6736
6737 pub fn workspaces(&self) -> &HashSet<WindowHandle<Workspace>> {
6738 &self.workspaces
6739 }
6740}
6741
6742impl ViewId {
6743 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
6744 Ok(Self {
6745 creator: message
6746 .creator
6747 .map(CollaboratorId::PeerId)
6748 .context("creator is missing")?,
6749 id: message.id,
6750 })
6751 }
6752
6753 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
6754 if let CollaboratorId::PeerId(peer_id) = self.creator {
6755 Some(proto::ViewId {
6756 creator: Some(peer_id),
6757 id: self.id,
6758 })
6759 } else {
6760 None
6761 }
6762 }
6763}
6764
6765impl FollowerState {
6766 fn pane(&self) -> &Entity<Pane> {
6767 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
6768 }
6769}
6770
6771pub trait WorkspaceHandle {
6772 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
6773}
6774
6775impl WorkspaceHandle for Entity<Workspace> {
6776 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
6777 self.read(cx)
6778 .worktrees(cx)
6779 .flat_map(|worktree| {
6780 let worktree_id = worktree.read(cx).id();
6781 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
6782 worktree_id,
6783 path: f.path.clone(),
6784 })
6785 })
6786 .collect::<Vec<_>>()
6787 }
6788}
6789
6790pub async fn last_opened_workspace_location() -> Option<(SerializedWorkspaceLocation, PathList)> {
6791 DB.last_workspace().await.log_err().flatten()
6792}
6793
6794pub fn last_session_workspace_locations(
6795 last_session_id: &str,
6796 last_session_window_stack: Option<Vec<WindowId>>,
6797) -> Option<Vec<(SerializedWorkspaceLocation, PathList)>> {
6798 DB.last_session_workspace_locations(last_session_id, last_session_window_stack)
6799 .log_err()
6800}
6801
6802actions!(
6803 collab,
6804 [
6805 /// Opens the channel notes for the current call.
6806 ///
6807 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
6808 /// can be copied via "Copy link to section" in the context menu of the channel notes
6809 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
6810 OpenChannelNotes,
6811 /// Mutes your microphone.
6812 Mute,
6813 /// Deafens yourself (mute both microphone and speakers).
6814 Deafen,
6815 /// Leaves the current call.
6816 LeaveCall,
6817 /// Shares the current project with collaborators.
6818 ShareProject,
6819 /// Shares your screen with collaborators.
6820 ScreenShare
6821 ]
6822);
6823actions!(
6824 zed,
6825 [
6826 /// Opens the Zed log file.
6827 OpenLog
6828 ]
6829);
6830
6831async fn join_channel_internal(
6832 channel_id: ChannelId,
6833 app_state: &Arc<AppState>,
6834 requesting_window: Option<WindowHandle<Workspace>>,
6835 active_call: &Entity<ActiveCall>,
6836 cx: &mut AsyncApp,
6837) -> Result<bool> {
6838 let (should_prompt, open_room) = active_call.update(cx, |active_call, cx| {
6839 let Some(room) = active_call.room().map(|room| room.read(cx)) else {
6840 return (false, None);
6841 };
6842
6843 let already_in_channel = room.channel_id() == Some(channel_id);
6844 let should_prompt = room.is_sharing_project()
6845 && !room.remote_participants().is_empty()
6846 && !already_in_channel;
6847 let open_room = if already_in_channel {
6848 active_call.room().cloned()
6849 } else {
6850 None
6851 };
6852 (should_prompt, open_room)
6853 })?;
6854
6855 if let Some(room) = open_room {
6856 let task = room.update(cx, |room, cx| {
6857 if let Some((project, host)) = room.most_active_project(cx) {
6858 return Some(join_in_room_project(project, host, app_state.clone(), cx));
6859 }
6860
6861 None
6862 })?;
6863 if let Some(task) = task {
6864 task.await?;
6865 }
6866 return anyhow::Ok(true);
6867 }
6868
6869 if should_prompt {
6870 if let Some(workspace) = requesting_window {
6871 let answer = workspace
6872 .update(cx, |_, window, cx| {
6873 window.prompt(
6874 PromptLevel::Warning,
6875 "Do you want to switch channels?",
6876 Some("Leaving this call will unshare your current project."),
6877 &["Yes, Join Channel", "Cancel"],
6878 cx,
6879 )
6880 })?
6881 .await;
6882
6883 if answer == Ok(1) {
6884 return Ok(false);
6885 }
6886 } else {
6887 return Ok(false); // unreachable!() hopefully
6888 }
6889 }
6890
6891 let client = cx.update(|cx| active_call.read(cx).client())?;
6892
6893 let mut client_status = client.status();
6894
6895 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
6896 'outer: loop {
6897 let Some(status) = client_status.recv().await else {
6898 anyhow::bail!("error connecting");
6899 };
6900
6901 match status {
6902 Status::Connecting
6903 | Status::Authenticating
6904 | Status::Authenticated
6905 | Status::Reconnecting
6906 | Status::Reauthenticating
6907 | Status::Reauthenticated => continue,
6908 Status::Connected { .. } => break 'outer,
6909 Status::SignedOut | Status::AuthenticationError => {
6910 return Err(ErrorCode::SignedOut.into());
6911 }
6912 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
6913 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
6914 return Err(ErrorCode::Disconnected.into());
6915 }
6916 }
6917 }
6918
6919 let room = active_call
6920 .update(cx, |active_call, cx| {
6921 active_call.join_channel(channel_id, cx)
6922 })?
6923 .await?;
6924
6925 let Some(room) = room else {
6926 return anyhow::Ok(true);
6927 };
6928
6929 room.update(cx, |room, _| room.room_update_completed())?
6930 .await;
6931
6932 let task = room.update(cx, |room, cx| {
6933 if let Some((project, host)) = room.most_active_project(cx) {
6934 return Some(join_in_room_project(project, host, app_state.clone(), cx));
6935 }
6936
6937 // If you are the first to join a channel, see if you should share your project.
6938 if room.remote_participants().is_empty()
6939 && !room.local_participant_is_guest()
6940 && let Some(workspace) = requesting_window
6941 {
6942 let project = workspace.update(cx, |workspace, _, cx| {
6943 let project = workspace.project.read(cx);
6944
6945 if !CallSettings::get_global(cx).share_on_join {
6946 return None;
6947 }
6948
6949 if (project.is_local() || project.is_via_remote_server())
6950 && project.visible_worktrees(cx).any(|tree| {
6951 tree.read(cx)
6952 .root_entry()
6953 .is_some_and(|entry| entry.is_dir())
6954 })
6955 {
6956 Some(workspace.project.clone())
6957 } else {
6958 None
6959 }
6960 });
6961 if let Ok(Some(project)) = project {
6962 return Some(cx.spawn(async move |room, cx| {
6963 room.update(cx, |room, cx| room.share_project(project, cx))?
6964 .await?;
6965 Ok(())
6966 }));
6967 }
6968 }
6969
6970 None
6971 })?;
6972 if let Some(task) = task {
6973 task.await?;
6974 return anyhow::Ok(true);
6975 }
6976 anyhow::Ok(false)
6977}
6978
6979pub fn join_channel(
6980 channel_id: ChannelId,
6981 app_state: Arc<AppState>,
6982 requesting_window: Option<WindowHandle<Workspace>>,
6983 cx: &mut App,
6984) -> Task<Result<()>> {
6985 let active_call = ActiveCall::global(cx);
6986 cx.spawn(async move |cx| {
6987 let result = join_channel_internal(
6988 channel_id,
6989 &app_state,
6990 requesting_window,
6991 &active_call,
6992 cx,
6993 )
6994 .await;
6995
6996 // join channel succeeded, and opened a window
6997 if matches!(result, Ok(true)) {
6998 return anyhow::Ok(());
6999 }
7000
7001 // find an existing workspace to focus and show call controls
7002 let mut active_window =
7003 requesting_window.or_else(|| activate_any_workspace_window( cx));
7004 if active_window.is_none() {
7005 // no open workspaces, make one to show the error in (blergh)
7006 let (window_handle, _) = cx
7007 .update(|cx| {
7008 Workspace::new_local(vec![], app_state.clone(), requesting_window, None, cx)
7009 })?
7010 .await?;
7011
7012 if result.is_ok() {
7013 cx.update(|cx| {
7014 cx.dispatch_action(&OpenChannelNotes);
7015 }).log_err();
7016 }
7017
7018 active_window = Some(window_handle);
7019 }
7020
7021 if let Err(err) = result {
7022 log::error!("failed to join channel: {}", err);
7023 if let Some(active_window) = active_window {
7024 active_window
7025 .update(cx, |_, window, cx| {
7026 let detail: SharedString = match err.error_code() {
7027 ErrorCode::SignedOut => {
7028 "Please sign in to continue.".into()
7029 }
7030 ErrorCode::UpgradeRequired => {
7031 "Your are running an unsupported version of Zed. Please update to continue.".into()
7032 }
7033 ErrorCode::NoSuchChannel => {
7034 "No matching channel was found. Please check the link and try again.".into()
7035 }
7036 ErrorCode::Forbidden => {
7037 "This channel is private, and you do not have access. Please ask someone to add you and try again.".into()
7038 }
7039 ErrorCode::Disconnected => "Please check your internet connection and try again.".into(),
7040 _ => format!("{}\n\nPlease try again.", err).into(),
7041 };
7042 window.prompt(
7043 PromptLevel::Critical,
7044 "Failed to join channel",
7045 Some(&detail),
7046 &["Ok"],
7047 cx)
7048 })?
7049 .await
7050 .ok();
7051 }
7052 }
7053
7054 // return ok, we showed the error to the user.
7055 anyhow::Ok(())
7056 })
7057}
7058
7059pub async fn get_any_active_workspace(
7060 app_state: Arc<AppState>,
7061 mut cx: AsyncApp,
7062) -> anyhow::Result<WindowHandle<Workspace>> {
7063 // find an existing workspace to focus and show call controls
7064 let active_window = activate_any_workspace_window(&mut cx);
7065 if active_window.is_none() {
7066 cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, cx))?
7067 .await?;
7068 }
7069 activate_any_workspace_window(&mut cx).context("could not open zed")
7070}
7071
7072fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<Workspace>> {
7073 cx.update(|cx| {
7074 if let Some(workspace_window) = cx
7075 .active_window()
7076 .and_then(|window| window.downcast::<Workspace>())
7077 {
7078 return Some(workspace_window);
7079 }
7080
7081 for window in cx.windows() {
7082 if let Some(workspace_window) = window.downcast::<Workspace>() {
7083 workspace_window
7084 .update(cx, |_, window, _| window.activate_window())
7085 .ok();
7086 return Some(workspace_window);
7087 }
7088 }
7089 None
7090 })
7091 .ok()
7092 .flatten()
7093}
7094
7095pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<Workspace>> {
7096 cx.windows()
7097 .into_iter()
7098 .filter_map(|window| window.downcast::<Workspace>())
7099 .filter(|workspace| {
7100 workspace
7101 .read(cx)
7102 .is_ok_and(|workspace| workspace.project.read(cx).is_local())
7103 })
7104 .collect()
7105}
7106
7107#[derive(Default)]
7108pub struct OpenOptions {
7109 pub visible: Option<OpenVisible>,
7110 pub focus: Option<bool>,
7111 pub open_new_workspace: Option<bool>,
7112 pub replace_window: Option<WindowHandle<Workspace>>,
7113 pub env: Option<HashMap<String, String>>,
7114}
7115
7116#[allow(clippy::type_complexity)]
7117pub fn open_paths(
7118 abs_paths: &[PathBuf],
7119 app_state: Arc<AppState>,
7120 open_options: OpenOptions,
7121 cx: &mut App,
7122) -> Task<
7123 anyhow::Result<(
7124 WindowHandle<Workspace>,
7125 Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
7126 )>,
7127> {
7128 let abs_paths = abs_paths.to_vec();
7129 let mut existing = None;
7130 let mut best_match = None;
7131 let mut open_visible = OpenVisible::All;
7132
7133 cx.spawn(async move |cx| {
7134 if open_options.open_new_workspace != Some(true) {
7135 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
7136 let all_metadatas = futures::future::join_all(all_paths)
7137 .await
7138 .into_iter()
7139 .filter_map(|result| result.ok().flatten())
7140 .collect::<Vec<_>>();
7141
7142 cx.update(|cx| {
7143 for window in local_workspace_windows(cx) {
7144 if let Ok(workspace) = window.read(cx) {
7145 let m = workspace.project.read(cx).visibility_for_paths(
7146 &abs_paths,
7147 &all_metadatas,
7148 open_options.open_new_workspace == None,
7149 cx,
7150 );
7151 if m > best_match {
7152 existing = Some(window);
7153 best_match = m;
7154 } else if best_match.is_none()
7155 && open_options.open_new_workspace == Some(false)
7156 {
7157 existing = Some(window)
7158 }
7159 }
7160 }
7161 })?;
7162
7163 if open_options.open_new_workspace.is_none()
7164 && existing.is_none()
7165 && all_metadatas.iter().all(|file| !file.is_dir)
7166 {
7167 cx.update(|cx| {
7168 if let Some(window) = cx
7169 .active_window()
7170 .and_then(|window| window.downcast::<Workspace>())
7171 && let Ok(workspace) = window.read(cx)
7172 {
7173 let project = workspace.project().read(cx);
7174 if project.is_local() && !project.is_via_collab() {
7175 existing = Some(window);
7176 open_visible = OpenVisible::None;
7177 return;
7178 }
7179 }
7180 for window in local_workspace_windows(cx) {
7181 if let Ok(workspace) = window.read(cx) {
7182 let project = workspace.project().read(cx);
7183 if project.is_via_collab() {
7184 continue;
7185 }
7186 existing = Some(window);
7187 open_visible = OpenVisible::None;
7188 break;
7189 }
7190 }
7191 })?;
7192 }
7193 }
7194
7195 if let Some(existing) = existing {
7196 let open_task = existing
7197 .update(cx, |workspace, window, cx| {
7198 window.activate_window();
7199 workspace.open_paths(
7200 abs_paths,
7201 OpenOptions {
7202 visible: Some(open_visible),
7203 ..Default::default()
7204 },
7205 None,
7206 window,
7207 cx,
7208 )
7209 })?
7210 .await;
7211
7212 _ = existing.update(cx, |workspace, _, cx| {
7213 for item in open_task.iter().flatten() {
7214 if let Err(e) = item {
7215 workspace.show_error(&e, cx);
7216 }
7217 }
7218 });
7219
7220 Ok((existing, open_task))
7221 } else {
7222 cx.update(move |cx| {
7223 Workspace::new_local(
7224 abs_paths,
7225 app_state.clone(),
7226 open_options.replace_window,
7227 open_options.env,
7228 cx,
7229 )
7230 })?
7231 .await
7232 }
7233 })
7234}
7235
7236pub fn open_new(
7237 open_options: OpenOptions,
7238 app_state: Arc<AppState>,
7239 cx: &mut App,
7240 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
7241) -> Task<anyhow::Result<()>> {
7242 let task = Workspace::new_local(Vec::new(), app_state, None, open_options.env, cx);
7243 cx.spawn(async move |cx| {
7244 let (workspace, opened_paths) = task.await?;
7245 workspace.update(cx, |workspace, window, cx| {
7246 if opened_paths.is_empty() {
7247 init(workspace, window, cx)
7248 }
7249 })?;
7250 Ok(())
7251 })
7252}
7253
7254pub fn create_and_open_local_file(
7255 path: &'static Path,
7256 window: &mut Window,
7257 cx: &mut Context<Workspace>,
7258 default_content: impl 'static + Send + FnOnce() -> Rope,
7259) -> Task<Result<Box<dyn ItemHandle>>> {
7260 cx.spawn_in(window, async move |workspace, cx| {
7261 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
7262 if !fs.is_file(path).await {
7263 fs.create_file(path, Default::default()).await?;
7264 fs.save(path, &default_content(), Default::default())
7265 .await?;
7266 }
7267
7268 let mut items = workspace
7269 .update_in(cx, |workspace, window, cx| {
7270 workspace.with_local_workspace(window, cx, |workspace, window, cx| {
7271 workspace.open_paths(
7272 vec![path.to_path_buf()],
7273 OpenOptions {
7274 visible: Some(OpenVisible::None),
7275 ..Default::default()
7276 },
7277 None,
7278 window,
7279 cx,
7280 )
7281 })
7282 })?
7283 .await?
7284 .await;
7285
7286 let item = items.pop().flatten();
7287 item.with_context(|| format!("path {path:?} is not a file"))?
7288 })
7289}
7290
7291pub fn open_remote_project_with_new_connection(
7292 window: WindowHandle<Workspace>,
7293 connection_options: RemoteConnectionOptions,
7294 cancel_rx: oneshot::Receiver<()>,
7295 delegate: Arc<dyn RemoteClientDelegate>,
7296 app_state: Arc<AppState>,
7297 paths: Vec<PathBuf>,
7298 cx: &mut App,
7299) -> Task<Result<()>> {
7300 cx.spawn(async move |cx| {
7301 let (workspace_id, serialized_workspace) =
7302 serialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
7303
7304 let session = match cx
7305 .update(|cx| {
7306 remote::RemoteClient::new(
7307 ConnectionIdentifier::Workspace(workspace_id.0),
7308 connection_options,
7309 cancel_rx,
7310 delegate,
7311 cx,
7312 )
7313 })?
7314 .await?
7315 {
7316 Some(result) => result,
7317 None => return Ok(()),
7318 };
7319
7320 let project = cx.update(|cx| {
7321 project::Project::remote(
7322 session,
7323 app_state.client.clone(),
7324 app_state.node_runtime.clone(),
7325 app_state.user_store.clone(),
7326 app_state.languages.clone(),
7327 app_state.fs.clone(),
7328 cx,
7329 )
7330 })?;
7331
7332 open_remote_project_inner(
7333 project,
7334 paths,
7335 workspace_id,
7336 serialized_workspace,
7337 app_state,
7338 window,
7339 cx,
7340 )
7341 .await
7342 })
7343}
7344
7345pub fn open_remote_project_with_existing_connection(
7346 connection_options: RemoteConnectionOptions,
7347 project: Entity<Project>,
7348 paths: Vec<PathBuf>,
7349 app_state: Arc<AppState>,
7350 window: WindowHandle<Workspace>,
7351 cx: &mut AsyncApp,
7352) -> Task<Result<()>> {
7353 cx.spawn(async move |cx| {
7354 let (workspace_id, serialized_workspace) =
7355 serialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
7356
7357 open_remote_project_inner(
7358 project,
7359 paths,
7360 workspace_id,
7361 serialized_workspace,
7362 app_state,
7363 window,
7364 cx,
7365 )
7366 .await
7367 })
7368}
7369
7370async fn open_remote_project_inner(
7371 project: Entity<Project>,
7372 paths: Vec<PathBuf>,
7373 workspace_id: WorkspaceId,
7374 serialized_workspace: Option<SerializedWorkspace>,
7375 app_state: Arc<AppState>,
7376 window: WindowHandle<Workspace>,
7377 cx: &mut AsyncApp,
7378) -> Result<()> {
7379 let toolchains = DB.toolchains(workspace_id).await?;
7380 for (toolchain, worktree_id, path) in toolchains {
7381 project
7382 .update(cx, |this, cx| {
7383 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
7384 })?
7385 .await;
7386 }
7387 let mut project_paths_to_open = vec![];
7388 let mut project_path_errors = vec![];
7389
7390 for path in paths {
7391 let result = cx
7392 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))?
7393 .await;
7394 match result {
7395 Ok((_, project_path)) => {
7396 project_paths_to_open.push((path.clone(), Some(project_path)));
7397 }
7398 Err(error) => {
7399 project_path_errors.push(error);
7400 }
7401 };
7402 }
7403
7404 if project_paths_to_open.is_empty() {
7405 return Err(project_path_errors.pop().context("no paths given")?);
7406 }
7407
7408 if let Some(detach_session_task) = window
7409 .update(cx, |_workspace, window, cx| {
7410 cx.spawn_in(window, async move |this, cx| {
7411 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))
7412 })
7413 })
7414 .ok()
7415 {
7416 detach_session_task.await.ok();
7417 }
7418
7419 cx.update_window(window.into(), |_, window, cx| {
7420 window.replace_root(cx, |window, cx| {
7421 telemetry::event!("SSH Project Opened");
7422
7423 let mut workspace =
7424 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
7425 workspace.update_history(cx);
7426
7427 if let Some(ref serialized) = serialized_workspace {
7428 workspace.centered_layout = serialized.centered_layout;
7429 }
7430
7431 workspace
7432 });
7433 })?;
7434
7435 window
7436 .update(cx, |_, window, cx| {
7437 window.activate_window();
7438 open_items(serialized_workspace, project_paths_to_open, window, cx)
7439 })?
7440 .await?;
7441
7442 window.update(cx, |workspace, _, cx| {
7443 for error in project_path_errors {
7444 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
7445 if let Some(path) = error.error_tag("path") {
7446 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
7447 }
7448 } else {
7449 workspace.show_error(&error, cx)
7450 }
7451 }
7452 })?;
7453
7454 Ok(())
7455}
7456
7457fn serialize_remote_project(
7458 connection_options: RemoteConnectionOptions,
7459 paths: Vec<PathBuf>,
7460 cx: &AsyncApp,
7461) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
7462 cx.background_spawn(async move {
7463 let remote_connection_id = persistence::DB
7464 .get_or_create_remote_connection(connection_options)
7465 .await?;
7466
7467 let serialized_workspace =
7468 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
7469
7470 let workspace_id = if let Some(workspace_id) =
7471 serialized_workspace.as_ref().map(|workspace| workspace.id)
7472 {
7473 workspace_id
7474 } else {
7475 persistence::DB.next_id().await?
7476 };
7477
7478 Ok((workspace_id, serialized_workspace))
7479 })
7480}
7481
7482pub fn join_in_room_project(
7483 project_id: u64,
7484 follow_user_id: u64,
7485 app_state: Arc<AppState>,
7486 cx: &mut App,
7487) -> Task<Result<()>> {
7488 let windows = cx.windows();
7489 cx.spawn(async move |cx| {
7490 let existing_workspace = windows.into_iter().find_map(|window_handle| {
7491 window_handle
7492 .downcast::<Workspace>()
7493 .and_then(|window_handle| {
7494 window_handle
7495 .update(cx, |workspace, _window, cx| {
7496 if workspace.project().read(cx).remote_id() == Some(project_id) {
7497 Some(window_handle)
7498 } else {
7499 None
7500 }
7501 })
7502 .unwrap_or(None)
7503 })
7504 });
7505
7506 let workspace = if let Some(existing_workspace) = existing_workspace {
7507 existing_workspace
7508 } else {
7509 let active_call = cx.update(|cx| ActiveCall::global(cx))?;
7510 let room = active_call
7511 .read_with(cx, |call, _| call.room().cloned())?
7512 .context("not in a call")?;
7513 let project = room
7514 .update(cx, |room, cx| {
7515 room.join_project(
7516 project_id,
7517 app_state.languages.clone(),
7518 app_state.fs.clone(),
7519 cx,
7520 )
7521 })?
7522 .await?;
7523
7524 let window_bounds_override = window_bounds_env_override();
7525 cx.update(|cx| {
7526 let mut options = (app_state.build_window_options)(None, cx);
7527 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
7528 cx.open_window(options, |window, cx| {
7529 cx.new(|cx| {
7530 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
7531 })
7532 })
7533 })??
7534 };
7535
7536 workspace.update(cx, |workspace, window, cx| {
7537 cx.activate(true);
7538 window.activate_window();
7539
7540 if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
7541 let follow_peer_id = room
7542 .read(cx)
7543 .remote_participants()
7544 .iter()
7545 .find(|(_, participant)| participant.user.id == follow_user_id)
7546 .map(|(_, p)| p.peer_id)
7547 .or_else(|| {
7548 // If we couldn't follow the given user, follow the host instead.
7549 let collaborator = workspace
7550 .project()
7551 .read(cx)
7552 .collaborators()
7553 .values()
7554 .find(|collaborator| collaborator.is_host)?;
7555 Some(collaborator.peer_id)
7556 });
7557
7558 if let Some(follow_peer_id) = follow_peer_id {
7559 workspace.follow(follow_peer_id, window, cx);
7560 }
7561 }
7562 })?;
7563
7564 anyhow::Ok(())
7565 })
7566}
7567
7568pub fn reload(cx: &mut App) {
7569 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
7570 let mut workspace_windows = cx
7571 .windows()
7572 .into_iter()
7573 .filter_map(|window| window.downcast::<Workspace>())
7574 .collect::<Vec<_>>();
7575
7576 // If multiple windows have unsaved changes, and need a save prompt,
7577 // prompt in the active window before switching to a different window.
7578 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
7579
7580 let mut prompt = None;
7581 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
7582 prompt = window
7583 .update(cx, |_, window, cx| {
7584 window.prompt(
7585 PromptLevel::Info,
7586 "Are you sure you want to restart?",
7587 None,
7588 &["Restart", "Cancel"],
7589 cx,
7590 )
7591 })
7592 .ok();
7593 }
7594
7595 cx.spawn(async move |cx| {
7596 if let Some(prompt) = prompt {
7597 let answer = prompt.await?;
7598 if answer != 0 {
7599 return Ok(());
7600 }
7601 }
7602
7603 // If the user cancels any save prompt, then keep the app open.
7604 for window in workspace_windows {
7605 if let Ok(should_close) = window.update(cx, |workspace, window, cx| {
7606 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
7607 }) && !should_close.await?
7608 {
7609 return Ok(());
7610 }
7611 }
7612 cx.update(|cx| cx.restart())
7613 })
7614 .detach_and_log_err(cx);
7615}
7616
7617fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
7618 let mut parts = value.split(',');
7619 let x: usize = parts.next()?.parse().ok()?;
7620 let y: usize = parts.next()?.parse().ok()?;
7621 Some(point(px(x as f32), px(y as f32)))
7622}
7623
7624fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
7625 let mut parts = value.split(',');
7626 let width: usize = parts.next()?.parse().ok()?;
7627 let height: usize = parts.next()?.parse().ok()?;
7628 Some(size(px(width as f32), px(height as f32)))
7629}
7630
7631/// Add client-side decorations (rounded corners, shadows, resize handling) when appropriate.
7632pub fn client_side_decorations(
7633 element: impl IntoElement,
7634 window: &mut Window,
7635 cx: &mut App,
7636) -> Stateful<Div> {
7637 const BORDER_SIZE: Pixels = px(1.0);
7638 let decorations = window.window_decorations();
7639
7640 match decorations {
7641 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
7642 Decorations::Server => window.set_client_inset(px(0.0)),
7643 }
7644
7645 struct GlobalResizeEdge(ResizeEdge);
7646 impl Global for GlobalResizeEdge {}
7647
7648 div()
7649 .id("window-backdrop")
7650 .bg(transparent_black())
7651 .map(|div| match decorations {
7652 Decorations::Server => div,
7653 Decorations::Client { tiling, .. } => div
7654 .when(!(tiling.top || tiling.right), |div| {
7655 div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
7656 })
7657 .when(!(tiling.top || tiling.left), |div| {
7658 div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
7659 })
7660 .when(!(tiling.bottom || tiling.right), |div| {
7661 div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
7662 })
7663 .when(!(tiling.bottom || tiling.left), |div| {
7664 div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
7665 })
7666 .when(!tiling.top, |div| {
7667 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
7668 })
7669 .when(!tiling.bottom, |div| {
7670 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
7671 })
7672 .when(!tiling.left, |div| {
7673 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
7674 })
7675 .when(!tiling.right, |div| {
7676 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
7677 })
7678 .on_mouse_move(move |e, window, cx| {
7679 let size = window.window_bounds().get_bounds().size;
7680 let pos = e.position;
7681
7682 let new_edge =
7683 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
7684
7685 let edge = cx.try_global::<GlobalResizeEdge>();
7686 if new_edge != edge.map(|edge| edge.0) {
7687 window
7688 .window_handle()
7689 .update(cx, |workspace, _, cx| {
7690 cx.notify(workspace.entity_id());
7691 })
7692 .ok();
7693 }
7694 })
7695 .on_mouse_down(MouseButton::Left, move |e, window, _| {
7696 let size = window.window_bounds().get_bounds().size;
7697 let pos = e.position;
7698
7699 let edge = match resize_edge(
7700 pos,
7701 theme::CLIENT_SIDE_DECORATION_SHADOW,
7702 size,
7703 tiling,
7704 ) {
7705 Some(value) => value,
7706 None => return,
7707 };
7708
7709 window.start_window_resize(edge);
7710 }),
7711 })
7712 .size_full()
7713 .child(
7714 div()
7715 .cursor(CursorStyle::Arrow)
7716 .map(|div| match decorations {
7717 Decorations::Server => div,
7718 Decorations::Client { tiling } => div
7719 .border_color(cx.theme().colors().border)
7720 .when(!(tiling.top || tiling.right), |div| {
7721 div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
7722 })
7723 .when(!(tiling.top || tiling.left), |div| {
7724 div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
7725 })
7726 .when(!(tiling.bottom || tiling.right), |div| {
7727 div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
7728 })
7729 .when(!(tiling.bottom || tiling.left), |div| {
7730 div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
7731 })
7732 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
7733 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
7734 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
7735 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
7736 .when(!tiling.is_tiled(), |div| {
7737 div.shadow(vec![gpui::BoxShadow {
7738 color: Hsla {
7739 h: 0.,
7740 s: 0.,
7741 l: 0.,
7742 a: 0.4,
7743 },
7744 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
7745 spread_radius: px(0.),
7746 offset: point(px(0.0), px(0.0)),
7747 }])
7748 }),
7749 })
7750 .on_mouse_move(|_e, _, cx| {
7751 cx.stop_propagation();
7752 })
7753 .size_full()
7754 .child(element),
7755 )
7756 .map(|div| match decorations {
7757 Decorations::Server => div,
7758 Decorations::Client { tiling, .. } => div.child(
7759 canvas(
7760 |_bounds, window, _| {
7761 window.insert_hitbox(
7762 Bounds::new(
7763 point(px(0.0), px(0.0)),
7764 window.window_bounds().get_bounds().size,
7765 ),
7766 HitboxBehavior::Normal,
7767 )
7768 },
7769 move |_bounds, hitbox, window, cx| {
7770 let mouse = window.mouse_position();
7771 let size = window.window_bounds().get_bounds().size;
7772 let Some(edge) =
7773 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
7774 else {
7775 return;
7776 };
7777 cx.set_global(GlobalResizeEdge(edge));
7778 window.set_cursor_style(
7779 match edge {
7780 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
7781 ResizeEdge::Left | ResizeEdge::Right => {
7782 CursorStyle::ResizeLeftRight
7783 }
7784 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
7785 CursorStyle::ResizeUpLeftDownRight
7786 }
7787 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
7788 CursorStyle::ResizeUpRightDownLeft
7789 }
7790 },
7791 &hitbox,
7792 );
7793 },
7794 )
7795 .size_full()
7796 .absolute(),
7797 ),
7798 })
7799}
7800
7801fn resize_edge(
7802 pos: Point<Pixels>,
7803 shadow_size: Pixels,
7804 window_size: Size<Pixels>,
7805 tiling: Tiling,
7806) -> Option<ResizeEdge> {
7807 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
7808 if bounds.contains(&pos) {
7809 return None;
7810 }
7811
7812 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
7813 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
7814 if !tiling.top && top_left_bounds.contains(&pos) {
7815 return Some(ResizeEdge::TopLeft);
7816 }
7817
7818 let top_right_bounds = Bounds::new(
7819 Point::new(window_size.width - corner_size.width, px(0.)),
7820 corner_size,
7821 );
7822 if !tiling.top && top_right_bounds.contains(&pos) {
7823 return Some(ResizeEdge::TopRight);
7824 }
7825
7826 let bottom_left_bounds = Bounds::new(
7827 Point::new(px(0.), window_size.height - corner_size.height),
7828 corner_size,
7829 );
7830 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
7831 return Some(ResizeEdge::BottomLeft);
7832 }
7833
7834 let bottom_right_bounds = Bounds::new(
7835 Point::new(
7836 window_size.width - corner_size.width,
7837 window_size.height - corner_size.height,
7838 ),
7839 corner_size,
7840 );
7841 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
7842 return Some(ResizeEdge::BottomRight);
7843 }
7844
7845 if !tiling.top && pos.y < shadow_size {
7846 Some(ResizeEdge::Top)
7847 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
7848 Some(ResizeEdge::Bottom)
7849 } else if !tiling.left && pos.x < shadow_size {
7850 Some(ResizeEdge::Left)
7851 } else if !tiling.right && pos.x > window_size.width - shadow_size {
7852 Some(ResizeEdge::Right)
7853 } else {
7854 None
7855 }
7856}
7857
7858fn join_pane_into_active(
7859 active_pane: &Entity<Pane>,
7860 pane: &Entity<Pane>,
7861 window: &mut Window,
7862 cx: &mut App,
7863) {
7864 if pane == active_pane {
7865 } else if pane.read(cx).items_len() == 0 {
7866 pane.update(cx, |_, cx| {
7867 cx.emit(pane::Event::Remove {
7868 focus_on_pane: None,
7869 });
7870 })
7871 } else {
7872 move_all_items(pane, active_pane, window, cx);
7873 }
7874}
7875
7876fn move_all_items(
7877 from_pane: &Entity<Pane>,
7878 to_pane: &Entity<Pane>,
7879 window: &mut Window,
7880 cx: &mut App,
7881) {
7882 let destination_is_different = from_pane != to_pane;
7883 let mut moved_items = 0;
7884 for (item_ix, item_handle) in from_pane
7885 .read(cx)
7886 .items()
7887 .enumerate()
7888 .map(|(ix, item)| (ix, item.clone()))
7889 .collect::<Vec<_>>()
7890 {
7891 let ix = item_ix - moved_items;
7892 if destination_is_different {
7893 // Close item from previous pane
7894 from_pane.update(cx, |source, cx| {
7895 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
7896 });
7897 moved_items += 1;
7898 }
7899
7900 // This automatically removes duplicate items in the pane
7901 to_pane.update(cx, |destination, cx| {
7902 destination.add_item(item_handle, true, true, None, window, cx);
7903 window.focus(&destination.focus_handle(cx))
7904 });
7905 }
7906}
7907
7908pub fn move_item(
7909 source: &Entity<Pane>,
7910 destination: &Entity<Pane>,
7911 item_id_to_move: EntityId,
7912 destination_index: usize,
7913 activate: bool,
7914 window: &mut Window,
7915 cx: &mut App,
7916) {
7917 let Some((item_ix, item_handle)) = source
7918 .read(cx)
7919 .items()
7920 .enumerate()
7921 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
7922 .map(|(ix, item)| (ix, item.clone()))
7923 else {
7924 // Tab was closed during drag
7925 return;
7926 };
7927
7928 if source != destination {
7929 // Close item from previous pane
7930 source.update(cx, |source, cx| {
7931 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
7932 });
7933 }
7934
7935 // This automatically removes duplicate items in the pane
7936 destination.update(cx, |destination, cx| {
7937 destination.add_item_inner(
7938 item_handle,
7939 activate,
7940 activate,
7941 activate,
7942 Some(destination_index),
7943 window,
7944 cx,
7945 );
7946 if activate {
7947 window.focus(&destination.focus_handle(cx))
7948 }
7949 });
7950}
7951
7952pub fn move_active_item(
7953 source: &Entity<Pane>,
7954 destination: &Entity<Pane>,
7955 focus_destination: bool,
7956 close_if_empty: bool,
7957 window: &mut Window,
7958 cx: &mut App,
7959) {
7960 if source == destination {
7961 return;
7962 }
7963 let Some(active_item) = source.read(cx).active_item() else {
7964 return;
7965 };
7966 source.update(cx, |source_pane, cx| {
7967 let item_id = active_item.item_id();
7968 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
7969 destination.update(cx, |target_pane, cx| {
7970 target_pane.add_item(
7971 active_item,
7972 focus_destination,
7973 focus_destination,
7974 Some(target_pane.items_len()),
7975 window,
7976 cx,
7977 );
7978 });
7979 });
7980}
7981
7982pub fn clone_active_item(
7983 workspace_id: Option<WorkspaceId>,
7984 source: &Entity<Pane>,
7985 destination: &Entity<Pane>,
7986 focus_destination: bool,
7987 window: &mut Window,
7988 cx: &mut App,
7989) {
7990 if source == destination {
7991 return;
7992 }
7993 let Some(active_item) = source.read(cx).active_item() else {
7994 return;
7995 };
7996 destination.update(cx, |target_pane, cx| {
7997 let Some(clone) = active_item.clone_on_split(workspace_id, window, cx) else {
7998 return;
7999 };
8000 target_pane.add_item(
8001 clone,
8002 focus_destination,
8003 focus_destination,
8004 Some(target_pane.items_len()),
8005 window,
8006 cx,
8007 );
8008 });
8009}
8010
8011#[derive(Debug)]
8012pub struct WorkspacePosition {
8013 pub window_bounds: Option<WindowBounds>,
8014 pub display: Option<Uuid>,
8015 pub centered_layout: bool,
8016}
8017
8018pub fn remote_workspace_position_from_db(
8019 connection_options: RemoteConnectionOptions,
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 remote_connection_id = persistence::DB
8027 .get_or_create_remote_connection(connection_options)
8028 .await
8029 .context("fetching serialized ssh project")?;
8030 let serialized_workspace =
8031 persistence::DB.remote_workspace_for_roots(&paths, remote_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}