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