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