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