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