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 println!("{:?}", *self.encoding.lock().unwrap());
3420 cx.spawn_in(window, async move |workspace, cx| {
3421 let open_paths_task_result = workspace
3422 .update_in(cx, |workspace, window, cx| {
3423 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
3424 })
3425 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
3426 .await;
3427 anyhow::ensure!(
3428 open_paths_task_result.len() == 1,
3429 "open abs path {abs_path:?} task returned incorrect number of results"
3430 );
3431 match open_paths_task_result
3432 .into_iter()
3433 .next()
3434 .expect("ensured single task result")
3435 {
3436 Some(open_result) => {
3437 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
3438 }
3439 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
3440 }
3441 })
3442 }
3443
3444 pub fn split_abs_path(
3445 &mut self,
3446 abs_path: PathBuf,
3447 visible: bool,
3448 window: &mut Window,
3449 cx: &mut Context<Self>,
3450 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3451 let project_path_task =
3452 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
3453 cx.spawn_in(window, async move |this, cx| {
3454 let (_, path) = project_path_task.await?;
3455 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
3456 .await
3457 })
3458 }
3459
3460 pub fn open_path(
3461 &mut self,
3462 path: impl Into<ProjectPath>,
3463 pane: Option<WeakEntity<Pane>>,
3464 focus_item: bool,
3465 window: &mut Window,
3466 cx: &mut App,
3467 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3468 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
3469 }
3470
3471 pub fn open_path_preview(
3472 &mut self,
3473 path: impl Into<ProjectPath>,
3474 pane: Option<WeakEntity<Pane>>,
3475 focus_item: bool,
3476 allow_preview: bool,
3477 activate: bool,
3478 window: &mut Window,
3479 cx: &mut App,
3480 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3481 let pane = pane.unwrap_or_else(|| {
3482 self.last_active_center_pane.clone().unwrap_or_else(|| {
3483 self.panes
3484 .first()
3485 .expect("There must be an active pane")
3486 .downgrade()
3487 })
3488 });
3489
3490 let project_path = path.into();
3491 let task = self.load_path(project_path.clone(), window, cx);
3492 window.spawn(cx, async move |cx| {
3493 let (project_entry_id, build_item) = task.await?;
3494
3495 pane.update_in(cx, |pane, window, cx| {
3496 pane.open_item(
3497 project_entry_id,
3498 project_path,
3499 focus_item,
3500 allow_preview,
3501 activate,
3502 None,
3503 window,
3504 cx,
3505 build_item,
3506 )
3507 })
3508 })
3509 }
3510
3511 pub fn split_path(
3512 &mut self,
3513 path: impl Into<ProjectPath>,
3514 window: &mut Window,
3515 cx: &mut Context<Self>,
3516 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3517 self.split_path_preview(path, false, None, window, cx)
3518 }
3519
3520 pub fn split_path_preview(
3521 &mut self,
3522 path: impl Into<ProjectPath>,
3523 allow_preview: bool,
3524 split_direction: Option<SplitDirection>,
3525 window: &mut Window,
3526 cx: &mut Context<Self>,
3527 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3528 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
3529 self.panes
3530 .first()
3531 .expect("There must be an active pane")
3532 .downgrade()
3533 });
3534
3535 if let Member::Pane(center_pane) = &self.center.root
3536 && center_pane.read(cx).items_len() == 0
3537 {
3538 return self.open_path(path, Some(pane), true, window, cx);
3539 }
3540
3541 let project_path = path.into();
3542 let task = self.load_path(project_path.clone(), window, cx);
3543 cx.spawn_in(window, async move |this, cx| {
3544 let (project_entry_id, build_item) = task.await?;
3545 this.update_in(cx, move |this, window, cx| -> Option<_> {
3546 let pane = pane.upgrade()?;
3547 let new_pane = this.split_pane(
3548 pane,
3549 split_direction.unwrap_or(SplitDirection::Right),
3550 window,
3551 cx,
3552 );
3553 new_pane.update(cx, |new_pane, cx| {
3554 Some(new_pane.open_item(
3555 project_entry_id,
3556 project_path,
3557 true,
3558 allow_preview,
3559 true,
3560 None,
3561 window,
3562 cx,
3563 build_item,
3564 ))
3565 })
3566 })
3567 .map(|option| option.context("pane was dropped"))?
3568 })
3569 }
3570
3571 fn load_path(
3572 &mut self,
3573 path: ProjectPath,
3574 window: &mut Window,
3575 cx: &mut App,
3576 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
3577 let registry = cx.default_global::<ProjectItemRegistry>().clone();
3578 registry.open_path(
3579 self.project(),
3580 &path,
3581 Some(EncodingWrapper::new(*self.encoding.lock().unwrap())),
3582 window,
3583 cx,
3584 )
3585 }
3586
3587 pub fn find_project_item<T>(
3588 &self,
3589 pane: &Entity<Pane>,
3590 project_item: &Entity<T::Item>,
3591 cx: &App,
3592 ) -> Option<Entity<T>>
3593 where
3594 T: ProjectItem,
3595 {
3596 use project::ProjectItem as _;
3597 let project_item = project_item.read(cx);
3598 let entry_id = project_item.entry_id(cx);
3599 let project_path = project_item.project_path(cx);
3600
3601 let mut item = None;
3602 if let Some(entry_id) = entry_id {
3603 item = pane.read(cx).item_for_entry(entry_id, cx);
3604 }
3605 if item.is_none()
3606 && let Some(project_path) = project_path
3607 {
3608 item = pane.read(cx).item_for_path(project_path, cx);
3609 }
3610
3611 item.and_then(|item| item.downcast::<T>())
3612 }
3613
3614 pub fn is_project_item_open<T>(
3615 &self,
3616 pane: &Entity<Pane>,
3617 project_item: &Entity<T::Item>,
3618 cx: &App,
3619 ) -> bool
3620 where
3621 T: ProjectItem,
3622 {
3623 self.find_project_item::<T>(pane, project_item, cx)
3624 .is_some()
3625 }
3626
3627 pub fn open_project_item<T>(
3628 &mut self,
3629 pane: Entity<Pane>,
3630 project_item: Entity<T::Item>,
3631 activate_pane: bool,
3632 focus_item: bool,
3633 window: &mut Window,
3634 cx: &mut Context<Self>,
3635 ) -> Entity<T>
3636 where
3637 T: ProjectItem,
3638 {
3639 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
3640 self.activate_item(&item, activate_pane, focus_item, window, cx);
3641 return item;
3642 }
3643
3644 let item = pane.update(cx, |pane, cx| {
3645 cx.new(|cx| {
3646 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
3647 })
3648 });
3649 let item_id = item.item_id();
3650 let mut destination_index = None;
3651 pane.update(cx, |pane, cx| {
3652 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation
3653 && let Some(preview_item_id) = pane.preview_item_id()
3654 && preview_item_id != item_id
3655 {
3656 destination_index = pane.close_current_preview_item(window, cx);
3657 }
3658 pane.set_preview_item_id(Some(item.item_id()), cx)
3659 });
3660
3661 self.add_item(
3662 pane,
3663 Box::new(item.clone()),
3664 destination_index,
3665 activate_pane,
3666 focus_item,
3667 window,
3668 cx,
3669 );
3670 item
3671 }
3672
3673 pub fn open_shared_screen(
3674 &mut self,
3675 peer_id: PeerId,
3676 window: &mut Window,
3677 cx: &mut Context<Self>,
3678 ) {
3679 if let Some(shared_screen) =
3680 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
3681 {
3682 self.active_pane.update(cx, |pane, cx| {
3683 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
3684 });
3685 }
3686 }
3687
3688 pub fn activate_item(
3689 &mut self,
3690 item: &dyn ItemHandle,
3691 activate_pane: bool,
3692 focus_item: bool,
3693 window: &mut Window,
3694 cx: &mut App,
3695 ) -> bool {
3696 let result = self.panes.iter().find_map(|pane| {
3697 pane.read(cx)
3698 .index_for_item(item)
3699 .map(|ix| (pane.clone(), ix))
3700 });
3701 if let Some((pane, ix)) = result {
3702 pane.update(cx, |pane, cx| {
3703 pane.activate_item(ix, activate_pane, focus_item, window, cx)
3704 });
3705 true
3706 } else {
3707 false
3708 }
3709 }
3710
3711 fn activate_pane_at_index(
3712 &mut self,
3713 action: &ActivatePane,
3714 window: &mut Window,
3715 cx: &mut Context<Self>,
3716 ) {
3717 let panes = self.center.panes();
3718 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
3719 window.focus(&pane.focus_handle(cx));
3720 } else {
3721 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
3722 .detach();
3723 }
3724 }
3725
3726 fn move_item_to_pane_at_index(
3727 &mut self,
3728 action: &MoveItemToPane,
3729 window: &mut Window,
3730 cx: &mut Context<Self>,
3731 ) {
3732 let panes = self.center.panes();
3733 let destination = match panes.get(action.destination) {
3734 Some(&destination) => destination.clone(),
3735 None => {
3736 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
3737 return;
3738 }
3739 let direction = SplitDirection::Right;
3740 let split_off_pane = self
3741 .find_pane_in_direction(direction, cx)
3742 .unwrap_or_else(|| self.active_pane.clone());
3743 let new_pane = self.add_pane(window, cx);
3744 if self
3745 .center
3746 .split(&split_off_pane, &new_pane, direction)
3747 .log_err()
3748 .is_none()
3749 {
3750 return;
3751 };
3752 new_pane
3753 }
3754 };
3755
3756 if action.clone {
3757 if self
3758 .active_pane
3759 .read(cx)
3760 .active_item()
3761 .is_some_and(|item| item.can_split(cx))
3762 {
3763 clone_active_item(
3764 self.database_id(),
3765 &self.active_pane,
3766 &destination,
3767 action.focus,
3768 window,
3769 cx,
3770 );
3771 return;
3772 }
3773 }
3774 move_active_item(
3775 &self.active_pane,
3776 &destination,
3777 action.focus,
3778 true,
3779 window,
3780 cx,
3781 )
3782 }
3783
3784 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
3785 let panes = self.center.panes();
3786 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
3787 let next_ix = (ix + 1) % panes.len();
3788 let next_pane = panes[next_ix].clone();
3789 window.focus(&next_pane.focus_handle(cx));
3790 }
3791 }
3792
3793 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
3794 let panes = self.center.panes();
3795 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
3796 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
3797 let prev_pane = panes[prev_ix].clone();
3798 window.focus(&prev_pane.focus_handle(cx));
3799 }
3800 }
3801
3802 pub fn activate_pane_in_direction(
3803 &mut self,
3804 direction: SplitDirection,
3805 window: &mut Window,
3806 cx: &mut App,
3807 ) {
3808 use ActivateInDirectionTarget as Target;
3809 enum Origin {
3810 LeftDock,
3811 RightDock,
3812 BottomDock,
3813 Center,
3814 }
3815
3816 let origin: Origin = [
3817 (&self.left_dock, Origin::LeftDock),
3818 (&self.right_dock, Origin::RightDock),
3819 (&self.bottom_dock, Origin::BottomDock),
3820 ]
3821 .into_iter()
3822 .find_map(|(dock, origin)| {
3823 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
3824 Some(origin)
3825 } else {
3826 None
3827 }
3828 })
3829 .unwrap_or(Origin::Center);
3830
3831 let get_last_active_pane = || {
3832 let pane = self
3833 .last_active_center_pane
3834 .clone()
3835 .unwrap_or_else(|| {
3836 self.panes
3837 .first()
3838 .expect("There must be an active pane")
3839 .downgrade()
3840 })
3841 .upgrade()?;
3842 (pane.read(cx).items_len() != 0).then_some(pane)
3843 };
3844
3845 let try_dock =
3846 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
3847
3848 let target = match (origin, direction) {
3849 // We're in the center, so we first try to go to a different pane,
3850 // otherwise try to go to a dock.
3851 (Origin::Center, direction) => {
3852 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
3853 Some(Target::Pane(pane))
3854 } else {
3855 match direction {
3856 SplitDirection::Up => None,
3857 SplitDirection::Down => try_dock(&self.bottom_dock),
3858 SplitDirection::Left => try_dock(&self.left_dock),
3859 SplitDirection::Right => try_dock(&self.right_dock),
3860 }
3861 }
3862 }
3863
3864 (Origin::LeftDock, SplitDirection::Right) => {
3865 if let Some(last_active_pane) = get_last_active_pane() {
3866 Some(Target::Pane(last_active_pane))
3867 } else {
3868 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
3869 }
3870 }
3871
3872 (Origin::LeftDock, SplitDirection::Down)
3873 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
3874
3875 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
3876 (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
3877 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
3878
3879 (Origin::RightDock, SplitDirection::Left) => {
3880 if let Some(last_active_pane) = get_last_active_pane() {
3881 Some(Target::Pane(last_active_pane))
3882 } else {
3883 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
3884 }
3885 }
3886
3887 _ => None,
3888 };
3889
3890 match target {
3891 Some(ActivateInDirectionTarget::Pane(pane)) => {
3892 let pane = pane.read(cx);
3893 if let Some(item) = pane.active_item() {
3894 item.item_focus_handle(cx).focus(window);
3895 } else {
3896 log::error!(
3897 "Could not find a focus target when in switching focus in {direction} direction for a pane",
3898 );
3899 }
3900 }
3901 Some(ActivateInDirectionTarget::Dock(dock)) => {
3902 // Defer this to avoid a panic when the dock's active panel is already on the stack.
3903 window.defer(cx, move |window, cx| {
3904 let dock = dock.read(cx);
3905 if let Some(panel) = dock.active_panel() {
3906 panel.panel_focus_handle(cx).focus(window);
3907 } else {
3908 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
3909 }
3910 })
3911 }
3912 None => {}
3913 }
3914 }
3915
3916 pub fn move_item_to_pane_in_direction(
3917 &mut self,
3918 action: &MoveItemToPaneInDirection,
3919 window: &mut Window,
3920 cx: &mut Context<Self>,
3921 ) {
3922 let destination = match self.find_pane_in_direction(action.direction, cx) {
3923 Some(destination) => destination,
3924 None => {
3925 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
3926 return;
3927 }
3928 let new_pane = self.add_pane(window, cx);
3929 if self
3930 .center
3931 .split(&self.active_pane, &new_pane, action.direction)
3932 .log_err()
3933 .is_none()
3934 {
3935 return;
3936 };
3937 new_pane
3938 }
3939 };
3940
3941 if action.clone {
3942 if self
3943 .active_pane
3944 .read(cx)
3945 .active_item()
3946 .is_some_and(|item| item.can_split(cx))
3947 {
3948 clone_active_item(
3949 self.database_id(),
3950 &self.active_pane,
3951 &destination,
3952 action.focus,
3953 window,
3954 cx,
3955 );
3956 return;
3957 }
3958 }
3959 move_active_item(
3960 &self.active_pane,
3961 &destination,
3962 action.focus,
3963 true,
3964 window,
3965 cx,
3966 );
3967 }
3968
3969 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
3970 self.center.bounding_box_for_pane(pane)
3971 }
3972
3973 pub fn find_pane_in_direction(
3974 &mut self,
3975 direction: SplitDirection,
3976 cx: &App,
3977 ) -> Option<Entity<Pane>> {
3978 self.center
3979 .find_pane_in_direction(&self.active_pane, direction, cx)
3980 .cloned()
3981 }
3982
3983 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
3984 if let Some(to) = self.find_pane_in_direction(direction, cx) {
3985 self.center.swap(&self.active_pane, &to);
3986 cx.notify();
3987 }
3988 }
3989
3990 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
3991 if self
3992 .center
3993 .move_to_border(&self.active_pane, direction)
3994 .unwrap()
3995 {
3996 cx.notify();
3997 }
3998 }
3999
4000 pub fn resize_pane(
4001 &mut self,
4002 axis: gpui::Axis,
4003 amount: Pixels,
4004 window: &mut Window,
4005 cx: &mut Context<Self>,
4006 ) {
4007 let docks = self.all_docks();
4008 let active_dock = docks
4009 .into_iter()
4010 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
4011
4012 if let Some(dock) = active_dock {
4013 let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
4014 return;
4015 };
4016 match dock.read(cx).position() {
4017 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
4018 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
4019 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
4020 }
4021 } else {
4022 self.center
4023 .resize(&self.active_pane, axis, amount, &self.bounds);
4024 }
4025 cx.notify();
4026 }
4027
4028 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
4029 self.center.reset_pane_sizes();
4030 cx.notify();
4031 }
4032
4033 fn handle_pane_focused(
4034 &mut self,
4035 pane: Entity<Pane>,
4036 window: &mut Window,
4037 cx: &mut Context<Self>,
4038 ) {
4039 // This is explicitly hoisted out of the following check for pane identity as
4040 // terminal panel panes are not registered as a center panes.
4041 self.status_bar.update(cx, |status_bar, cx| {
4042 status_bar.set_active_pane(&pane, window, cx);
4043 });
4044 if self.active_pane != pane {
4045 self.set_active_pane(&pane, window, cx);
4046 }
4047
4048 if self.last_active_center_pane.is_none() {
4049 self.last_active_center_pane = Some(pane.downgrade());
4050 }
4051
4052 self.dismiss_zoomed_items_to_reveal(None, window, cx);
4053 if pane.read(cx).is_zoomed() {
4054 self.zoomed = Some(pane.downgrade().into());
4055 } else {
4056 self.zoomed = None;
4057 }
4058 self.zoomed_position = None;
4059 cx.emit(Event::ZoomChanged);
4060 self.update_active_view_for_followers(window, cx);
4061 pane.update(cx, |pane, _| {
4062 pane.track_alternate_file_items();
4063 });
4064
4065 cx.notify();
4066 }
4067
4068 fn set_active_pane(
4069 &mut self,
4070 pane: &Entity<Pane>,
4071 window: &mut Window,
4072 cx: &mut Context<Self>,
4073 ) {
4074 self.active_pane = pane.clone();
4075 self.active_item_path_changed(window, cx);
4076 self.last_active_center_pane = Some(pane.downgrade());
4077 }
4078
4079 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4080 self.update_active_view_for_followers(window, cx);
4081 }
4082
4083 fn handle_pane_event(
4084 &mut self,
4085 pane: &Entity<Pane>,
4086 event: &pane::Event,
4087 window: &mut Window,
4088 cx: &mut Context<Self>,
4089 ) {
4090 let mut serialize_workspace = true;
4091 match event {
4092 pane::Event::AddItem { item } => {
4093 item.added_to_pane(self, pane.clone(), window, cx);
4094 cx.emit(Event::ItemAdded {
4095 item: item.boxed_clone(),
4096 });
4097 }
4098 pane::Event::Split {
4099 direction,
4100 clone_active_item,
4101 } => {
4102 if *clone_active_item {
4103 self.split_and_clone(pane.clone(), *direction, window, cx)
4104 .detach();
4105 } else {
4106 self.split_and_move(pane.clone(), *direction, window, cx);
4107 }
4108 }
4109 pane::Event::JoinIntoNext => {
4110 self.join_pane_into_next(pane.clone(), window, cx);
4111 }
4112 pane::Event::JoinAll => {
4113 self.join_all_panes(window, cx);
4114 }
4115 pane::Event::Remove { focus_on_pane } => {
4116 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
4117 }
4118 pane::Event::ActivateItem {
4119 local,
4120 focus_changed,
4121 } => {
4122 window.invalidate_character_coordinates();
4123
4124 pane.update(cx, |pane, _| {
4125 pane.track_alternate_file_items();
4126 });
4127 if *local {
4128 self.unfollow_in_pane(pane, window, cx);
4129 }
4130 serialize_workspace = *focus_changed || pane != self.active_pane();
4131 if pane == self.active_pane() {
4132 self.active_item_path_changed(window, cx);
4133 self.update_active_view_for_followers(window, cx);
4134 } else if *local {
4135 self.set_active_pane(pane, window, cx);
4136 }
4137 }
4138 pane::Event::UserSavedItem { item, save_intent } => {
4139 cx.emit(Event::UserSavedItem {
4140 pane: pane.downgrade(),
4141 item: item.boxed_clone(),
4142 save_intent: *save_intent,
4143 });
4144 serialize_workspace = false;
4145 }
4146 pane::Event::ChangeItemTitle => {
4147 if *pane == self.active_pane {
4148 self.active_item_path_changed(window, cx);
4149 }
4150 serialize_workspace = false;
4151 }
4152 pane::Event::RemovedItem { item } => {
4153 cx.emit(Event::ActiveItemChanged);
4154 self.update_window_edited(window, cx);
4155 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
4156 && entry.get().entity_id() == pane.entity_id()
4157 {
4158 entry.remove();
4159 }
4160 cx.emit(Event::ItemRemoved {
4161 item_id: item.item_id(),
4162 });
4163 }
4164 pane::Event::Focus => {
4165 window.invalidate_character_coordinates();
4166 self.handle_pane_focused(pane.clone(), window, cx);
4167 }
4168 pane::Event::ZoomIn => {
4169 if *pane == self.active_pane {
4170 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
4171 if pane.read(cx).has_focus(window, cx) {
4172 self.zoomed = Some(pane.downgrade().into());
4173 self.zoomed_position = None;
4174 cx.emit(Event::ZoomChanged);
4175 }
4176 cx.notify();
4177 }
4178 }
4179 pane::Event::ZoomOut => {
4180 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4181 if self.zoomed_position.is_none() {
4182 self.zoomed = None;
4183 cx.emit(Event::ZoomChanged);
4184 }
4185 cx.notify();
4186 }
4187 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
4188 }
4189
4190 if serialize_workspace {
4191 self.serialize_workspace(window, cx);
4192 }
4193 }
4194
4195 pub fn unfollow_in_pane(
4196 &mut self,
4197 pane: &Entity<Pane>,
4198 window: &mut Window,
4199 cx: &mut Context<Workspace>,
4200 ) -> Option<CollaboratorId> {
4201 let leader_id = self.leader_for_pane(pane)?;
4202 self.unfollow(leader_id, window, cx);
4203 Some(leader_id)
4204 }
4205
4206 pub fn split_pane(
4207 &mut self,
4208 pane_to_split: Entity<Pane>,
4209 split_direction: SplitDirection,
4210 window: &mut Window,
4211 cx: &mut Context<Self>,
4212 ) -> Entity<Pane> {
4213 let new_pane = self.add_pane(window, cx);
4214 self.center
4215 .split(&pane_to_split, &new_pane, split_direction)
4216 .unwrap();
4217 cx.notify();
4218 new_pane
4219 }
4220
4221 pub fn split_and_move(
4222 &mut self,
4223 pane: Entity<Pane>,
4224 direction: SplitDirection,
4225 window: &mut Window,
4226 cx: &mut Context<Self>,
4227 ) {
4228 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
4229 return;
4230 };
4231 let new_pane = self.add_pane(window, cx);
4232 new_pane.update(cx, |pane, cx| {
4233 pane.add_item(item, true, true, None, window, cx)
4234 });
4235 self.center.split(&pane, &new_pane, direction).unwrap();
4236 cx.notify();
4237 }
4238
4239 pub fn split_and_clone(
4240 &mut self,
4241 pane: Entity<Pane>,
4242 direction: SplitDirection,
4243 window: &mut Window,
4244 cx: &mut Context<Self>,
4245 ) -> Task<Option<Entity<Pane>>> {
4246 let Some(item) = pane.read(cx).active_item() else {
4247 return Task::ready(None);
4248 };
4249 if !item.can_split(cx) {
4250 return Task::ready(None);
4251 }
4252 let task = item.clone_on_split(self.database_id(), window, cx);
4253 cx.spawn_in(window, async move |this, cx| {
4254 if let Some(clone) = task.await {
4255 this.update_in(cx, |this, window, cx| {
4256 let new_pane = this.add_pane(window, cx);
4257 new_pane.update(cx, |pane, cx| {
4258 pane.add_item(clone, true, true, None, window, cx)
4259 });
4260 this.center.split(&pane, &new_pane, direction).unwrap();
4261 cx.notify();
4262 new_pane
4263 })
4264 .ok()
4265 } else {
4266 None
4267 }
4268 })
4269 }
4270
4271 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4272 let active_item = self.active_pane.read(cx).active_item();
4273 for pane in &self.panes {
4274 join_pane_into_active(&self.active_pane, pane, window, cx);
4275 }
4276 if let Some(active_item) = active_item {
4277 self.activate_item(active_item.as_ref(), true, true, window, cx);
4278 }
4279 cx.notify();
4280 }
4281
4282 pub fn join_pane_into_next(
4283 &mut self,
4284 pane: Entity<Pane>,
4285 window: &mut Window,
4286 cx: &mut Context<Self>,
4287 ) {
4288 let next_pane = self
4289 .find_pane_in_direction(SplitDirection::Right, cx)
4290 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
4291 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
4292 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
4293 let Some(next_pane) = next_pane else {
4294 return;
4295 };
4296 move_all_items(&pane, &next_pane, window, cx);
4297 cx.notify();
4298 }
4299
4300 fn remove_pane(
4301 &mut self,
4302 pane: Entity<Pane>,
4303 focus_on: Option<Entity<Pane>>,
4304 window: &mut Window,
4305 cx: &mut Context<Self>,
4306 ) {
4307 if self.center.remove(&pane).unwrap() {
4308 self.force_remove_pane(&pane, &focus_on, window, cx);
4309 self.unfollow_in_pane(&pane, window, cx);
4310 self.last_leaders_by_pane.remove(&pane.downgrade());
4311 for removed_item in pane.read(cx).items() {
4312 self.panes_by_item.remove(&removed_item.item_id());
4313 }
4314
4315 cx.notify();
4316 } else {
4317 self.active_item_path_changed(window, cx);
4318 }
4319 cx.emit(Event::PaneRemoved);
4320 }
4321
4322 pub fn panes(&self) -> &[Entity<Pane>] {
4323 &self.panes
4324 }
4325
4326 pub fn active_pane(&self) -> &Entity<Pane> {
4327 &self.active_pane
4328 }
4329
4330 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
4331 for dock in self.all_docks() {
4332 if dock.focus_handle(cx).contains_focused(window, cx)
4333 && let Some(pane) = dock
4334 .read(cx)
4335 .active_panel()
4336 .and_then(|panel| panel.pane(cx))
4337 {
4338 return pane;
4339 }
4340 }
4341 self.active_pane().clone()
4342 }
4343
4344 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
4345 self.find_pane_in_direction(SplitDirection::Right, cx)
4346 .unwrap_or_else(|| {
4347 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
4348 })
4349 }
4350
4351 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
4352 let weak_pane = self.panes_by_item.get(&handle.item_id())?;
4353 weak_pane.upgrade()
4354 }
4355
4356 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
4357 self.follower_states.retain(|leader_id, state| {
4358 if *leader_id == CollaboratorId::PeerId(peer_id) {
4359 for item in state.items_by_leader_view_id.values() {
4360 item.view.set_leader_id(None, window, cx);
4361 }
4362 false
4363 } else {
4364 true
4365 }
4366 });
4367 cx.notify();
4368 }
4369
4370 pub fn start_following(
4371 &mut self,
4372 leader_id: impl Into<CollaboratorId>,
4373 window: &mut Window,
4374 cx: &mut Context<Self>,
4375 ) -> Option<Task<Result<()>>> {
4376 let leader_id = leader_id.into();
4377 let pane = self.active_pane().clone();
4378
4379 self.last_leaders_by_pane
4380 .insert(pane.downgrade(), leader_id);
4381 self.unfollow(leader_id, window, cx);
4382 self.unfollow_in_pane(&pane, window, cx);
4383 self.follower_states.insert(
4384 leader_id,
4385 FollowerState {
4386 center_pane: pane.clone(),
4387 dock_pane: None,
4388 active_view_id: None,
4389 items_by_leader_view_id: Default::default(),
4390 },
4391 );
4392 cx.notify();
4393
4394 match leader_id {
4395 CollaboratorId::PeerId(leader_peer_id) => {
4396 let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
4397 let project_id = self.project.read(cx).remote_id();
4398 let request = self.app_state.client.request(proto::Follow {
4399 room_id,
4400 project_id,
4401 leader_id: Some(leader_peer_id),
4402 });
4403
4404 Some(cx.spawn_in(window, async move |this, cx| {
4405 let response = request.await?;
4406 this.update(cx, |this, _| {
4407 let state = this
4408 .follower_states
4409 .get_mut(&leader_id)
4410 .context("following interrupted")?;
4411 state.active_view_id = response
4412 .active_view
4413 .as_ref()
4414 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
4415 anyhow::Ok(())
4416 })??;
4417 if let Some(view) = response.active_view {
4418 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
4419 }
4420 this.update_in(cx, |this, window, cx| {
4421 this.leader_updated(leader_id, window, cx)
4422 })?;
4423 Ok(())
4424 }))
4425 }
4426 CollaboratorId::Agent => {
4427 self.leader_updated(leader_id, window, cx)?;
4428 Some(Task::ready(Ok(())))
4429 }
4430 }
4431 }
4432
4433 pub fn follow_next_collaborator(
4434 &mut self,
4435 _: &FollowNextCollaborator,
4436 window: &mut Window,
4437 cx: &mut Context<Self>,
4438 ) {
4439 let collaborators = self.project.read(cx).collaborators();
4440 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
4441 let mut collaborators = collaborators.keys().copied();
4442 for peer_id in collaborators.by_ref() {
4443 if CollaboratorId::PeerId(peer_id) == leader_id {
4444 break;
4445 }
4446 }
4447 collaborators.next().map(CollaboratorId::PeerId)
4448 } else if let Some(last_leader_id) =
4449 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
4450 {
4451 match last_leader_id {
4452 CollaboratorId::PeerId(peer_id) => {
4453 if collaborators.contains_key(peer_id) {
4454 Some(*last_leader_id)
4455 } else {
4456 None
4457 }
4458 }
4459 CollaboratorId::Agent => Some(CollaboratorId::Agent),
4460 }
4461 } else {
4462 None
4463 };
4464
4465 let pane = self.active_pane.clone();
4466 let Some(leader_id) = next_leader_id.or_else(|| {
4467 Some(CollaboratorId::PeerId(
4468 collaborators.keys().copied().next()?,
4469 ))
4470 }) else {
4471 return;
4472 };
4473 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
4474 return;
4475 }
4476 if let Some(task) = self.start_following(leader_id, window, cx) {
4477 task.detach_and_log_err(cx)
4478 }
4479 }
4480
4481 pub fn follow(
4482 &mut self,
4483 leader_id: impl Into<CollaboratorId>,
4484 window: &mut Window,
4485 cx: &mut Context<Self>,
4486 ) {
4487 let leader_id = leader_id.into();
4488
4489 if let CollaboratorId::PeerId(peer_id) = leader_id {
4490 let Some(room) = ActiveCall::global(cx).read(cx).room() else {
4491 return;
4492 };
4493 let room = room.read(cx);
4494 let Some(remote_participant) = room.remote_participant_for_peer_id(peer_id) else {
4495 return;
4496 };
4497
4498 let project = self.project.read(cx);
4499
4500 let other_project_id = match remote_participant.location {
4501 call::ParticipantLocation::External => None,
4502 call::ParticipantLocation::UnsharedProject => None,
4503 call::ParticipantLocation::SharedProject { project_id } => {
4504 if Some(project_id) == project.remote_id() {
4505 None
4506 } else {
4507 Some(project_id)
4508 }
4509 }
4510 };
4511
4512 // if they are active in another project, follow there.
4513 if let Some(project_id) = other_project_id {
4514 let app_state = self.app_state.clone();
4515 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
4516 .detach_and_log_err(cx);
4517 }
4518 }
4519
4520 // if you're already following, find the right pane and focus it.
4521 if let Some(follower_state) = self.follower_states.get(&leader_id) {
4522 window.focus(&follower_state.pane().focus_handle(cx));
4523
4524 return;
4525 }
4526
4527 // Otherwise, follow.
4528 if let Some(task) = self.start_following(leader_id, window, cx) {
4529 task.detach_and_log_err(cx)
4530 }
4531 }
4532
4533 pub fn unfollow(
4534 &mut self,
4535 leader_id: impl Into<CollaboratorId>,
4536 window: &mut Window,
4537 cx: &mut Context<Self>,
4538 ) -> Option<()> {
4539 cx.notify();
4540
4541 let leader_id = leader_id.into();
4542 let state = self.follower_states.remove(&leader_id)?;
4543 for (_, item) in state.items_by_leader_view_id {
4544 item.view.set_leader_id(None, window, cx);
4545 }
4546
4547 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
4548 let project_id = self.project.read(cx).remote_id();
4549 let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
4550 self.app_state
4551 .client
4552 .send(proto::Unfollow {
4553 room_id,
4554 project_id,
4555 leader_id: Some(leader_peer_id),
4556 })
4557 .log_err();
4558 }
4559
4560 Some(())
4561 }
4562
4563 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
4564 self.follower_states.contains_key(&id.into())
4565 }
4566
4567 fn active_item_path_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4568 cx.emit(Event::ActiveItemChanged);
4569 let active_entry = self.active_project_path(cx);
4570 self.project.update(cx, |project, cx| {
4571 project.set_active_path(active_entry.clone(), cx)
4572 });
4573
4574 if let Some(project_path) = &active_entry {
4575 let git_store_entity = self.project.read(cx).git_store().clone();
4576 git_store_entity.update(cx, |git_store, cx| {
4577 git_store.set_active_repo_for_path(project_path, cx);
4578 });
4579 }
4580
4581 self.update_window_title(window, cx);
4582 }
4583
4584 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
4585 let project = self.project().read(cx);
4586 let mut title = String::new();
4587
4588 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
4589 let name = {
4590 let settings_location = SettingsLocation {
4591 worktree_id: worktree.read(cx).id(),
4592 path: RelPath::empty(),
4593 };
4594
4595 let settings = WorktreeSettings::get(Some(settings_location), cx);
4596 match &settings.project_name {
4597 Some(name) => name.as_str(),
4598 None => worktree.read(cx).root_name_str(),
4599 }
4600 };
4601 if i > 0 {
4602 title.push_str(", ");
4603 }
4604 title.push_str(name);
4605 }
4606
4607 if title.is_empty() {
4608 title = "empty project".to_string();
4609 }
4610
4611 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
4612 let filename = path.path.file_name().or_else(|| {
4613 Some(
4614 project
4615 .worktree_for_id(path.worktree_id, cx)?
4616 .read(cx)
4617 .root_name_str(),
4618 )
4619 });
4620
4621 if let Some(filename) = filename {
4622 title.push_str(" — ");
4623 title.push_str(filename.as_ref());
4624 }
4625 }
4626
4627 if project.is_via_collab() {
4628 title.push_str(" ↙");
4629 } else if project.is_shared() {
4630 title.push_str(" ↗");
4631 }
4632
4633 if let Some(last_title) = self.last_window_title.as_ref()
4634 && &title == last_title
4635 {
4636 return;
4637 }
4638 window.set_window_title(&title);
4639 SystemWindowTabController::update_tab_title(
4640 cx,
4641 window.window_handle().window_id(),
4642 SharedString::from(&title),
4643 );
4644 self.last_window_title = Some(title);
4645 }
4646
4647 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
4648 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
4649 if is_edited != self.window_edited {
4650 self.window_edited = is_edited;
4651 window.set_window_edited(self.window_edited)
4652 }
4653 }
4654
4655 fn update_item_dirty_state(
4656 &mut self,
4657 item: &dyn ItemHandle,
4658 window: &mut Window,
4659 cx: &mut App,
4660 ) {
4661 let is_dirty = item.is_dirty(cx);
4662 let item_id = item.item_id();
4663 let was_dirty = self.dirty_items.contains_key(&item_id);
4664 if is_dirty == was_dirty {
4665 return;
4666 }
4667 if was_dirty {
4668 self.dirty_items.remove(&item_id);
4669 self.update_window_edited(window, cx);
4670 return;
4671 }
4672 if let Some(window_handle) = window.window_handle().downcast::<Self>() {
4673 let s = item.on_release(
4674 cx,
4675 Box::new(move |cx| {
4676 window_handle
4677 .update(cx, |this, window, cx| {
4678 this.dirty_items.remove(&item_id);
4679 this.update_window_edited(window, cx)
4680 })
4681 .ok();
4682 }),
4683 );
4684 self.dirty_items.insert(item_id, s);
4685 self.update_window_edited(window, cx);
4686 }
4687 }
4688
4689 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
4690 if self.notifications.is_empty() {
4691 None
4692 } else {
4693 Some(
4694 div()
4695 .absolute()
4696 .right_3()
4697 .bottom_3()
4698 .w_112()
4699 .h_full()
4700 .flex()
4701 .flex_col()
4702 .justify_end()
4703 .gap_2()
4704 .children(
4705 self.notifications
4706 .iter()
4707 .map(|(_, notification)| notification.clone().into_any()),
4708 ),
4709 )
4710 }
4711 }
4712
4713 // RPC handlers
4714
4715 fn active_view_for_follower(
4716 &self,
4717 follower_project_id: Option<u64>,
4718 window: &mut Window,
4719 cx: &mut Context<Self>,
4720 ) -> Option<proto::View> {
4721 let (item, panel_id) = self.active_item_for_followers(window, cx);
4722 let item = item?;
4723 let leader_id = self
4724 .pane_for(&*item)
4725 .and_then(|pane| self.leader_for_pane(&pane));
4726 let leader_peer_id = match leader_id {
4727 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
4728 Some(CollaboratorId::Agent) | None => None,
4729 };
4730
4731 let item_handle = item.to_followable_item_handle(cx)?;
4732 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
4733 let variant = item_handle.to_state_proto(window, cx)?;
4734
4735 if item_handle.is_project_item(window, cx)
4736 && (follower_project_id.is_none()
4737 || follower_project_id != self.project.read(cx).remote_id())
4738 {
4739 return None;
4740 }
4741
4742 Some(proto::View {
4743 id: id.to_proto(),
4744 leader_id: leader_peer_id,
4745 variant: Some(variant),
4746 panel_id: panel_id.map(|id| id as i32),
4747 })
4748 }
4749
4750 fn handle_follow(
4751 &mut self,
4752 follower_project_id: Option<u64>,
4753 window: &mut Window,
4754 cx: &mut Context<Self>,
4755 ) -> proto::FollowResponse {
4756 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
4757
4758 cx.notify();
4759 proto::FollowResponse {
4760 // TODO: Remove after version 0.145.x stabilizes.
4761 active_view_id: active_view.as_ref().and_then(|view| view.id.clone()),
4762 views: active_view.iter().cloned().collect(),
4763 active_view,
4764 }
4765 }
4766
4767 fn handle_update_followers(
4768 &mut self,
4769 leader_id: PeerId,
4770 message: proto::UpdateFollowers,
4771 _window: &mut Window,
4772 _cx: &mut Context<Self>,
4773 ) {
4774 self.leader_updates_tx
4775 .unbounded_send((leader_id, message))
4776 .ok();
4777 }
4778
4779 async fn process_leader_update(
4780 this: &WeakEntity<Self>,
4781 leader_id: PeerId,
4782 update: proto::UpdateFollowers,
4783 cx: &mut AsyncWindowContext,
4784 ) -> Result<()> {
4785 match update.variant.context("invalid update")? {
4786 proto::update_followers::Variant::CreateView(view) => {
4787 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
4788 let should_add_view = this.update(cx, |this, _| {
4789 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
4790 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
4791 } else {
4792 anyhow::Ok(false)
4793 }
4794 })??;
4795
4796 if should_add_view {
4797 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
4798 }
4799 }
4800 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
4801 let should_add_view = this.update(cx, |this, _| {
4802 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
4803 state.active_view_id = update_active_view
4804 .view
4805 .as_ref()
4806 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
4807
4808 if state.active_view_id.is_some_and(|view_id| {
4809 !state.items_by_leader_view_id.contains_key(&view_id)
4810 }) {
4811 anyhow::Ok(true)
4812 } else {
4813 anyhow::Ok(false)
4814 }
4815 } else {
4816 anyhow::Ok(false)
4817 }
4818 })??;
4819
4820 if should_add_view && let Some(view) = update_active_view.view {
4821 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
4822 }
4823 }
4824 proto::update_followers::Variant::UpdateView(update_view) => {
4825 let variant = update_view.variant.context("missing update view variant")?;
4826 let id = update_view.id.context("missing update view id")?;
4827 let mut tasks = Vec::new();
4828 this.update_in(cx, |this, window, cx| {
4829 let project = this.project.clone();
4830 if let Some(state) = this.follower_states.get(&leader_id.into()) {
4831 let view_id = ViewId::from_proto(id.clone())?;
4832 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
4833 tasks.push(item.view.apply_update_proto(
4834 &project,
4835 variant.clone(),
4836 window,
4837 cx,
4838 ));
4839 }
4840 }
4841 anyhow::Ok(())
4842 })??;
4843 try_join_all(tasks).await.log_err();
4844 }
4845 }
4846 this.update_in(cx, |this, window, cx| {
4847 this.leader_updated(leader_id, window, cx)
4848 })?;
4849 Ok(())
4850 }
4851
4852 async fn add_view_from_leader(
4853 this: WeakEntity<Self>,
4854 leader_id: PeerId,
4855 view: &proto::View,
4856 cx: &mut AsyncWindowContext,
4857 ) -> Result<()> {
4858 let this = this.upgrade().context("workspace dropped")?;
4859
4860 let Some(id) = view.id.clone() else {
4861 anyhow::bail!("no id for view");
4862 };
4863 let id = ViewId::from_proto(id)?;
4864 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
4865
4866 let pane = this.update(cx, |this, _cx| {
4867 let state = this
4868 .follower_states
4869 .get(&leader_id.into())
4870 .context("stopped following")?;
4871 anyhow::Ok(state.pane().clone())
4872 })??;
4873 let existing_item = pane.update_in(cx, |pane, window, cx| {
4874 let client = this.read(cx).client().clone();
4875 pane.items().find_map(|item| {
4876 let item = item.to_followable_item_handle(cx)?;
4877 if item.remote_id(&client, window, cx) == Some(id) {
4878 Some(item)
4879 } else {
4880 None
4881 }
4882 })
4883 })?;
4884 let item = if let Some(existing_item) = existing_item {
4885 existing_item
4886 } else {
4887 let variant = view.variant.clone();
4888 anyhow::ensure!(variant.is_some(), "missing view variant");
4889
4890 let task = cx.update(|window, cx| {
4891 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
4892 })?;
4893
4894 let Some(task) = task else {
4895 anyhow::bail!(
4896 "failed to construct view from leader (maybe from a different version of zed?)"
4897 );
4898 };
4899
4900 let mut new_item = task.await?;
4901 pane.update_in(cx, |pane, window, cx| {
4902 let mut item_to_remove = None;
4903 for (ix, item) in pane.items().enumerate() {
4904 if let Some(item) = item.to_followable_item_handle(cx) {
4905 match new_item.dedup(item.as_ref(), window, cx) {
4906 Some(item::Dedup::KeepExisting) => {
4907 new_item =
4908 item.boxed_clone().to_followable_item_handle(cx).unwrap();
4909 break;
4910 }
4911 Some(item::Dedup::ReplaceExisting) => {
4912 item_to_remove = Some((ix, item.item_id()));
4913 break;
4914 }
4915 None => {}
4916 }
4917 }
4918 }
4919
4920 if let Some((ix, id)) = item_to_remove {
4921 pane.remove_item(id, false, false, window, cx);
4922 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
4923 }
4924 })?;
4925
4926 new_item
4927 };
4928
4929 this.update_in(cx, |this, window, cx| {
4930 let state = this.follower_states.get_mut(&leader_id.into())?;
4931 item.set_leader_id(Some(leader_id.into()), window, cx);
4932 state.items_by_leader_view_id.insert(
4933 id,
4934 FollowerView {
4935 view: item,
4936 location: panel_id,
4937 },
4938 );
4939
4940 Some(())
4941 })?;
4942
4943 Ok(())
4944 }
4945
4946 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4947 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
4948 return;
4949 };
4950
4951 if let Some(agent_location) = self.project.read(cx).agent_location() {
4952 let buffer_entity_id = agent_location.buffer.entity_id();
4953 let view_id = ViewId {
4954 creator: CollaboratorId::Agent,
4955 id: buffer_entity_id.as_u64(),
4956 };
4957 follower_state.active_view_id = Some(view_id);
4958
4959 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
4960 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
4961 hash_map::Entry::Vacant(entry) => {
4962 let existing_view =
4963 follower_state
4964 .center_pane
4965 .read(cx)
4966 .items()
4967 .find_map(|item| {
4968 let item = item.to_followable_item_handle(cx)?;
4969 if item.buffer_kind(cx) == ItemBufferKind::Singleton
4970 && item.project_item_model_ids(cx).as_slice()
4971 == [buffer_entity_id]
4972 {
4973 Some(item)
4974 } else {
4975 None
4976 }
4977 });
4978 let view = existing_view.or_else(|| {
4979 agent_location.buffer.upgrade().and_then(|buffer| {
4980 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
4981 registry.build_item(buffer, self.project.clone(), None, window, cx)
4982 })?
4983 .to_followable_item_handle(cx)
4984 })
4985 });
4986
4987 view.map(|view| {
4988 entry.insert(FollowerView {
4989 view,
4990 location: None,
4991 })
4992 })
4993 }
4994 };
4995
4996 if let Some(item) = item {
4997 item.view
4998 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
4999 item.view
5000 .update_agent_location(agent_location.position, window, cx);
5001 }
5002 } else {
5003 follower_state.active_view_id = None;
5004 }
5005
5006 self.leader_updated(CollaboratorId::Agent, window, cx);
5007 }
5008
5009 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
5010 let mut is_project_item = true;
5011 let mut update = proto::UpdateActiveView::default();
5012 if window.is_window_active() {
5013 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
5014
5015 if let Some(item) = active_item
5016 && item.item_focus_handle(cx).contains_focused(window, cx)
5017 {
5018 let leader_id = self
5019 .pane_for(&*item)
5020 .and_then(|pane| self.leader_for_pane(&pane));
5021 let leader_peer_id = match leader_id {
5022 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5023 Some(CollaboratorId::Agent) | None => None,
5024 };
5025
5026 if let Some(item) = item.to_followable_item_handle(cx) {
5027 let id = item
5028 .remote_id(&self.app_state.client, window, cx)
5029 .map(|id| id.to_proto());
5030
5031 if let Some(id) = id
5032 && let Some(variant) = item.to_state_proto(window, cx)
5033 {
5034 let view = Some(proto::View {
5035 id: id.clone(),
5036 leader_id: leader_peer_id,
5037 variant: Some(variant),
5038 panel_id: panel_id.map(|id| id as i32),
5039 });
5040
5041 is_project_item = item.is_project_item(window, cx);
5042 update = proto::UpdateActiveView {
5043 view,
5044 // TODO: Remove after version 0.145.x stabilizes.
5045 id,
5046 leader_id: leader_peer_id,
5047 };
5048 };
5049 }
5050 }
5051 }
5052
5053 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
5054 if active_view_id != self.last_active_view_id.as_ref() {
5055 self.last_active_view_id = active_view_id.cloned();
5056 self.update_followers(
5057 is_project_item,
5058 proto::update_followers::Variant::UpdateActiveView(update),
5059 window,
5060 cx,
5061 );
5062 }
5063 }
5064
5065 fn active_item_for_followers(
5066 &self,
5067 window: &mut Window,
5068 cx: &mut App,
5069 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
5070 let mut active_item = None;
5071 let mut panel_id = None;
5072 for dock in self.all_docks() {
5073 if dock.focus_handle(cx).contains_focused(window, cx)
5074 && let Some(panel) = dock.read(cx).active_panel()
5075 && let Some(pane) = panel.pane(cx)
5076 && let Some(item) = pane.read(cx).active_item()
5077 {
5078 active_item = Some(item);
5079 panel_id = panel.remote_id();
5080 break;
5081 }
5082 }
5083
5084 if active_item.is_none() {
5085 active_item = self.active_pane().read(cx).active_item();
5086 }
5087 (active_item, panel_id)
5088 }
5089
5090 fn update_followers(
5091 &self,
5092 project_only: bool,
5093 update: proto::update_followers::Variant,
5094 _: &mut Window,
5095 cx: &mut App,
5096 ) -> Option<()> {
5097 // If this update only applies to for followers in the current project,
5098 // then skip it unless this project is shared. If it applies to all
5099 // followers, regardless of project, then set `project_id` to none,
5100 // indicating that it goes to all followers.
5101 let project_id = if project_only {
5102 Some(self.project.read(cx).remote_id()?)
5103 } else {
5104 None
5105 };
5106 self.app_state().workspace_store.update(cx, |store, cx| {
5107 store.update_followers(project_id, update, cx)
5108 })
5109 }
5110
5111 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
5112 self.follower_states.iter().find_map(|(leader_id, state)| {
5113 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
5114 Some(*leader_id)
5115 } else {
5116 None
5117 }
5118 })
5119 }
5120
5121 fn leader_updated(
5122 &mut self,
5123 leader_id: impl Into<CollaboratorId>,
5124 window: &mut Window,
5125 cx: &mut Context<Self>,
5126 ) -> Option<Box<dyn ItemHandle>> {
5127 cx.notify();
5128
5129 let leader_id = leader_id.into();
5130 let (panel_id, item) = match leader_id {
5131 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
5132 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
5133 };
5134
5135 let state = self.follower_states.get(&leader_id)?;
5136 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
5137 let pane;
5138 if let Some(panel_id) = panel_id {
5139 pane = self
5140 .activate_panel_for_proto_id(panel_id, window, cx)?
5141 .pane(cx)?;
5142 let state = self.follower_states.get_mut(&leader_id)?;
5143 state.dock_pane = Some(pane.clone());
5144 } else {
5145 pane = state.center_pane.clone();
5146 let state = self.follower_states.get_mut(&leader_id)?;
5147 if let Some(dock_pane) = state.dock_pane.take() {
5148 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
5149 }
5150 }
5151
5152 pane.update(cx, |pane, cx| {
5153 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
5154 if let Some(index) = pane.index_for_item(item.as_ref()) {
5155 pane.activate_item(index, false, false, window, cx);
5156 } else {
5157 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
5158 }
5159
5160 if focus_active_item {
5161 pane.focus_active_item(window, cx)
5162 }
5163 });
5164
5165 Some(item)
5166 }
5167
5168 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
5169 let state = self.follower_states.get(&CollaboratorId::Agent)?;
5170 let active_view_id = state.active_view_id?;
5171 Some(
5172 state
5173 .items_by_leader_view_id
5174 .get(&active_view_id)?
5175 .view
5176 .boxed_clone(),
5177 )
5178 }
5179
5180 fn active_item_for_peer(
5181 &self,
5182 peer_id: PeerId,
5183 window: &mut Window,
5184 cx: &mut Context<Self>,
5185 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
5186 let call = self.active_call()?;
5187 let room = call.read(cx).room()?.read(cx);
5188 let participant = room.remote_participant_for_peer_id(peer_id)?;
5189 let leader_in_this_app;
5190 let leader_in_this_project;
5191 match participant.location {
5192 call::ParticipantLocation::SharedProject { project_id } => {
5193 leader_in_this_app = true;
5194 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
5195 }
5196 call::ParticipantLocation::UnsharedProject => {
5197 leader_in_this_app = true;
5198 leader_in_this_project = false;
5199 }
5200 call::ParticipantLocation::External => {
5201 leader_in_this_app = false;
5202 leader_in_this_project = false;
5203 }
5204 };
5205 let state = self.follower_states.get(&peer_id.into())?;
5206 let mut item_to_activate = None;
5207 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
5208 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
5209 && (leader_in_this_project || !item.view.is_project_item(window, cx))
5210 {
5211 item_to_activate = Some((item.location, item.view.boxed_clone()));
5212 }
5213 } else if let Some(shared_screen) =
5214 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
5215 {
5216 item_to_activate = Some((None, Box::new(shared_screen)));
5217 }
5218 item_to_activate
5219 }
5220
5221 fn shared_screen_for_peer(
5222 &self,
5223 peer_id: PeerId,
5224 pane: &Entity<Pane>,
5225 window: &mut Window,
5226 cx: &mut App,
5227 ) -> Option<Entity<SharedScreen>> {
5228 let call = self.active_call()?;
5229 let room = call.read(cx).room()?.clone();
5230 let participant = room.read(cx).remote_participant_for_peer_id(peer_id)?;
5231 let track = participant.video_tracks.values().next()?.clone();
5232 let user = participant.user.clone();
5233
5234 for item in pane.read(cx).items_of_type::<SharedScreen>() {
5235 if item.read(cx).peer_id == peer_id {
5236 return Some(item);
5237 }
5238 }
5239
5240 Some(cx.new(|cx| SharedScreen::new(track, peer_id, user.clone(), room.clone(), window, cx)))
5241 }
5242
5243 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5244 if window.is_window_active() {
5245 self.update_active_view_for_followers(window, cx);
5246
5247 if let Some(database_id) = self.database_id {
5248 cx.background_spawn(persistence::DB.update_timestamp(database_id))
5249 .detach();
5250 }
5251 } else {
5252 for pane in &self.panes {
5253 pane.update(cx, |pane, cx| {
5254 if let Some(item) = pane.active_item() {
5255 item.workspace_deactivated(window, cx);
5256 }
5257 for item in pane.items() {
5258 if matches!(
5259 item.workspace_settings(cx).autosave,
5260 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
5261 ) {
5262 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
5263 .detach_and_log_err(cx);
5264 }
5265 }
5266 });
5267 }
5268 }
5269 }
5270
5271 pub fn active_call(&self) -> Option<&Entity<ActiveCall>> {
5272 self.active_call.as_ref().map(|(call, _)| call)
5273 }
5274
5275 fn on_active_call_event(
5276 &mut self,
5277 _: &Entity<ActiveCall>,
5278 event: &call::room::Event,
5279 window: &mut Window,
5280 cx: &mut Context<Self>,
5281 ) {
5282 match event {
5283 call::room::Event::ParticipantLocationChanged { participant_id }
5284 | call::room::Event::RemoteVideoTracksChanged { participant_id } => {
5285 self.leader_updated(participant_id, window, cx);
5286 }
5287 _ => {}
5288 }
5289 }
5290
5291 pub fn database_id(&self) -> Option<WorkspaceId> {
5292 self.database_id
5293 }
5294
5295 pub fn session_id(&self) -> Option<String> {
5296 self.session_id.clone()
5297 }
5298
5299 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
5300 let project = self.project().read(cx);
5301 project
5302 .visible_worktrees(cx)
5303 .map(|worktree| worktree.read(cx).abs_path())
5304 .collect::<Vec<_>>()
5305 }
5306
5307 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
5308 match member {
5309 Member::Axis(PaneAxis { members, .. }) => {
5310 for child in members.iter() {
5311 self.remove_panes(child.clone(), window, cx)
5312 }
5313 }
5314 Member::Pane(pane) => {
5315 self.force_remove_pane(&pane, &None, window, cx);
5316 }
5317 }
5318 }
5319
5320 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
5321 self.session_id.take();
5322 self.serialize_workspace_internal(window, cx)
5323 }
5324
5325 fn force_remove_pane(
5326 &mut self,
5327 pane: &Entity<Pane>,
5328 focus_on: &Option<Entity<Pane>>,
5329 window: &mut Window,
5330 cx: &mut Context<Workspace>,
5331 ) {
5332 self.panes.retain(|p| p != pane);
5333 if let Some(focus_on) = focus_on {
5334 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
5335 } else if self.active_pane() == pane {
5336 self.panes
5337 .last()
5338 .unwrap()
5339 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
5340 }
5341 if self.last_active_center_pane == Some(pane.downgrade()) {
5342 self.last_active_center_pane = None;
5343 }
5344 cx.notify();
5345 }
5346
5347 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5348 if self._schedule_serialize_workspace.is_none() {
5349 self._schedule_serialize_workspace =
5350 Some(cx.spawn_in(window, async move |this, cx| {
5351 cx.background_executor()
5352 .timer(SERIALIZATION_THROTTLE_TIME)
5353 .await;
5354 this.update_in(cx, |this, window, cx| {
5355 this.serialize_workspace_internal(window, cx).detach();
5356 this._schedule_serialize_workspace.take();
5357 })
5358 .log_err();
5359 }));
5360 }
5361 }
5362
5363 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
5364 let Some(database_id) = self.database_id() else {
5365 return Task::ready(());
5366 };
5367
5368 fn serialize_pane_handle(
5369 pane_handle: &Entity<Pane>,
5370 window: &mut Window,
5371 cx: &mut App,
5372 ) -> SerializedPane {
5373 let (items, active, pinned_count) = {
5374 let pane = pane_handle.read(cx);
5375 let active_item_id = pane.active_item().map(|item| item.item_id());
5376 (
5377 pane.items()
5378 .filter_map(|handle| {
5379 let handle = handle.to_serializable_item_handle(cx)?;
5380
5381 Some(SerializedItem {
5382 kind: Arc::from(handle.serialized_item_kind()),
5383 item_id: handle.item_id().as_u64(),
5384 active: Some(handle.item_id()) == active_item_id,
5385 preview: pane.is_active_preview_item(handle.item_id()),
5386 })
5387 })
5388 .collect::<Vec<_>>(),
5389 pane.has_focus(window, cx),
5390 pane.pinned_count(),
5391 )
5392 };
5393
5394 SerializedPane::new(items, active, pinned_count)
5395 }
5396
5397 fn build_serialized_pane_group(
5398 pane_group: &Member,
5399 window: &mut Window,
5400 cx: &mut App,
5401 ) -> SerializedPaneGroup {
5402 match pane_group {
5403 Member::Axis(PaneAxis {
5404 axis,
5405 members,
5406 flexes,
5407 bounding_boxes: _,
5408 }) => SerializedPaneGroup::Group {
5409 axis: SerializedAxis(*axis),
5410 children: members
5411 .iter()
5412 .map(|member| build_serialized_pane_group(member, window, cx))
5413 .collect::<Vec<_>>(),
5414 flexes: Some(flexes.lock().clone()),
5415 },
5416 Member::Pane(pane_handle) => {
5417 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
5418 }
5419 }
5420 }
5421
5422 fn build_serialized_docks(
5423 this: &Workspace,
5424 window: &mut Window,
5425 cx: &mut App,
5426 ) -> DockStructure {
5427 let left_dock = this.left_dock.read(cx);
5428 let left_visible = left_dock.is_open();
5429 let left_active_panel = left_dock
5430 .active_panel()
5431 .map(|panel| panel.persistent_name().to_string());
5432 let left_dock_zoom = left_dock
5433 .active_panel()
5434 .map(|panel| panel.is_zoomed(window, cx))
5435 .unwrap_or(false);
5436
5437 let right_dock = this.right_dock.read(cx);
5438 let right_visible = right_dock.is_open();
5439 let right_active_panel = right_dock
5440 .active_panel()
5441 .map(|panel| panel.persistent_name().to_string());
5442 let right_dock_zoom = right_dock
5443 .active_panel()
5444 .map(|panel| panel.is_zoomed(window, cx))
5445 .unwrap_or(false);
5446
5447 let bottom_dock = this.bottom_dock.read(cx);
5448 let bottom_visible = bottom_dock.is_open();
5449 let bottom_active_panel = bottom_dock
5450 .active_panel()
5451 .map(|panel| panel.persistent_name().to_string());
5452 let bottom_dock_zoom = bottom_dock
5453 .active_panel()
5454 .map(|panel| panel.is_zoomed(window, cx))
5455 .unwrap_or(false);
5456
5457 DockStructure {
5458 left: DockData {
5459 visible: left_visible,
5460 active_panel: left_active_panel,
5461 zoom: left_dock_zoom,
5462 },
5463 right: DockData {
5464 visible: right_visible,
5465 active_panel: right_active_panel,
5466 zoom: right_dock_zoom,
5467 },
5468 bottom: DockData {
5469 visible: bottom_visible,
5470 active_panel: bottom_active_panel,
5471 zoom: bottom_dock_zoom,
5472 },
5473 }
5474 }
5475
5476 match self.serialize_workspace_location(cx) {
5477 WorkspaceLocation::Location(location, paths) => {
5478 let breakpoints = self.project.update(cx, |project, cx| {
5479 project
5480 .breakpoint_store()
5481 .read(cx)
5482 .all_source_breakpoints(cx)
5483 });
5484 let user_toolchains = self
5485 .project
5486 .read(cx)
5487 .user_toolchains(cx)
5488 .unwrap_or_default();
5489
5490 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
5491 let docks = build_serialized_docks(self, window, cx);
5492 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
5493
5494 let serialized_workspace = SerializedWorkspace {
5495 id: database_id,
5496 location,
5497 paths,
5498 center_group,
5499 window_bounds,
5500 display: Default::default(),
5501 docks,
5502 centered_layout: self.centered_layout,
5503 session_id: self.session_id.clone(),
5504 breakpoints,
5505 window_id: Some(window.window_handle().window_id().as_u64()),
5506 user_toolchains,
5507 };
5508
5509 window.spawn(cx, async move |_| {
5510 persistence::DB.save_workspace(serialized_workspace).await;
5511 })
5512 }
5513 WorkspaceLocation::DetachFromSession => window.spawn(cx, async move |_| {
5514 persistence::DB
5515 .set_session_id(database_id, None)
5516 .await
5517 .log_err();
5518 }),
5519 WorkspaceLocation::None => Task::ready(()),
5520 }
5521 }
5522
5523 fn serialize_workspace_location(&self, cx: &App) -> WorkspaceLocation {
5524 let paths = PathList::new(&self.root_paths(cx));
5525 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
5526 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
5527 } else if self.project.read(cx).is_local() {
5528 if !paths.is_empty() {
5529 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
5530 } else {
5531 WorkspaceLocation::DetachFromSession
5532 }
5533 } else {
5534 WorkspaceLocation::None
5535 }
5536 }
5537
5538 fn update_history(&self, cx: &mut App) {
5539 let Some(id) = self.database_id() else {
5540 return;
5541 };
5542 if !self.project.read(cx).is_local() {
5543 return;
5544 }
5545 if let Some(manager) = HistoryManager::global(cx) {
5546 let paths = PathList::new(&self.root_paths(cx));
5547 manager.update(cx, |this, cx| {
5548 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
5549 });
5550 }
5551 }
5552
5553 async fn serialize_items(
5554 this: &WeakEntity<Self>,
5555 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
5556 cx: &mut AsyncWindowContext,
5557 ) -> Result<()> {
5558 const CHUNK_SIZE: usize = 200;
5559
5560 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
5561
5562 while let Some(items_received) = serializable_items.next().await {
5563 let unique_items =
5564 items_received
5565 .into_iter()
5566 .fold(HashMap::default(), |mut acc, item| {
5567 acc.entry(item.item_id()).or_insert(item);
5568 acc
5569 });
5570
5571 // We use into_iter() here so that the references to the items are moved into
5572 // the tasks and not kept alive while we're sleeping.
5573 for (_, item) in unique_items.into_iter() {
5574 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
5575 item.serialize(workspace, false, window, cx)
5576 }) {
5577 cx.background_spawn(async move { task.await.log_err() })
5578 .detach();
5579 }
5580 }
5581
5582 cx.background_executor()
5583 .timer(SERIALIZATION_THROTTLE_TIME)
5584 .await;
5585 }
5586
5587 Ok(())
5588 }
5589
5590 pub(crate) fn enqueue_item_serialization(
5591 &mut self,
5592 item: Box<dyn SerializableItemHandle>,
5593 ) -> Result<()> {
5594 self.serializable_items_tx
5595 .unbounded_send(item)
5596 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
5597 }
5598
5599 pub(crate) fn load_workspace(
5600 serialized_workspace: SerializedWorkspace,
5601 paths_to_open: Vec<Option<ProjectPath>>,
5602 window: &mut Window,
5603 cx: &mut Context<Workspace>,
5604 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
5605 cx.spawn_in(window, async move |workspace, cx| {
5606 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
5607
5608 let mut center_group = None;
5609 let mut center_items = None;
5610
5611 // Traverse the splits tree and add to things
5612 if let Some((group, active_pane, items)) = serialized_workspace
5613 .center_group
5614 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
5615 .await
5616 {
5617 center_items = Some(items);
5618 center_group = Some((group, active_pane))
5619 }
5620
5621 let mut items_by_project_path = HashMap::default();
5622 let mut item_ids_by_kind = HashMap::default();
5623 let mut all_deserialized_items = Vec::default();
5624 cx.update(|_, cx| {
5625 for item in center_items.unwrap_or_default().into_iter().flatten() {
5626 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
5627 item_ids_by_kind
5628 .entry(serializable_item_handle.serialized_item_kind())
5629 .or_insert(Vec::new())
5630 .push(item.item_id().as_u64() as ItemId);
5631 }
5632
5633 if let Some(project_path) = item.project_path(cx) {
5634 items_by_project_path.insert(project_path, item.clone());
5635 }
5636 all_deserialized_items.push(item);
5637 }
5638 })?;
5639
5640 let opened_items = paths_to_open
5641 .into_iter()
5642 .map(|path_to_open| {
5643 path_to_open
5644 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
5645 })
5646 .collect::<Vec<_>>();
5647
5648 // Remove old panes from workspace panes list
5649 workspace.update_in(cx, |workspace, window, cx| {
5650 if let Some((center_group, active_pane)) = center_group {
5651 workspace.remove_panes(workspace.center.root.clone(), window, cx);
5652
5653 // Swap workspace center group
5654 workspace.center = PaneGroup::with_root(center_group);
5655 if let Some(active_pane) = active_pane {
5656 workspace.set_active_pane(&active_pane, window, cx);
5657 cx.focus_self(window);
5658 } else {
5659 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
5660 }
5661 }
5662
5663 let docks = serialized_workspace.docks;
5664
5665 for (dock, serialized_dock) in [
5666 (&mut workspace.right_dock, docks.right),
5667 (&mut workspace.left_dock, docks.left),
5668 (&mut workspace.bottom_dock, docks.bottom),
5669 ]
5670 .iter_mut()
5671 {
5672 dock.update(cx, |dock, cx| {
5673 dock.serialized_dock = Some(serialized_dock.clone());
5674 dock.restore_state(window, cx);
5675 });
5676 }
5677
5678 cx.notify();
5679 })?;
5680
5681 let _ = project
5682 .update(cx, |project, cx| {
5683 project
5684 .breakpoint_store()
5685 .update(cx, |breakpoint_store, cx| {
5686 breakpoint_store
5687 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
5688 })
5689 })?
5690 .await;
5691
5692 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
5693 // after loading the items, we might have different items and in order to avoid
5694 // the database filling up, we delete items that haven't been loaded now.
5695 //
5696 // The items that have been loaded, have been saved after they've been added to the workspace.
5697 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
5698 item_ids_by_kind
5699 .into_iter()
5700 .map(|(item_kind, loaded_items)| {
5701 SerializableItemRegistry::cleanup(
5702 item_kind,
5703 serialized_workspace.id,
5704 loaded_items,
5705 window,
5706 cx,
5707 )
5708 .log_err()
5709 })
5710 .collect::<Vec<_>>()
5711 })?;
5712
5713 futures::future::join_all(clean_up_tasks).await;
5714
5715 workspace
5716 .update_in(cx, |workspace, window, cx| {
5717 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
5718 workspace.serialize_workspace_internal(window, cx).detach();
5719
5720 // Ensure that we mark the window as edited if we did load dirty items
5721 workspace.update_window_edited(window, cx);
5722 })
5723 .ok();
5724
5725 Ok(opened_items)
5726 })
5727 }
5728
5729 fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
5730 self.add_workspace_actions_listeners(div, window, cx)
5731 .on_action(cx.listener(
5732 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
5733 for action in &action_sequence.0 {
5734 window.dispatch_action(action.boxed_clone(), cx);
5735 }
5736 },
5737 ))
5738 .on_action(cx.listener(Self::close_inactive_items_and_panes))
5739 .on_action(cx.listener(Self::close_all_items_and_panes))
5740 .on_action(cx.listener(Self::save_all))
5741 .on_action(cx.listener(Self::send_keystrokes))
5742 .on_action(cx.listener(Self::add_folder_to_project))
5743 .on_action(cx.listener(Self::follow_next_collaborator))
5744 .on_action(cx.listener(Self::close_window))
5745 .on_action(cx.listener(Self::activate_pane_at_index))
5746 .on_action(cx.listener(Self::move_item_to_pane_at_index))
5747 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
5748 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
5749 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
5750 let pane = workspace.active_pane().clone();
5751 workspace.unfollow_in_pane(&pane, window, cx);
5752 }))
5753 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
5754 workspace
5755 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
5756 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
5757 }))
5758 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
5759 workspace
5760 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
5761 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
5762 }))
5763 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
5764 workspace
5765 .save_active_item(SaveIntent::SaveAs, window, cx)
5766 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
5767 }))
5768 .on_action(
5769 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
5770 workspace.activate_previous_pane(window, cx)
5771 }),
5772 )
5773 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
5774 workspace.activate_next_pane(window, cx)
5775 }))
5776 .on_action(
5777 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
5778 workspace.activate_next_window(cx)
5779 }),
5780 )
5781 .on_action(
5782 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
5783 workspace.activate_previous_window(cx)
5784 }),
5785 )
5786 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
5787 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
5788 }))
5789 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
5790 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
5791 }))
5792 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
5793 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
5794 }))
5795 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
5796 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
5797 }))
5798 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
5799 workspace.activate_next_pane(window, cx)
5800 }))
5801 .on_action(cx.listener(
5802 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
5803 workspace.move_item_to_pane_in_direction(action, window, cx)
5804 },
5805 ))
5806 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
5807 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
5808 }))
5809 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
5810 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
5811 }))
5812 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
5813 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
5814 }))
5815 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
5816 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
5817 }))
5818 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
5819 workspace.move_pane_to_border(SplitDirection::Left, cx)
5820 }))
5821 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
5822 workspace.move_pane_to_border(SplitDirection::Right, cx)
5823 }))
5824 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
5825 workspace.move_pane_to_border(SplitDirection::Up, cx)
5826 }))
5827 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
5828 workspace.move_pane_to_border(SplitDirection::Down, cx)
5829 }))
5830 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
5831 this.toggle_dock(DockPosition::Left, window, cx);
5832 }))
5833 .on_action(cx.listener(
5834 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
5835 workspace.toggle_dock(DockPosition::Right, window, cx);
5836 },
5837 ))
5838 .on_action(cx.listener(
5839 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
5840 workspace.toggle_dock(DockPosition::Bottom, window, cx);
5841 },
5842 ))
5843 .on_action(cx.listener(
5844 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
5845 if !workspace.close_active_dock(window, cx) {
5846 cx.propagate();
5847 }
5848 },
5849 ))
5850 .on_action(
5851 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
5852 workspace.close_all_docks(window, cx);
5853 }),
5854 )
5855 .on_action(cx.listener(Self::toggle_all_docks))
5856 .on_action(cx.listener(
5857 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
5858 workspace.clear_all_notifications(cx);
5859 },
5860 ))
5861 .on_action(cx.listener(
5862 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
5863 if let Some((notification_id, _)) = workspace.notifications.pop() {
5864 workspace.suppress_notification(¬ification_id, cx);
5865 }
5866 },
5867 ))
5868 .on_action(cx.listener(
5869 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
5870 workspace.reopen_closed_item(window, cx).detach();
5871 },
5872 ))
5873 .on_action(cx.listener(
5874 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
5875 for dock in workspace.all_docks() {
5876 if dock.focus_handle(cx).contains_focused(window, cx) {
5877 let Some(panel) = dock.read(cx).active_panel() else {
5878 return;
5879 };
5880
5881 // Set to `None`, then the size will fall back to the default.
5882 panel.clone().set_size(None, window, cx);
5883
5884 return;
5885 }
5886 }
5887 },
5888 ))
5889 .on_action(cx.listener(
5890 |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
5891 for dock in workspace.all_docks() {
5892 if let Some(panel) = dock.read(cx).visible_panel() {
5893 // Set to `None`, then the size will fall back to the default.
5894 panel.clone().set_size(None, window, cx);
5895 }
5896 }
5897 },
5898 ))
5899 .on_action(cx.listener(
5900 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
5901 adjust_active_dock_size_by_px(
5902 px_with_ui_font_fallback(act.px, cx),
5903 workspace,
5904 window,
5905 cx,
5906 );
5907 },
5908 ))
5909 .on_action(cx.listener(
5910 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
5911 adjust_active_dock_size_by_px(
5912 px_with_ui_font_fallback(act.px, cx) * -1.,
5913 workspace,
5914 window,
5915 cx,
5916 );
5917 },
5918 ))
5919 .on_action(cx.listener(
5920 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
5921 adjust_open_docks_size_by_px(
5922 px_with_ui_font_fallback(act.px, cx),
5923 workspace,
5924 window,
5925 cx,
5926 );
5927 },
5928 ))
5929 .on_action(cx.listener(
5930 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
5931 adjust_open_docks_size_by_px(
5932 px_with_ui_font_fallback(act.px, cx) * -1.,
5933 workspace,
5934 window,
5935 cx,
5936 );
5937 },
5938 ))
5939 .on_action(cx.listener(Workspace::toggle_centered_layout))
5940 .on_action(cx.listener(Workspace::cancel))
5941 }
5942
5943 #[cfg(any(test, feature = "test-support"))]
5944 pub fn test_new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
5945 use node_runtime::NodeRuntime;
5946 use session::Session;
5947
5948 let client = project.read(cx).client();
5949 let user_store = project.read(cx).user_store();
5950 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
5951 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
5952 window.activate_window();
5953 let app_state = Arc::new(AppState {
5954 languages: project.read(cx).languages().clone(),
5955 workspace_store,
5956 client,
5957 user_store,
5958 fs: project.read(cx).fs().clone(),
5959 build_window_options: |_, _| Default::default(),
5960 node_runtime: NodeRuntime::unavailable(),
5961 session,
5962 });
5963 let workspace = Self::new(Default::default(), project, app_state, window, cx);
5964 workspace
5965 .active_pane
5966 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
5967 workspace
5968 }
5969
5970 pub fn register_action<A: Action>(
5971 &mut self,
5972 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
5973 ) -> &mut Self {
5974 let callback = Arc::new(callback);
5975
5976 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
5977 let callback = callback.clone();
5978 div.on_action(cx.listener(move |workspace, event, window, cx| {
5979 (callback)(workspace, event, window, cx)
5980 }))
5981 }));
5982 self
5983 }
5984 pub fn register_action_renderer(
5985 &mut self,
5986 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
5987 ) -> &mut Self {
5988 self.workspace_actions.push(Box::new(callback));
5989 self
5990 }
5991
5992 fn add_workspace_actions_listeners(
5993 &self,
5994 mut div: Div,
5995 window: &mut Window,
5996 cx: &mut Context<Self>,
5997 ) -> Div {
5998 for action in self.workspace_actions.iter() {
5999 div = (action)(div, self, window, cx)
6000 }
6001 div
6002 }
6003
6004 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
6005 self.modal_layer.read(cx).has_active_modal()
6006 }
6007
6008 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
6009 self.modal_layer.read(cx).active_modal()
6010 }
6011
6012 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
6013 where
6014 B: FnOnce(&mut Window, &mut Context<V>) -> V,
6015 {
6016 self.modal_layer.update(cx, |modal_layer, cx| {
6017 modal_layer.toggle_modal(window, cx, build)
6018 })
6019 }
6020
6021 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
6022 self.modal_layer
6023 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
6024 }
6025
6026 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
6027 self.toast_layer
6028 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
6029 }
6030
6031 pub fn toggle_centered_layout(
6032 &mut self,
6033 _: &ToggleCenteredLayout,
6034 _: &mut Window,
6035 cx: &mut Context<Self>,
6036 ) {
6037 self.centered_layout = !self.centered_layout;
6038 if let Some(database_id) = self.database_id() {
6039 cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
6040 .detach_and_log_err(cx);
6041 }
6042 cx.notify();
6043 }
6044
6045 fn adjust_padding(padding: Option<f32>) -> f32 {
6046 padding
6047 .unwrap_or(CenteredPaddingSettings::default().0)
6048 .clamp(
6049 CenteredPaddingSettings::MIN_PADDING,
6050 CenteredPaddingSettings::MAX_PADDING,
6051 )
6052 }
6053
6054 fn render_dock(
6055 &self,
6056 position: DockPosition,
6057 dock: &Entity<Dock>,
6058 window: &mut Window,
6059 cx: &mut App,
6060 ) -> Option<Div> {
6061 if self.zoomed_position == Some(position) {
6062 return None;
6063 }
6064
6065 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
6066 let pane = panel.pane(cx)?;
6067 let follower_states = &self.follower_states;
6068 leader_border_for_pane(follower_states, &pane, window, cx)
6069 });
6070
6071 Some(
6072 div()
6073 .flex()
6074 .flex_none()
6075 .overflow_hidden()
6076 .child(dock.clone())
6077 .children(leader_border),
6078 )
6079 }
6080
6081 pub fn for_window(window: &mut Window, _: &mut App) -> Option<Entity<Workspace>> {
6082 window.root().flatten()
6083 }
6084
6085 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
6086 self.zoomed.as_ref()
6087 }
6088
6089 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
6090 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
6091 return;
6092 };
6093 let windows = cx.windows();
6094 let next_window =
6095 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
6096 || {
6097 windows
6098 .iter()
6099 .cycle()
6100 .skip_while(|window| window.window_id() != current_window_id)
6101 .nth(1)
6102 },
6103 );
6104
6105 if let Some(window) = next_window {
6106 window
6107 .update(cx, |_, window, _| window.activate_window())
6108 .ok();
6109 }
6110 }
6111
6112 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
6113 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
6114 return;
6115 };
6116 let windows = cx.windows();
6117 let prev_window =
6118 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
6119 || {
6120 windows
6121 .iter()
6122 .rev()
6123 .cycle()
6124 .skip_while(|window| window.window_id() != current_window_id)
6125 .nth(1)
6126 },
6127 );
6128
6129 if let Some(window) = prev_window {
6130 window
6131 .update(cx, |_, window, _| window.activate_window())
6132 .ok();
6133 }
6134 }
6135
6136 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
6137 if cx.stop_active_drag(window) {
6138 } else if let Some((notification_id, _)) = self.notifications.pop() {
6139 dismiss_app_notification(¬ification_id, cx);
6140 } else {
6141 cx.propagate();
6142 }
6143 }
6144
6145 fn adjust_dock_size_by_px(
6146 &mut self,
6147 panel_size: Pixels,
6148 dock_pos: DockPosition,
6149 px: Pixels,
6150 window: &mut Window,
6151 cx: &mut Context<Self>,
6152 ) {
6153 match dock_pos {
6154 DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
6155 DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
6156 DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
6157 }
6158 }
6159
6160 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
6161 let size = new_size.min(self.bounds.right() - RESIZE_HANDLE_SIZE);
6162
6163 self.left_dock.update(cx, |left_dock, cx| {
6164 if WorkspaceSettings::get_global(cx)
6165 .resize_all_panels_in_dock
6166 .contains(&DockPosition::Left)
6167 {
6168 left_dock.resize_all_panels(Some(size), window, cx);
6169 } else {
6170 left_dock.resize_active_panel(Some(size), window, cx);
6171 }
6172 });
6173 }
6174
6175 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
6176 let mut size = new_size.max(self.bounds.left() - RESIZE_HANDLE_SIZE);
6177 self.left_dock.read_with(cx, |left_dock, cx| {
6178 let left_dock_size = left_dock
6179 .active_panel_size(window, cx)
6180 .unwrap_or(Pixels::ZERO);
6181 if left_dock_size + size > self.bounds.right() {
6182 size = self.bounds.right() - left_dock_size
6183 }
6184 });
6185 self.right_dock.update(cx, |right_dock, cx| {
6186 if WorkspaceSettings::get_global(cx)
6187 .resize_all_panels_in_dock
6188 .contains(&DockPosition::Right)
6189 {
6190 right_dock.resize_all_panels(Some(size), window, cx);
6191 } else {
6192 right_dock.resize_active_panel(Some(size), window, cx);
6193 }
6194 });
6195 }
6196
6197 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
6198 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
6199 self.bottom_dock.update(cx, |bottom_dock, cx| {
6200 if WorkspaceSettings::get_global(cx)
6201 .resize_all_panels_in_dock
6202 .contains(&DockPosition::Bottom)
6203 {
6204 bottom_dock.resize_all_panels(Some(size), window, cx);
6205 } else {
6206 bottom_dock.resize_active_panel(Some(size), window, cx);
6207 }
6208 });
6209 }
6210
6211 fn toggle_edit_predictions_all_files(
6212 &mut self,
6213 _: &ToggleEditPrediction,
6214 _window: &mut Window,
6215 cx: &mut Context<Self>,
6216 ) {
6217 let fs = self.project().read(cx).fs().clone();
6218 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
6219 update_settings_file(fs, cx, move |file, _| {
6220 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
6221 });
6222 }
6223}
6224
6225fn leader_border_for_pane(
6226 follower_states: &HashMap<CollaboratorId, FollowerState>,
6227 pane: &Entity<Pane>,
6228 _: &Window,
6229 cx: &App,
6230) -> Option<Div> {
6231 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
6232 if state.pane() == pane {
6233 Some((*leader_id, state))
6234 } else {
6235 None
6236 }
6237 })?;
6238
6239 let mut leader_color = match leader_id {
6240 CollaboratorId::PeerId(leader_peer_id) => {
6241 let room = ActiveCall::try_global(cx)?.read(cx).room()?.read(cx);
6242 let leader = room.remote_participant_for_peer_id(leader_peer_id)?;
6243
6244 cx.theme()
6245 .players()
6246 .color_for_participant(leader.participant_index.0)
6247 .cursor
6248 }
6249 CollaboratorId::Agent => cx.theme().players().agent().cursor,
6250 };
6251 leader_color.fade_out(0.3);
6252 Some(
6253 div()
6254 .absolute()
6255 .size_full()
6256 .left_0()
6257 .top_0()
6258 .border_2()
6259 .border_color(leader_color),
6260 )
6261}
6262
6263fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
6264 ZED_WINDOW_POSITION
6265 .zip(*ZED_WINDOW_SIZE)
6266 .map(|(position, size)| Bounds {
6267 origin: position,
6268 size,
6269 })
6270}
6271
6272fn open_items(
6273 serialized_workspace: Option<SerializedWorkspace>,
6274 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
6275 window: &mut Window,
6276 cx: &mut Context<Workspace>,
6277) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
6278 let restored_items = serialized_workspace.map(|serialized_workspace| {
6279 Workspace::load_workspace(
6280 serialized_workspace,
6281 project_paths_to_open
6282 .iter()
6283 .map(|(_, project_path)| project_path)
6284 .cloned()
6285 .collect(),
6286 window,
6287 cx,
6288 )
6289 });
6290
6291 cx.spawn_in(window, async move |workspace, cx| {
6292 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
6293
6294 if let Some(restored_items) = restored_items {
6295 let restored_items = restored_items.await?;
6296
6297 let restored_project_paths = restored_items
6298 .iter()
6299 .filter_map(|item| {
6300 cx.update(|_, cx| item.as_ref()?.project_path(cx))
6301 .ok()
6302 .flatten()
6303 })
6304 .collect::<HashSet<_>>();
6305
6306 for restored_item in restored_items {
6307 opened_items.push(restored_item.map(Ok));
6308 }
6309
6310 project_paths_to_open
6311 .iter_mut()
6312 .for_each(|(_, project_path)| {
6313 if let Some(project_path_to_open) = project_path
6314 && restored_project_paths.contains(project_path_to_open)
6315 {
6316 *project_path = None;
6317 }
6318 });
6319 } else {
6320 for _ in 0..project_paths_to_open.len() {
6321 opened_items.push(None);
6322 }
6323 }
6324 assert!(opened_items.len() == project_paths_to_open.len());
6325
6326 let tasks =
6327 project_paths_to_open
6328 .into_iter()
6329 .enumerate()
6330 .map(|(ix, (abs_path, project_path))| {
6331 let workspace = workspace.clone();
6332 cx.spawn(async move |cx| {
6333 let file_project_path = project_path?;
6334 let abs_path_task = workspace.update(cx, |workspace, cx| {
6335 workspace.project().update(cx, |project, cx| {
6336 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
6337 })
6338 });
6339
6340 // We only want to open file paths here. If one of the items
6341 // here is a directory, it was already opened further above
6342 // with a `find_or_create_worktree`.
6343 if let Ok(task) = abs_path_task
6344 && task.await.is_none_or(|p| p.is_file())
6345 {
6346 return Some((
6347 ix,
6348 workspace
6349 .update_in(cx, |workspace, window, cx| {
6350 workspace.open_path(
6351 file_project_path,
6352 None,
6353 true,
6354 window,
6355 cx,
6356 )
6357 })
6358 .log_err()?
6359 .await,
6360 ));
6361 }
6362 None
6363 })
6364 });
6365
6366 let tasks = tasks.collect::<Vec<_>>();
6367
6368 let tasks = futures::future::join_all(tasks);
6369 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
6370 opened_items[ix] = Some(path_open_result);
6371 }
6372
6373 Ok(opened_items)
6374 })
6375}
6376
6377enum ActivateInDirectionTarget {
6378 Pane(Entity<Pane>),
6379 Dock(Entity<Dock>),
6380}
6381
6382fn notify_if_database_failed(workspace: WindowHandle<Workspace>, cx: &mut AsyncApp) {
6383 workspace
6384 .update(cx, |workspace, _, cx| {
6385 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
6386 struct DatabaseFailedNotification;
6387
6388 workspace.show_notification(
6389 NotificationId::unique::<DatabaseFailedNotification>(),
6390 cx,
6391 |cx| {
6392 cx.new(|cx| {
6393 MessageNotification::new("Failed to load the database file.", cx)
6394 .primary_message("File an Issue")
6395 .primary_icon(IconName::Plus)
6396 .primary_on_click(|window, cx| {
6397 window.dispatch_action(Box::new(FileBugReport), cx)
6398 })
6399 })
6400 },
6401 );
6402 }
6403 })
6404 .log_err();
6405}
6406
6407fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
6408 if val == 0 {
6409 ThemeSettings::get_global(cx).ui_font_size(cx)
6410 } else {
6411 px(val as f32)
6412 }
6413}
6414
6415fn adjust_active_dock_size_by_px(
6416 px: Pixels,
6417 workspace: &mut Workspace,
6418 window: &mut Window,
6419 cx: &mut Context<Workspace>,
6420) {
6421 let Some(active_dock) = workspace
6422 .all_docks()
6423 .into_iter()
6424 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
6425 else {
6426 return;
6427 };
6428 let dock = active_dock.read(cx);
6429 let Some(panel_size) = dock.active_panel_size(window, cx) else {
6430 return;
6431 };
6432 let dock_pos = dock.position();
6433 workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
6434}
6435
6436fn adjust_open_docks_size_by_px(
6437 px: Pixels,
6438 workspace: &mut Workspace,
6439 window: &mut Window,
6440 cx: &mut Context<Workspace>,
6441) {
6442 let docks = workspace
6443 .all_docks()
6444 .into_iter()
6445 .filter_map(|dock| {
6446 if dock.read(cx).is_open() {
6447 let dock = dock.read(cx);
6448 let panel_size = dock.active_panel_size(window, cx)?;
6449 let dock_pos = dock.position();
6450 Some((panel_size, dock_pos, px))
6451 } else {
6452 None
6453 }
6454 })
6455 .collect::<Vec<_>>();
6456
6457 docks
6458 .into_iter()
6459 .for_each(|(panel_size, dock_pos, offset)| {
6460 workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
6461 });
6462}
6463
6464impl Focusable for Workspace {
6465 fn focus_handle(&self, cx: &App) -> FocusHandle {
6466 self.active_pane.focus_handle(cx)
6467 }
6468}
6469
6470#[derive(Clone)]
6471struct DraggedDock(DockPosition);
6472
6473impl Render for DraggedDock {
6474 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
6475 gpui::Empty
6476 }
6477}
6478
6479impl Render for Workspace {
6480 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
6481 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
6482 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
6483 log::info!("Rendered first frame");
6484 }
6485 let mut context = KeyContext::new_with_defaults();
6486 context.add("Workspace");
6487 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6488 if let Some(status) = self
6489 .debugger_provider
6490 .as_ref()
6491 .and_then(|provider| provider.active_thread_state(cx))
6492 {
6493 match status {
6494 ThreadStatus::Running | ThreadStatus::Stepping => {
6495 context.add("debugger_running");
6496 }
6497 ThreadStatus::Stopped => context.add("debugger_stopped"),
6498 ThreadStatus::Exited | ThreadStatus::Ended => {}
6499 }
6500 }
6501
6502 if self.left_dock.read(cx).is_open() {
6503 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6504 context.set("left_dock", active_panel.panel_key());
6505 }
6506 }
6507
6508 if self.right_dock.read(cx).is_open() {
6509 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6510 context.set("right_dock", active_panel.panel_key());
6511 }
6512 }
6513
6514 if self.bottom_dock.read(cx).is_open() {
6515 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6516 context.set("bottom_dock", active_panel.panel_key());
6517 }
6518 }
6519
6520 let centered_layout = self.centered_layout
6521 && self.center.panes().len() == 1
6522 && self.active_item(cx).is_some();
6523 let render_padding = |size| {
6524 (size > 0.0).then(|| {
6525 div()
6526 .h_full()
6527 .w(relative(size))
6528 .bg(cx.theme().colors().editor_background)
6529 .border_color(cx.theme().colors().pane_group_border)
6530 })
6531 };
6532 let paddings = if centered_layout {
6533 let settings = WorkspaceSettings::get_global(cx).centered_layout;
6534 (
6535 render_padding(Self::adjust_padding(
6536 settings.left_padding.map(|padding| padding.0),
6537 )),
6538 render_padding(Self::adjust_padding(
6539 settings.right_padding.map(|padding| padding.0),
6540 )),
6541 )
6542 } else {
6543 (None, None)
6544 };
6545 let ui_font = theme::setup_ui_font(window, cx);
6546
6547 let theme = cx.theme().clone();
6548 let colors = theme.colors();
6549 let notification_entities = self
6550 .notifications
6551 .iter()
6552 .map(|(_, notification)| notification.entity_id())
6553 .collect::<Vec<_>>();
6554 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
6555
6556 client_side_decorations(
6557 self.actions(div(), window, cx)
6558 .key_context(context)
6559 .relative()
6560 .size_full()
6561 .flex()
6562 .flex_col()
6563 .font(ui_font)
6564 .gap_0()
6565 .justify_start()
6566 .items_start()
6567 .text_color(colors.text)
6568 .overflow_hidden()
6569 .children(self.titlebar_item.clone())
6570 .on_modifiers_changed(move |_, _, cx| {
6571 for &id in ¬ification_entities {
6572 cx.notify(id);
6573 }
6574 })
6575 .child(
6576 div()
6577 .size_full()
6578 .relative()
6579 .flex_1()
6580 .flex()
6581 .flex_col()
6582 .child(
6583 div()
6584 .id("workspace")
6585 .bg(colors.background)
6586 .relative()
6587 .flex_1()
6588 .w_full()
6589 .flex()
6590 .flex_col()
6591 .overflow_hidden()
6592 .border_t_1()
6593 .border_b_1()
6594 .border_color(colors.border)
6595 .child({
6596 let this = cx.entity();
6597 canvas(
6598 move |bounds, window, cx| {
6599 this.update(cx, |this, cx| {
6600 let bounds_changed = this.bounds != bounds;
6601 this.bounds = bounds;
6602
6603 if bounds_changed {
6604 this.left_dock.update(cx, |dock, cx| {
6605 dock.clamp_panel_size(
6606 bounds.size.width,
6607 window,
6608 cx,
6609 )
6610 });
6611
6612 this.right_dock.update(cx, |dock, cx| {
6613 dock.clamp_panel_size(
6614 bounds.size.width,
6615 window,
6616 cx,
6617 )
6618 });
6619
6620 this.bottom_dock.update(cx, |dock, cx| {
6621 dock.clamp_panel_size(
6622 bounds.size.height,
6623 window,
6624 cx,
6625 )
6626 });
6627 }
6628 })
6629 },
6630 |_, _, _, _| {},
6631 )
6632 .absolute()
6633 .size_full()
6634 })
6635 .when(self.zoomed.is_none(), |this| {
6636 this.on_drag_move(cx.listener(
6637 move |workspace,
6638 e: &DragMoveEvent<DraggedDock>,
6639 window,
6640 cx| {
6641 if workspace.previous_dock_drag_coordinates
6642 != Some(e.event.position)
6643 {
6644 workspace.previous_dock_drag_coordinates =
6645 Some(e.event.position);
6646 match e.drag(cx).0 {
6647 DockPosition::Left => {
6648 workspace.resize_left_dock(
6649 e.event.position.x
6650 - workspace.bounds.left(),
6651 window,
6652 cx,
6653 );
6654 }
6655 DockPosition::Right => {
6656 workspace.resize_right_dock(
6657 workspace.bounds.right()
6658 - e.event.position.x,
6659 window,
6660 cx,
6661 );
6662 }
6663 DockPosition::Bottom => {
6664 workspace.resize_bottom_dock(
6665 workspace.bounds.bottom()
6666 - e.event.position.y,
6667 window,
6668 cx,
6669 );
6670 }
6671 };
6672 workspace.serialize_workspace(window, cx);
6673 }
6674 },
6675 ))
6676 })
6677 .child({
6678 match bottom_dock_layout {
6679 BottomDockLayout::Full => div()
6680 .flex()
6681 .flex_col()
6682 .h_full()
6683 .child(
6684 div()
6685 .flex()
6686 .flex_row()
6687 .flex_1()
6688 .overflow_hidden()
6689 .children(self.render_dock(
6690 DockPosition::Left,
6691 &self.left_dock,
6692 window,
6693 cx,
6694 ))
6695 .child(
6696 div()
6697 .flex()
6698 .flex_col()
6699 .flex_1()
6700 .overflow_hidden()
6701 .child(
6702 h_flex()
6703 .flex_1()
6704 .when_some(
6705 paddings.0,
6706 |this, p| {
6707 this.child(
6708 p.border_r_1(),
6709 )
6710 },
6711 )
6712 .child(self.center.render(
6713 self.zoomed.as_ref(),
6714 &PaneRenderContext {
6715 follower_states:
6716 &self.follower_states,
6717 active_call: self.active_call(),
6718 active_pane: &self.active_pane,
6719 app_state: &self.app_state,
6720 project: &self.project,
6721 workspace: &self.weak_self,
6722 },
6723 window,
6724 cx,
6725 ))
6726 .when_some(
6727 paddings.1,
6728 |this, p| {
6729 this.child(
6730 p.border_l_1(),
6731 )
6732 },
6733 ),
6734 ),
6735 )
6736 .children(self.render_dock(
6737 DockPosition::Right,
6738 &self.right_dock,
6739 window,
6740 cx,
6741 )),
6742 )
6743 .child(div().w_full().children(self.render_dock(
6744 DockPosition::Bottom,
6745 &self.bottom_dock,
6746 window,
6747 cx
6748 ))),
6749
6750 BottomDockLayout::LeftAligned => div()
6751 .flex()
6752 .flex_row()
6753 .h_full()
6754 .child(
6755 div()
6756 .flex()
6757 .flex_col()
6758 .flex_1()
6759 .h_full()
6760 .child(
6761 div()
6762 .flex()
6763 .flex_row()
6764 .flex_1()
6765 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
6766 .child(
6767 div()
6768 .flex()
6769 .flex_col()
6770 .flex_1()
6771 .overflow_hidden()
6772 .child(
6773 h_flex()
6774 .flex_1()
6775 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
6776 .child(self.center.render(
6777 self.zoomed.as_ref(),
6778 &PaneRenderContext {
6779 follower_states:
6780 &self.follower_states,
6781 active_call: self.active_call(),
6782 active_pane: &self.active_pane,
6783 app_state: &self.app_state,
6784 project: &self.project,
6785 workspace: &self.weak_self,
6786 },
6787 window,
6788 cx,
6789 ))
6790 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
6791 )
6792 )
6793 )
6794 .child(
6795 div()
6796 .w_full()
6797 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
6798 ),
6799 )
6800 .children(self.render_dock(
6801 DockPosition::Right,
6802 &self.right_dock,
6803 window,
6804 cx,
6805 )),
6806
6807 BottomDockLayout::RightAligned => div()
6808 .flex()
6809 .flex_row()
6810 .h_full()
6811 .children(self.render_dock(
6812 DockPosition::Left,
6813 &self.left_dock,
6814 window,
6815 cx,
6816 ))
6817 .child(
6818 div()
6819 .flex()
6820 .flex_col()
6821 .flex_1()
6822 .h_full()
6823 .child(
6824 div()
6825 .flex()
6826 .flex_row()
6827 .flex_1()
6828 .child(
6829 div()
6830 .flex()
6831 .flex_col()
6832 .flex_1()
6833 .overflow_hidden()
6834 .child(
6835 h_flex()
6836 .flex_1()
6837 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
6838 .child(self.center.render(
6839 self.zoomed.as_ref(),
6840 &PaneRenderContext {
6841 follower_states:
6842 &self.follower_states,
6843 active_call: self.active_call(),
6844 active_pane: &self.active_pane,
6845 app_state: &self.app_state,
6846 project: &self.project,
6847 workspace: &self.weak_self,
6848 },
6849 window,
6850 cx,
6851 ))
6852 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
6853 )
6854 )
6855 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
6856 )
6857 .child(
6858 div()
6859 .w_full()
6860 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
6861 ),
6862 ),
6863
6864 BottomDockLayout::Contained => div()
6865 .flex()
6866 .flex_row()
6867 .h_full()
6868 .children(self.render_dock(
6869 DockPosition::Left,
6870 &self.left_dock,
6871 window,
6872 cx,
6873 ))
6874 .child(
6875 div()
6876 .flex()
6877 .flex_col()
6878 .flex_1()
6879 .overflow_hidden()
6880 .child(
6881 h_flex()
6882 .flex_1()
6883 .when_some(paddings.0, |this, p| {
6884 this.child(p.border_r_1())
6885 })
6886 .child(self.center.render(
6887 self.zoomed.as_ref(),
6888 &PaneRenderContext {
6889 follower_states:
6890 &self.follower_states,
6891 active_call: self.active_call(),
6892 active_pane: &self.active_pane,
6893 app_state: &self.app_state,
6894 project: &self.project,
6895 workspace: &self.weak_self,
6896 },
6897 window,
6898 cx,
6899 ))
6900 .when_some(paddings.1, |this, p| {
6901 this.child(p.border_l_1())
6902 }),
6903 )
6904 .children(self.render_dock(
6905 DockPosition::Bottom,
6906 &self.bottom_dock,
6907 window,
6908 cx,
6909 )),
6910 )
6911 .children(self.render_dock(
6912 DockPosition::Right,
6913 &self.right_dock,
6914 window,
6915 cx,
6916 )),
6917 }
6918 })
6919 .children(self.zoomed.as_ref().and_then(|view| {
6920 let zoomed_view = view.upgrade()?;
6921 let div = div()
6922 .occlude()
6923 .absolute()
6924 .overflow_hidden()
6925 .border_color(colors.border)
6926 .bg(colors.background)
6927 .child(zoomed_view)
6928 .inset_0()
6929 .shadow_lg();
6930
6931 if !WorkspaceSettings::get_global(cx).zoomed_padding {
6932 return Some(div);
6933 }
6934
6935 Some(match self.zoomed_position {
6936 Some(DockPosition::Left) => div.right_2().border_r_1(),
6937 Some(DockPosition::Right) => div.left_2().border_l_1(),
6938 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
6939 None => {
6940 div.top_2().bottom_2().left_2().right_2().border_1()
6941 }
6942 })
6943 }))
6944 .children(self.render_notifications(window, cx)),
6945 )
6946 .when(self.status_bar_visible(cx), |parent| {
6947 parent.child(self.status_bar.clone())
6948 })
6949 .child(self.modal_layer.clone())
6950 .child(self.toast_layer.clone()),
6951 ),
6952 window,
6953 cx,
6954 )
6955 }
6956}
6957
6958impl WorkspaceStore {
6959 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
6960 Self {
6961 workspaces: Default::default(),
6962 _subscriptions: vec![
6963 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
6964 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
6965 ],
6966 client,
6967 }
6968 }
6969
6970 pub fn update_followers(
6971 &self,
6972 project_id: Option<u64>,
6973 update: proto::update_followers::Variant,
6974 cx: &App,
6975 ) -> Option<()> {
6976 let active_call = ActiveCall::try_global(cx)?;
6977 let room_id = active_call.read(cx).room()?.read(cx).id();
6978 self.client
6979 .send(proto::UpdateFollowers {
6980 room_id,
6981 project_id,
6982 variant: Some(update),
6983 })
6984 .log_err()
6985 }
6986
6987 pub async fn handle_follow(
6988 this: Entity<Self>,
6989 envelope: TypedEnvelope<proto::Follow>,
6990 mut cx: AsyncApp,
6991 ) -> Result<proto::FollowResponse> {
6992 this.update(&mut cx, |this, cx| {
6993 let follower = Follower {
6994 project_id: envelope.payload.project_id,
6995 peer_id: envelope.original_sender_id()?,
6996 };
6997
6998 let mut response = proto::FollowResponse::default();
6999 this.workspaces.retain(|workspace| {
7000 workspace
7001 .update(cx, |workspace, window, cx| {
7002 let handler_response =
7003 workspace.handle_follow(follower.project_id, window, cx);
7004 if let Some(active_view) = handler_response.active_view
7005 && workspace.project.read(cx).remote_id() == follower.project_id
7006 {
7007 response.active_view = Some(active_view)
7008 }
7009 })
7010 .is_ok()
7011 });
7012
7013 Ok(response)
7014 })?
7015 }
7016
7017 async fn handle_update_followers(
7018 this: Entity<Self>,
7019 envelope: TypedEnvelope<proto::UpdateFollowers>,
7020 mut cx: AsyncApp,
7021 ) -> Result<()> {
7022 let leader_id = envelope.original_sender_id()?;
7023 let update = envelope.payload;
7024
7025 this.update(&mut cx, |this, cx| {
7026 this.workspaces.retain(|workspace| {
7027 workspace
7028 .update(cx, |workspace, window, cx| {
7029 let project_id = workspace.project.read(cx).remote_id();
7030 if update.project_id != project_id && update.project_id.is_some() {
7031 return;
7032 }
7033 workspace.handle_update_followers(leader_id, update.clone(), window, cx);
7034 })
7035 .is_ok()
7036 });
7037 Ok(())
7038 })?
7039 }
7040
7041 pub fn workspaces(&self) -> &HashSet<WindowHandle<Workspace>> {
7042 &self.workspaces
7043 }
7044}
7045
7046impl ViewId {
7047 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
7048 Ok(Self {
7049 creator: message
7050 .creator
7051 .map(CollaboratorId::PeerId)
7052 .context("creator is missing")?,
7053 id: message.id,
7054 })
7055 }
7056
7057 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
7058 if let CollaboratorId::PeerId(peer_id) = self.creator {
7059 Some(proto::ViewId {
7060 creator: Some(peer_id),
7061 id: self.id,
7062 })
7063 } else {
7064 None
7065 }
7066 }
7067}
7068
7069impl FollowerState {
7070 fn pane(&self) -> &Entity<Pane> {
7071 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
7072 }
7073}
7074
7075pub trait WorkspaceHandle {
7076 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
7077}
7078
7079impl WorkspaceHandle for Entity<Workspace> {
7080 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
7081 self.read(cx)
7082 .worktrees(cx)
7083 .flat_map(|worktree| {
7084 let worktree_id = worktree.read(cx).id();
7085 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
7086 worktree_id,
7087 path: f.path.clone(),
7088 })
7089 })
7090 .collect::<Vec<_>>()
7091 }
7092}
7093
7094pub async fn last_opened_workspace_location() -> Option<(SerializedWorkspaceLocation, PathList)> {
7095 DB.last_workspace().await.log_err().flatten()
7096}
7097
7098pub fn last_session_workspace_locations(
7099 last_session_id: &str,
7100 last_session_window_stack: Option<Vec<WindowId>>,
7101) -> Option<Vec<(SerializedWorkspaceLocation, PathList)>> {
7102 DB.last_session_workspace_locations(last_session_id, last_session_window_stack)
7103 .log_err()
7104}
7105
7106actions!(
7107 collab,
7108 [
7109 /// Opens the channel notes for the current call.
7110 ///
7111 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
7112 /// channel in the collab panel.
7113 ///
7114 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
7115 /// can be copied via "Copy link to section" in the context menu of the channel notes
7116 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
7117 OpenChannelNotes,
7118 /// Mutes your microphone.
7119 Mute,
7120 /// Deafens yourself (mute both microphone and speakers).
7121 Deafen,
7122 /// Leaves the current call.
7123 LeaveCall,
7124 /// Shares the current project with collaborators.
7125 ShareProject,
7126 /// Shares your screen with collaborators.
7127 ScreenShare
7128 ]
7129);
7130actions!(
7131 zed,
7132 [
7133 /// Opens the Zed log file.
7134 OpenLog,
7135 /// Reveals the Zed log file in the system file manager.
7136 RevealLogInFileManager
7137 ]
7138);
7139
7140async fn join_channel_internal(
7141 channel_id: ChannelId,
7142 app_state: &Arc<AppState>,
7143 requesting_window: Option<WindowHandle<Workspace>>,
7144 active_call: &Entity<ActiveCall>,
7145 cx: &mut AsyncApp,
7146) -> Result<bool> {
7147 let (should_prompt, open_room) = active_call.update(cx, |active_call, cx| {
7148 let Some(room) = active_call.room().map(|room| room.read(cx)) else {
7149 return (false, None);
7150 };
7151
7152 let already_in_channel = room.channel_id() == Some(channel_id);
7153 let should_prompt = room.is_sharing_project()
7154 && !room.remote_participants().is_empty()
7155 && !already_in_channel;
7156 let open_room = if already_in_channel {
7157 active_call.room().cloned()
7158 } else {
7159 None
7160 };
7161 (should_prompt, open_room)
7162 })?;
7163
7164 if let Some(room) = open_room {
7165 let task = room.update(cx, |room, cx| {
7166 if let Some((project, host)) = room.most_active_project(cx) {
7167 return Some(join_in_room_project(project, host, app_state.clone(), cx));
7168 }
7169
7170 None
7171 })?;
7172 if let Some(task) = task {
7173 task.await?;
7174 }
7175 return anyhow::Ok(true);
7176 }
7177
7178 if should_prompt {
7179 if let Some(workspace) = requesting_window {
7180 let answer = workspace
7181 .update(cx, |_, window, cx| {
7182 window.prompt(
7183 PromptLevel::Warning,
7184 "Do you want to switch channels?",
7185 Some("Leaving this call will unshare your current project."),
7186 &["Yes, Join Channel", "Cancel"],
7187 cx,
7188 )
7189 })?
7190 .await;
7191
7192 if answer == Ok(1) {
7193 return Ok(false);
7194 }
7195 } else {
7196 return Ok(false); // unreachable!() hopefully
7197 }
7198 }
7199
7200 let client = cx.update(|cx| active_call.read(cx).client())?;
7201
7202 let mut client_status = client.status();
7203
7204 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
7205 'outer: loop {
7206 let Some(status) = client_status.recv().await else {
7207 anyhow::bail!("error connecting");
7208 };
7209
7210 match status {
7211 Status::Connecting
7212 | Status::Authenticating
7213 | Status::Authenticated
7214 | Status::Reconnecting
7215 | Status::Reauthenticating
7216 | Status::Reauthenticated => continue,
7217 Status::Connected { .. } => break 'outer,
7218 Status::SignedOut | Status::AuthenticationError => {
7219 return Err(ErrorCode::SignedOut.into());
7220 }
7221 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
7222 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
7223 return Err(ErrorCode::Disconnected.into());
7224 }
7225 }
7226 }
7227
7228 let room = active_call
7229 .update(cx, |active_call, cx| {
7230 active_call.join_channel(channel_id, cx)
7231 })?
7232 .await?;
7233
7234 let Some(room) = room else {
7235 return anyhow::Ok(true);
7236 };
7237
7238 room.update(cx, |room, _| room.room_update_completed())?
7239 .await;
7240
7241 let task = room.update(cx, |room, cx| {
7242 if let Some((project, host)) = room.most_active_project(cx) {
7243 return Some(join_in_room_project(project, host, app_state.clone(), cx));
7244 }
7245
7246 // If you are the first to join a channel, see if you should share your project.
7247 if room.remote_participants().is_empty()
7248 && !room.local_participant_is_guest()
7249 && let Some(workspace) = requesting_window
7250 {
7251 let project = workspace.update(cx, |workspace, _, cx| {
7252 let project = workspace.project.read(cx);
7253
7254 if !CallSettings::get_global(cx).share_on_join {
7255 return None;
7256 }
7257
7258 if (project.is_local() || project.is_via_remote_server())
7259 && project.visible_worktrees(cx).any(|tree| {
7260 tree.read(cx)
7261 .root_entry()
7262 .is_some_and(|entry| entry.is_dir())
7263 })
7264 {
7265 Some(workspace.project.clone())
7266 } else {
7267 None
7268 }
7269 });
7270 if let Ok(Some(project)) = project {
7271 return Some(cx.spawn(async move |room, cx| {
7272 room.update(cx, |room, cx| room.share_project(project, cx))?
7273 .await?;
7274 Ok(())
7275 }));
7276 }
7277 }
7278
7279 None
7280 })?;
7281 if let Some(task) = task {
7282 task.await?;
7283 return anyhow::Ok(true);
7284 }
7285 anyhow::Ok(false)
7286}
7287
7288pub fn join_channel(
7289 channel_id: ChannelId,
7290 app_state: Arc<AppState>,
7291 requesting_window: Option<WindowHandle<Workspace>>,
7292 cx: &mut App,
7293) -> Task<Result<()>> {
7294 let active_call = ActiveCall::global(cx);
7295 cx.spawn(async move |cx| {
7296 let result = join_channel_internal(
7297 channel_id,
7298 &app_state,
7299 requesting_window,
7300 &active_call,
7301 cx,
7302 )
7303 .await;
7304
7305 // join channel succeeded, and opened a window
7306 if matches!(result, Ok(true)) {
7307 return anyhow::Ok(());
7308 }
7309
7310 // find an existing workspace to focus and show call controls
7311 let mut active_window =
7312 requesting_window.or_else(|| activate_any_workspace_window( cx));
7313 if active_window.is_none() {
7314 // no open workspaces, make one to show the error in (blergh)
7315 let (window_handle, _) = cx
7316 .update(|cx| {
7317 Workspace::new_local(vec![], app_state.clone(), requesting_window, None, cx)
7318 })?
7319 .await?;
7320
7321 if result.is_ok() {
7322 cx.update(|cx| {
7323 cx.dispatch_action(&OpenChannelNotes);
7324 }).log_err();
7325 }
7326
7327 active_window = Some(window_handle);
7328 }
7329
7330 if let Err(err) = result {
7331 log::error!("failed to join channel: {}", err);
7332 if let Some(active_window) = active_window {
7333 active_window
7334 .update(cx, |_, window, cx| {
7335 let detail: SharedString = match err.error_code() {
7336 ErrorCode::SignedOut => {
7337 "Please sign in to continue.".into()
7338 }
7339 ErrorCode::UpgradeRequired => {
7340 "Your are running an unsupported version of Zed. Please update to continue.".into()
7341 }
7342 ErrorCode::NoSuchChannel => {
7343 "No matching channel was found. Please check the link and try again.".into()
7344 }
7345 ErrorCode::Forbidden => {
7346 "This channel is private, and you do not have access. Please ask someone to add you and try again.".into()
7347 }
7348 ErrorCode::Disconnected => "Please check your internet connection and try again.".into(),
7349 _ => format!("{}\n\nPlease try again.", err).into(),
7350 };
7351 window.prompt(
7352 PromptLevel::Critical,
7353 "Failed to join channel",
7354 Some(&detail),
7355 &["Ok"],
7356 cx)
7357 })?
7358 .await
7359 .ok();
7360 }
7361 }
7362
7363 // return ok, we showed the error to the user.
7364 anyhow::Ok(())
7365 })
7366}
7367
7368pub async fn get_any_active_workspace(
7369 app_state: Arc<AppState>,
7370 mut cx: AsyncApp,
7371) -> anyhow::Result<WindowHandle<Workspace>> {
7372 // find an existing workspace to focus and show call controls
7373 let active_window = activate_any_workspace_window(&mut cx);
7374 if active_window.is_none() {
7375 cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, cx))?
7376 .await?;
7377 }
7378 activate_any_workspace_window(&mut cx).context("could not open zed")
7379}
7380
7381fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<Workspace>> {
7382 cx.update(|cx| {
7383 if let Some(workspace_window) = cx
7384 .active_window()
7385 .and_then(|window| window.downcast::<Workspace>())
7386 {
7387 return Some(workspace_window);
7388 }
7389
7390 for window in cx.windows() {
7391 if let Some(workspace_window) = window.downcast::<Workspace>() {
7392 workspace_window
7393 .update(cx, |_, window, _| window.activate_window())
7394 .ok();
7395 return Some(workspace_window);
7396 }
7397 }
7398 None
7399 })
7400 .ok()
7401 .flatten()
7402}
7403
7404pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<Workspace>> {
7405 cx.windows()
7406 .into_iter()
7407 .filter_map(|window| window.downcast::<Workspace>())
7408 .filter(|workspace| {
7409 workspace
7410 .read(cx)
7411 .is_ok_and(|workspace| workspace.project.read(cx).is_local())
7412 })
7413 .collect()
7414}
7415
7416#[derive(Default)]
7417pub struct OpenOptions {
7418 pub visible: Option<OpenVisible>,
7419 pub focus: Option<bool>,
7420 pub open_new_workspace: Option<bool>,
7421 pub prefer_focused_window: bool,
7422 pub replace_window: Option<WindowHandle<Workspace>>,
7423 pub env: Option<HashMap<String, String>>,
7424}
7425
7426#[allow(clippy::type_complexity)]
7427pub fn open_paths(
7428 abs_paths: &[PathBuf],
7429 app_state: Arc<AppState>,
7430 open_options: OpenOptions,
7431 cx: &mut App,
7432) -> Task<
7433 anyhow::Result<(
7434 WindowHandle<Workspace>,
7435 Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
7436 )>,
7437> {
7438 let abs_paths = abs_paths.to_vec();
7439 let mut existing = None;
7440 let mut best_match = None;
7441 let mut open_visible = OpenVisible::All;
7442 #[cfg(target_os = "windows")]
7443 let wsl_path = abs_paths
7444 .iter()
7445 .find_map(|p| util::paths::WslPath::from_path(p));
7446
7447 cx.spawn(async move |cx| {
7448 if open_options.open_new_workspace != Some(true) {
7449 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
7450 let all_metadatas = futures::future::join_all(all_paths)
7451 .await
7452 .into_iter()
7453 .filter_map(|result| result.ok().flatten())
7454 .collect::<Vec<_>>();
7455
7456 cx.update(|cx| {
7457 for window in local_workspace_windows(cx) {
7458 if let Ok(workspace) = window.read(cx) {
7459 let m = workspace.project.read(cx).visibility_for_paths(
7460 &abs_paths,
7461 &all_metadatas,
7462 open_options.open_new_workspace == None,
7463 cx,
7464 );
7465 if m > best_match {
7466 existing = Some(window);
7467 best_match = m;
7468 } else if best_match.is_none()
7469 && open_options.open_new_workspace == Some(false)
7470 {
7471 existing = Some(window)
7472 }
7473 }
7474 }
7475 })?;
7476
7477 if open_options.open_new_workspace.is_none()
7478 && (existing.is_none() || open_options.prefer_focused_window)
7479 && all_metadatas.iter().all(|file| !file.is_dir)
7480 {
7481 cx.update(|cx| {
7482 if let Some(window) = cx
7483 .active_window()
7484 .and_then(|window| window.downcast::<Workspace>())
7485 && let Ok(workspace) = window.read(cx)
7486 {
7487 let project = workspace.project().read(cx);
7488 if project.is_local() && !project.is_via_collab() {
7489 existing = Some(window);
7490 open_visible = OpenVisible::None;
7491 return;
7492 }
7493 }
7494 for window in local_workspace_windows(cx) {
7495 if let Ok(workspace) = window.read(cx) {
7496 let project = workspace.project().read(cx);
7497 if project.is_via_collab() {
7498 continue;
7499 }
7500 existing = Some(window);
7501 open_visible = OpenVisible::None;
7502 break;
7503 }
7504 }
7505 })?;
7506 }
7507 }
7508
7509 let result = if let Some(existing) = existing {
7510 let open_task = existing
7511 .update(cx, |workspace, window, cx| {
7512 window.activate_window();
7513 workspace.open_paths(
7514 abs_paths,
7515 OpenOptions {
7516 visible: Some(open_visible),
7517 ..Default::default()
7518 },
7519 None,
7520 window,
7521 cx,
7522 )
7523 })?
7524 .await;
7525
7526 _ = existing.update(cx, |workspace, _, cx| {
7527 for item in open_task.iter().flatten() {
7528 if let Err(e) = item {
7529 workspace.show_error(&e, cx);
7530 }
7531 }
7532 });
7533
7534 Ok((existing, open_task))
7535 } else {
7536 cx.update(move |cx| {
7537 Workspace::new_local(
7538 abs_paths,
7539 app_state.clone(),
7540 open_options.replace_window,
7541 open_options.env,
7542 cx,
7543 )
7544 })?
7545 .await
7546 };
7547
7548 #[cfg(target_os = "windows")]
7549 if let Some(util::paths::WslPath{distro, path}) = wsl_path
7550 && let Ok((workspace, _)) = &result
7551 {
7552 workspace
7553 .update(cx, move |workspace, _window, cx| {
7554 struct OpenInWsl;
7555 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
7556 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
7557 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
7558 cx.new(move |cx| {
7559 MessageNotification::new(msg, cx)
7560 .primary_message("Open in WSL")
7561 .primary_icon(IconName::FolderOpen)
7562 .primary_on_click(move |window, cx| {
7563 window.dispatch_action(Box::new(remote::OpenWslPath {
7564 distro: remote::WslConnectionOptions {
7565 distro_name: distro.clone(),
7566 user: None,
7567 },
7568 paths: vec![path.clone().into()],
7569 }), cx)
7570 })
7571 })
7572 });
7573 })
7574 .unwrap();
7575 };
7576 result
7577 })
7578}
7579
7580pub fn open_new(
7581 open_options: OpenOptions,
7582 app_state: Arc<AppState>,
7583 cx: &mut App,
7584 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
7585) -> Task<anyhow::Result<()>> {
7586 let task = Workspace::new_local(Vec::new(), app_state, None, open_options.env, cx);
7587 cx.spawn(async move |cx| {
7588 let (workspace, opened_paths) = task.await?;
7589 workspace.update(cx, |workspace, window, cx| {
7590 if opened_paths.is_empty() {
7591 init(workspace, window, cx)
7592 }
7593 })?;
7594 Ok(())
7595 })
7596}
7597
7598pub fn create_and_open_local_file(
7599 path: &'static Path,
7600 window: &mut Window,
7601 cx: &mut Context<Workspace>,
7602 default_content: impl 'static + Send + FnOnce(&mut AsyncApp) -> Rope,
7603) -> Task<Result<Box<dyn ItemHandle>>> {
7604 cx.spawn_in(window, async move |workspace, cx| {
7605 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
7606 if !fs.is_file(path).await {
7607 fs.create_file(path, Default::default()).await?;
7608 let encoding_wrapper = EncodingWrapper::new(UTF_8);
7609 fs.save(
7610 path,
7611 &default_content(),
7612 Default::default(),
7613 encoding_wrapper,
7614 )
7615 .await?;
7616 }
7617
7618 let mut items = workspace
7619 .update_in(cx, |workspace, window, cx| {
7620 workspace.with_local_workspace(window, cx, |workspace, window, cx| {
7621 workspace.open_paths(
7622 vec![path.to_path_buf()],
7623 OpenOptions {
7624 visible: Some(OpenVisible::None),
7625 ..Default::default()
7626 },
7627 None,
7628 window,
7629 cx,
7630 )
7631 })
7632 })?
7633 .await?
7634 .await;
7635
7636 let item = items.pop().flatten();
7637 item.with_context(|| format!("path {path:?} is not a file"))?
7638 })
7639}
7640
7641pub fn open_remote_project_with_new_connection(
7642 window: WindowHandle<Workspace>,
7643 remote_connection: Arc<dyn RemoteConnection>,
7644 cancel_rx: oneshot::Receiver<()>,
7645 delegate: Arc<dyn RemoteClientDelegate>,
7646 app_state: Arc<AppState>,
7647 paths: Vec<PathBuf>,
7648 cx: &mut App,
7649) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
7650 cx.spawn(async move |cx| {
7651 let (workspace_id, serialized_workspace) =
7652 serialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
7653 .await?;
7654
7655 let session = match cx
7656 .update(|cx| {
7657 remote::RemoteClient::new(
7658 ConnectionIdentifier::Workspace(workspace_id.0),
7659 remote_connection,
7660 cancel_rx,
7661 delegate,
7662 cx,
7663 )
7664 })?
7665 .await?
7666 {
7667 Some(result) => result,
7668 None => return Ok(Vec::new()),
7669 };
7670
7671 let project = cx.update(|cx| {
7672 project::Project::remote(
7673 session,
7674 app_state.client.clone(),
7675 app_state.node_runtime.clone(),
7676 app_state.user_store.clone(),
7677 app_state.languages.clone(),
7678 app_state.fs.clone(),
7679 cx,
7680 )
7681 })?;
7682
7683 open_remote_project_inner(
7684 project,
7685 paths,
7686 workspace_id,
7687 serialized_workspace,
7688 app_state,
7689 window,
7690 cx,
7691 )
7692 .await
7693 })
7694}
7695
7696pub fn open_remote_project_with_existing_connection(
7697 connection_options: RemoteConnectionOptions,
7698 project: Entity<Project>,
7699 paths: Vec<PathBuf>,
7700 app_state: Arc<AppState>,
7701 window: WindowHandle<Workspace>,
7702 cx: &mut AsyncApp,
7703) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
7704 cx.spawn(async move |cx| {
7705 let (workspace_id, serialized_workspace) =
7706 serialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
7707
7708 open_remote_project_inner(
7709 project,
7710 paths,
7711 workspace_id,
7712 serialized_workspace,
7713 app_state,
7714 window,
7715 cx,
7716 )
7717 .await
7718 })
7719}
7720
7721async fn open_remote_project_inner(
7722 project: Entity<Project>,
7723 paths: Vec<PathBuf>,
7724 workspace_id: WorkspaceId,
7725 serialized_workspace: Option<SerializedWorkspace>,
7726 app_state: Arc<AppState>,
7727 window: WindowHandle<Workspace>,
7728 cx: &mut AsyncApp,
7729) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
7730 let toolchains = DB.toolchains(workspace_id).await?;
7731 for (toolchain, worktree_id, path) in toolchains {
7732 project
7733 .update(cx, |this, cx| {
7734 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
7735 })?
7736 .await;
7737 }
7738 let mut project_paths_to_open = vec![];
7739 let mut project_path_errors = vec![];
7740
7741 for path in paths {
7742 let result = cx
7743 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))?
7744 .await;
7745 match result {
7746 Ok((_, project_path)) => {
7747 project_paths_to_open.push((path.clone(), Some(project_path)));
7748 }
7749 Err(error) => {
7750 project_path_errors.push(error);
7751 }
7752 };
7753 }
7754
7755 if project_paths_to_open.is_empty() {
7756 return Err(project_path_errors.pop().context("no paths given")?);
7757 }
7758
7759 if let Some(detach_session_task) = window
7760 .update(cx, |_workspace, window, cx| {
7761 cx.spawn_in(window, async move |this, cx| {
7762 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))
7763 })
7764 })
7765 .ok()
7766 {
7767 detach_session_task.await.ok();
7768 }
7769
7770 cx.update_window(window.into(), |_, window, cx| {
7771 window.replace_root(cx, |window, cx| {
7772 telemetry::event!("SSH Project Opened");
7773
7774 let mut workspace =
7775 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
7776 workspace.update_history(cx);
7777
7778 if let Some(ref serialized) = serialized_workspace {
7779 workspace.centered_layout = serialized.centered_layout;
7780 }
7781
7782 workspace
7783 });
7784 })?;
7785
7786 let items = window
7787 .update(cx, |_, window, cx| {
7788 window.activate_window();
7789 open_items(serialized_workspace, project_paths_to_open, window, cx)
7790 })?
7791 .await?;
7792
7793 window.update(cx, |workspace, _, cx| {
7794 for error in project_path_errors {
7795 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
7796 if let Some(path) = error.error_tag("path") {
7797 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
7798 }
7799 } else {
7800 workspace.show_error(&error, cx)
7801 }
7802 }
7803 })?;
7804
7805 Ok(items.into_iter().map(|item| item?.ok()).collect())
7806}
7807
7808fn serialize_remote_project(
7809 connection_options: RemoteConnectionOptions,
7810 paths: Vec<PathBuf>,
7811 cx: &AsyncApp,
7812) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
7813 cx.background_spawn(async move {
7814 let remote_connection_id = persistence::DB
7815 .get_or_create_remote_connection(connection_options)
7816 .await?;
7817
7818 let serialized_workspace =
7819 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
7820
7821 let workspace_id = if let Some(workspace_id) =
7822 serialized_workspace.as_ref().map(|workspace| workspace.id)
7823 {
7824 workspace_id
7825 } else {
7826 persistence::DB.next_id().await?
7827 };
7828
7829 Ok((workspace_id, serialized_workspace))
7830 })
7831}
7832
7833pub fn join_in_room_project(
7834 project_id: u64,
7835 follow_user_id: u64,
7836 app_state: Arc<AppState>,
7837 cx: &mut App,
7838) -> Task<Result<()>> {
7839 let windows = cx.windows();
7840 cx.spawn(async move |cx| {
7841 let existing_workspace = windows.into_iter().find_map(|window_handle| {
7842 window_handle
7843 .downcast::<Workspace>()
7844 .and_then(|window_handle| {
7845 window_handle
7846 .update(cx, |workspace, _window, cx| {
7847 if workspace.project().read(cx).remote_id() == Some(project_id) {
7848 Some(window_handle)
7849 } else {
7850 None
7851 }
7852 })
7853 .unwrap_or(None)
7854 })
7855 });
7856
7857 let workspace = if let Some(existing_workspace) = existing_workspace {
7858 existing_workspace
7859 } else {
7860 let active_call = cx.update(|cx| ActiveCall::global(cx))?;
7861 let room = active_call
7862 .read_with(cx, |call, _| call.room().cloned())?
7863 .context("not in a call")?;
7864 let project = room
7865 .update(cx, |room, cx| {
7866 room.join_project(
7867 project_id,
7868 app_state.languages.clone(),
7869 app_state.fs.clone(),
7870 cx,
7871 )
7872 })?
7873 .await?;
7874
7875 let window_bounds_override = window_bounds_env_override();
7876 cx.update(|cx| {
7877 let mut options = (app_state.build_window_options)(None, cx);
7878 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
7879 cx.open_window(options, |window, cx| {
7880 cx.new(|cx| {
7881 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
7882 })
7883 })
7884 })??
7885 };
7886
7887 workspace.update(cx, |workspace, window, cx| {
7888 cx.activate(true);
7889 window.activate_window();
7890
7891 if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
7892 let follow_peer_id = room
7893 .read(cx)
7894 .remote_participants()
7895 .iter()
7896 .find(|(_, participant)| participant.user.id == follow_user_id)
7897 .map(|(_, p)| p.peer_id)
7898 .or_else(|| {
7899 // If we couldn't follow the given user, follow the host instead.
7900 let collaborator = workspace
7901 .project()
7902 .read(cx)
7903 .collaborators()
7904 .values()
7905 .find(|collaborator| collaborator.is_host)?;
7906 Some(collaborator.peer_id)
7907 });
7908
7909 if let Some(follow_peer_id) = follow_peer_id {
7910 workspace.follow(follow_peer_id, window, cx);
7911 }
7912 }
7913 })?;
7914
7915 anyhow::Ok(())
7916 })
7917}
7918
7919pub fn reload(cx: &mut App) {
7920 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
7921 let mut workspace_windows = cx
7922 .windows()
7923 .into_iter()
7924 .filter_map(|window| window.downcast::<Workspace>())
7925 .collect::<Vec<_>>();
7926
7927 // If multiple windows have unsaved changes, and need a save prompt,
7928 // prompt in the active window before switching to a different window.
7929 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
7930
7931 let mut prompt = None;
7932 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
7933 prompt = window
7934 .update(cx, |_, window, cx| {
7935 window.prompt(
7936 PromptLevel::Info,
7937 "Are you sure you want to restart?",
7938 None,
7939 &["Restart", "Cancel"],
7940 cx,
7941 )
7942 })
7943 .ok();
7944 }
7945
7946 cx.spawn(async move |cx| {
7947 if let Some(prompt) = prompt {
7948 let answer = prompt.await?;
7949 if answer != 0 {
7950 return Ok(());
7951 }
7952 }
7953
7954 // If the user cancels any save prompt, then keep the app open.
7955 for window in workspace_windows {
7956 if let Ok(should_close) = window.update(cx, |workspace, window, cx| {
7957 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
7958 }) && !should_close.await?
7959 {
7960 return Ok(());
7961 }
7962 }
7963 cx.update(|cx| cx.restart())
7964 })
7965 .detach_and_log_err(cx);
7966}
7967
7968fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
7969 let mut parts = value.split(',');
7970 let x: usize = parts.next()?.parse().ok()?;
7971 let y: usize = parts.next()?.parse().ok()?;
7972 Some(point(px(x as f32), px(y as f32)))
7973}
7974
7975fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
7976 let mut parts = value.split(',');
7977 let width: usize = parts.next()?.parse().ok()?;
7978 let height: usize = parts.next()?.parse().ok()?;
7979 Some(size(px(width as f32), px(height as f32)))
7980}
7981
7982/// Add client-side decorations (rounded corners, shadows, resize handling) when appropriate.
7983pub fn client_side_decorations(
7984 element: impl IntoElement,
7985 window: &mut Window,
7986 cx: &mut App,
7987) -> Stateful<Div> {
7988 const BORDER_SIZE: Pixels = px(1.0);
7989 let decorations = window.window_decorations();
7990
7991 match decorations {
7992 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
7993 Decorations::Server => window.set_client_inset(px(0.0)),
7994 }
7995
7996 struct GlobalResizeEdge(ResizeEdge);
7997 impl Global for GlobalResizeEdge {}
7998
7999 div()
8000 .id("window-backdrop")
8001 .bg(transparent_black())
8002 .map(|div| match decorations {
8003 Decorations::Server => div,
8004 Decorations::Client { tiling, .. } => div
8005 .when(!(tiling.top || tiling.right), |div| {
8006 div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8007 })
8008 .when(!(tiling.top || tiling.left), |div| {
8009 div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8010 })
8011 .when(!(tiling.bottom || tiling.right), |div| {
8012 div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8013 })
8014 .when(!(tiling.bottom || tiling.left), |div| {
8015 div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8016 })
8017 .when(!tiling.top, |div| {
8018 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
8019 })
8020 .when(!tiling.bottom, |div| {
8021 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
8022 })
8023 .when(!tiling.left, |div| {
8024 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
8025 })
8026 .when(!tiling.right, |div| {
8027 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
8028 })
8029 .on_mouse_move(move |e, window, cx| {
8030 let size = window.window_bounds().get_bounds().size;
8031 let pos = e.position;
8032
8033 let new_edge =
8034 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
8035
8036 let edge = cx.try_global::<GlobalResizeEdge>();
8037 if new_edge != edge.map(|edge| edge.0) {
8038 window
8039 .window_handle()
8040 .update(cx, |workspace, _, cx| {
8041 cx.notify(workspace.entity_id());
8042 })
8043 .ok();
8044 }
8045 })
8046 .on_mouse_down(MouseButton::Left, move |e, window, _| {
8047 let size = window.window_bounds().get_bounds().size;
8048 let pos = e.position;
8049
8050 let edge = match resize_edge(
8051 pos,
8052 theme::CLIENT_SIDE_DECORATION_SHADOW,
8053 size,
8054 tiling,
8055 ) {
8056 Some(value) => value,
8057 None => return,
8058 };
8059
8060 window.start_window_resize(edge);
8061 }),
8062 })
8063 .size_full()
8064 .child(
8065 div()
8066 .cursor(CursorStyle::Arrow)
8067 .map(|div| match decorations {
8068 Decorations::Server => div,
8069 Decorations::Client { tiling } => div
8070 .border_color(cx.theme().colors().border)
8071 .when(!(tiling.top || tiling.right), |div| {
8072 div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8073 })
8074 .when(!(tiling.top || tiling.left), |div| {
8075 div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8076 })
8077 .when(!(tiling.bottom || tiling.right), |div| {
8078 div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8079 })
8080 .when(!(tiling.bottom || tiling.left), |div| {
8081 div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8082 })
8083 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
8084 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
8085 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
8086 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
8087 .when(!tiling.is_tiled(), |div| {
8088 div.shadow(vec![gpui::BoxShadow {
8089 color: Hsla {
8090 h: 0.,
8091 s: 0.,
8092 l: 0.,
8093 a: 0.4,
8094 },
8095 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
8096 spread_radius: px(0.),
8097 offset: point(px(0.0), px(0.0)),
8098 }])
8099 }),
8100 })
8101 .on_mouse_move(|_e, _, cx| {
8102 cx.stop_propagation();
8103 })
8104 .size_full()
8105 .child(element),
8106 )
8107 .map(|div| match decorations {
8108 Decorations::Server => div,
8109 Decorations::Client { tiling, .. } => div.child(
8110 canvas(
8111 |_bounds, window, _| {
8112 window.insert_hitbox(
8113 Bounds::new(
8114 point(px(0.0), px(0.0)),
8115 window.window_bounds().get_bounds().size,
8116 ),
8117 HitboxBehavior::Normal,
8118 )
8119 },
8120 move |_bounds, hitbox, window, cx| {
8121 let mouse = window.mouse_position();
8122 let size = window.window_bounds().get_bounds().size;
8123 let Some(edge) =
8124 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
8125 else {
8126 return;
8127 };
8128 cx.set_global(GlobalResizeEdge(edge));
8129 window.set_cursor_style(
8130 match edge {
8131 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
8132 ResizeEdge::Left | ResizeEdge::Right => {
8133 CursorStyle::ResizeLeftRight
8134 }
8135 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
8136 CursorStyle::ResizeUpLeftDownRight
8137 }
8138 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
8139 CursorStyle::ResizeUpRightDownLeft
8140 }
8141 },
8142 &hitbox,
8143 );
8144 },
8145 )
8146 .size_full()
8147 .absolute(),
8148 ),
8149 })
8150}
8151
8152fn resize_edge(
8153 pos: Point<Pixels>,
8154 shadow_size: Pixels,
8155 window_size: Size<Pixels>,
8156 tiling: Tiling,
8157) -> Option<ResizeEdge> {
8158 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
8159 if bounds.contains(&pos) {
8160 return None;
8161 }
8162
8163 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
8164 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
8165 if !tiling.top && top_left_bounds.contains(&pos) {
8166 return Some(ResizeEdge::TopLeft);
8167 }
8168
8169 let top_right_bounds = Bounds::new(
8170 Point::new(window_size.width - corner_size.width, px(0.)),
8171 corner_size,
8172 );
8173 if !tiling.top && top_right_bounds.contains(&pos) {
8174 return Some(ResizeEdge::TopRight);
8175 }
8176
8177 let bottom_left_bounds = Bounds::new(
8178 Point::new(px(0.), window_size.height - corner_size.height),
8179 corner_size,
8180 );
8181 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
8182 return Some(ResizeEdge::BottomLeft);
8183 }
8184
8185 let bottom_right_bounds = Bounds::new(
8186 Point::new(
8187 window_size.width - corner_size.width,
8188 window_size.height - corner_size.height,
8189 ),
8190 corner_size,
8191 );
8192 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
8193 return Some(ResizeEdge::BottomRight);
8194 }
8195
8196 if !tiling.top && pos.y < shadow_size {
8197 Some(ResizeEdge::Top)
8198 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
8199 Some(ResizeEdge::Bottom)
8200 } else if !tiling.left && pos.x < shadow_size {
8201 Some(ResizeEdge::Left)
8202 } else if !tiling.right && pos.x > window_size.width - shadow_size {
8203 Some(ResizeEdge::Right)
8204 } else {
8205 None
8206 }
8207}
8208
8209fn join_pane_into_active(
8210 active_pane: &Entity<Pane>,
8211 pane: &Entity<Pane>,
8212 window: &mut Window,
8213 cx: &mut App,
8214) {
8215 if pane == active_pane {
8216 } else if pane.read(cx).items_len() == 0 {
8217 pane.update(cx, |_, cx| {
8218 cx.emit(pane::Event::Remove {
8219 focus_on_pane: None,
8220 });
8221 })
8222 } else {
8223 move_all_items(pane, active_pane, window, cx);
8224 }
8225}
8226
8227fn move_all_items(
8228 from_pane: &Entity<Pane>,
8229 to_pane: &Entity<Pane>,
8230 window: &mut Window,
8231 cx: &mut App,
8232) {
8233 let destination_is_different = from_pane != to_pane;
8234 let mut moved_items = 0;
8235 for (item_ix, item_handle) in from_pane
8236 .read(cx)
8237 .items()
8238 .enumerate()
8239 .map(|(ix, item)| (ix, item.clone()))
8240 .collect::<Vec<_>>()
8241 {
8242 let ix = item_ix - moved_items;
8243 if destination_is_different {
8244 // Close item from previous pane
8245 from_pane.update(cx, |source, cx| {
8246 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
8247 });
8248 moved_items += 1;
8249 }
8250
8251 // This automatically removes duplicate items in the pane
8252 to_pane.update(cx, |destination, cx| {
8253 destination.add_item(item_handle, true, true, None, window, cx);
8254 window.focus(&destination.focus_handle(cx))
8255 });
8256 }
8257}
8258
8259pub fn move_item(
8260 source: &Entity<Pane>,
8261 destination: &Entity<Pane>,
8262 item_id_to_move: EntityId,
8263 destination_index: usize,
8264 activate: bool,
8265 window: &mut Window,
8266 cx: &mut App,
8267) {
8268 let Some((item_ix, item_handle)) = source
8269 .read(cx)
8270 .items()
8271 .enumerate()
8272 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
8273 .map(|(ix, item)| (ix, item.clone()))
8274 else {
8275 // Tab was closed during drag
8276 return;
8277 };
8278
8279 if source != destination {
8280 // Close item from previous pane
8281 source.update(cx, |source, cx| {
8282 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
8283 });
8284 }
8285
8286 // This automatically removes duplicate items in the pane
8287 destination.update(cx, |destination, cx| {
8288 destination.add_item_inner(
8289 item_handle,
8290 activate,
8291 activate,
8292 activate,
8293 Some(destination_index),
8294 window,
8295 cx,
8296 );
8297 if activate {
8298 window.focus(&destination.focus_handle(cx))
8299 }
8300 });
8301}
8302
8303pub fn move_active_item(
8304 source: &Entity<Pane>,
8305 destination: &Entity<Pane>,
8306 focus_destination: bool,
8307 close_if_empty: bool,
8308 window: &mut Window,
8309 cx: &mut App,
8310) {
8311 if source == destination {
8312 return;
8313 }
8314 let Some(active_item) = source.read(cx).active_item() else {
8315 return;
8316 };
8317 source.update(cx, |source_pane, cx| {
8318 let item_id = active_item.item_id();
8319 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
8320 destination.update(cx, |target_pane, cx| {
8321 target_pane.add_item(
8322 active_item,
8323 focus_destination,
8324 focus_destination,
8325 Some(target_pane.items_len()),
8326 window,
8327 cx,
8328 );
8329 });
8330 });
8331}
8332
8333pub fn clone_active_item(
8334 workspace_id: Option<WorkspaceId>,
8335 source: &Entity<Pane>,
8336 destination: &Entity<Pane>,
8337 focus_destination: bool,
8338 window: &mut Window,
8339 cx: &mut App,
8340) {
8341 if source == destination {
8342 return;
8343 }
8344 let Some(active_item) = source.read(cx).active_item() else {
8345 return;
8346 };
8347 if !active_item.can_split(cx) {
8348 return;
8349 }
8350 let destination = destination.downgrade();
8351 let task = active_item.clone_on_split(workspace_id, window, cx);
8352 window
8353 .spawn(cx, async move |cx| {
8354 let Some(clone) = task.await else {
8355 return;
8356 };
8357 destination
8358 .update_in(cx, |target_pane, window, cx| {
8359 target_pane.add_item(
8360 clone,
8361 focus_destination,
8362 focus_destination,
8363 Some(target_pane.items_len()),
8364 window,
8365 cx,
8366 );
8367 })
8368 .log_err();
8369 })
8370 .detach();
8371}
8372
8373#[derive(Debug)]
8374pub struct WorkspacePosition {
8375 pub window_bounds: Option<WindowBounds>,
8376 pub display: Option<Uuid>,
8377 pub centered_layout: bool,
8378}
8379
8380pub fn remote_workspace_position_from_db(
8381 connection_options: RemoteConnectionOptions,
8382 paths_to_open: &[PathBuf],
8383 cx: &App,
8384) -> Task<Result<WorkspacePosition>> {
8385 let paths = paths_to_open.to_vec();
8386
8387 cx.background_spawn(async move {
8388 let remote_connection_id = persistence::DB
8389 .get_or_create_remote_connection(connection_options)
8390 .await
8391 .context("fetching serialized ssh project")?;
8392 let serialized_workspace =
8393 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
8394
8395 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
8396 (Some(WindowBounds::Windowed(bounds)), None)
8397 } else {
8398 let restorable_bounds = serialized_workspace
8399 .as_ref()
8400 .and_then(|workspace| Some((workspace.display?, workspace.window_bounds?)))
8401 .or_else(|| {
8402 let (display, window_bounds) = DB.last_window().log_err()?;
8403 Some((display?, window_bounds?))
8404 });
8405
8406 if let Some((serialized_display, serialized_status)) = restorable_bounds {
8407 (Some(serialized_status.0), Some(serialized_display))
8408 } else {
8409 (None, None)
8410 }
8411 };
8412
8413 let centered_layout = serialized_workspace
8414 .as_ref()
8415 .map(|w| w.centered_layout)
8416 .unwrap_or(false);
8417
8418 Ok(WorkspacePosition {
8419 window_bounds,
8420 display,
8421 centered_layout,
8422 })
8423 })
8424}
8425
8426pub fn with_active_or_new_workspace(
8427 cx: &mut App,
8428 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
8429) {
8430 match cx.active_window().and_then(|w| w.downcast::<Workspace>()) {
8431 Some(workspace) => {
8432 cx.defer(move |cx| {
8433 workspace
8434 .update(cx, |workspace, window, cx| f(workspace, window, cx))
8435 .log_err();
8436 });
8437 }
8438 None => {
8439 let app_state = AppState::global(cx);
8440 if let Some(app_state) = app_state.upgrade() {
8441 open_new(
8442 OpenOptions::default(),
8443 app_state,
8444 cx,
8445 move |workspace, window, cx| f(workspace, window, cx),
8446 )
8447 .detach_and_log_err(cx);
8448 }
8449 }
8450 }
8451}
8452
8453#[cfg(test)]
8454mod tests {
8455 use std::{cell::RefCell, rc::Rc};
8456
8457 use super::*;
8458 use crate::{
8459 dock::{PanelEvent, test::TestPanel},
8460 item::{
8461 ItemBufferKind, ItemEvent,
8462 test::{TestItem, TestProjectItem},
8463 },
8464 };
8465 use fs::FakeFs;
8466 use gpui::{
8467 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
8468 UpdateGlobal, VisualTestContext, px,
8469 };
8470 use project::{Project, ProjectEntryId};
8471 use serde_json::json;
8472 use settings::SettingsStore;
8473 use util::rel_path::rel_path;
8474
8475 #[gpui::test]
8476 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
8477 init_test(cx);
8478
8479 let fs = FakeFs::new(cx.executor());
8480 let project = Project::test(fs, [], cx).await;
8481 let (workspace, cx) =
8482 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8483
8484 // Adding an item with no ambiguity renders the tab without detail.
8485 let item1 = cx.new(|cx| {
8486 let mut item = TestItem::new(cx);
8487 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
8488 item
8489 });
8490 workspace.update_in(cx, |workspace, window, cx| {
8491 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
8492 });
8493 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
8494
8495 // Adding an item that creates ambiguity increases the level of detail on
8496 // both tabs.
8497 let item2 = cx.new_window_entity(|_window, cx| {
8498 let mut item = TestItem::new(cx);
8499 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
8500 item
8501 });
8502 workspace.update_in(cx, |workspace, window, cx| {
8503 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
8504 });
8505 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
8506 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
8507
8508 // Adding an item that creates ambiguity increases the level of detail only
8509 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
8510 // we stop at the highest detail available.
8511 let item3 = cx.new(|cx| {
8512 let mut item = TestItem::new(cx);
8513 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
8514 item
8515 });
8516 workspace.update_in(cx, |workspace, window, cx| {
8517 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
8518 });
8519 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
8520 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
8521 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
8522 }
8523
8524 #[gpui::test]
8525 async fn test_tracking_active_path(cx: &mut TestAppContext) {
8526 init_test(cx);
8527
8528 let fs = FakeFs::new(cx.executor());
8529 fs.insert_tree(
8530 "/root1",
8531 json!({
8532 "one.txt": "",
8533 "two.txt": "",
8534 }),
8535 )
8536 .await;
8537 fs.insert_tree(
8538 "/root2",
8539 json!({
8540 "three.txt": "",
8541 }),
8542 )
8543 .await;
8544
8545 let project = Project::test(fs, ["root1".as_ref()], cx).await;
8546 let (workspace, cx) =
8547 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8548 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8549 let worktree_id = project.update(cx, |project, cx| {
8550 project.worktrees(cx).next().unwrap().read(cx).id()
8551 });
8552
8553 let item1 = cx.new(|cx| {
8554 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
8555 });
8556 let item2 = cx.new(|cx| {
8557 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
8558 });
8559
8560 // Add an item to an empty pane
8561 workspace.update_in(cx, |workspace, window, cx| {
8562 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
8563 });
8564 project.update(cx, |project, cx| {
8565 assert_eq!(
8566 project.active_entry(),
8567 project
8568 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
8569 .map(|e| e.id)
8570 );
8571 });
8572 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
8573
8574 // Add a second item to a non-empty pane
8575 workspace.update_in(cx, |workspace, window, cx| {
8576 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
8577 });
8578 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
8579 project.update(cx, |project, cx| {
8580 assert_eq!(
8581 project.active_entry(),
8582 project
8583 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
8584 .map(|e| e.id)
8585 );
8586 });
8587
8588 // Close the active item
8589 pane.update_in(cx, |pane, window, cx| {
8590 pane.close_active_item(&Default::default(), window, cx)
8591 })
8592 .await
8593 .unwrap();
8594 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
8595 project.update(cx, |project, cx| {
8596 assert_eq!(
8597 project.active_entry(),
8598 project
8599 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
8600 .map(|e| e.id)
8601 );
8602 });
8603
8604 // Add a project folder
8605 project
8606 .update(cx, |project, cx| {
8607 project.find_or_create_worktree("root2", true, cx)
8608 })
8609 .await
8610 .unwrap();
8611 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
8612
8613 // Remove a project folder
8614 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
8615 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
8616 }
8617
8618 #[gpui::test]
8619 async fn test_close_window(cx: &mut TestAppContext) {
8620 init_test(cx);
8621
8622 let fs = FakeFs::new(cx.executor());
8623 fs.insert_tree("/root", json!({ "one": "" })).await;
8624
8625 let project = Project::test(fs, ["root".as_ref()], cx).await;
8626 let (workspace, cx) =
8627 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8628
8629 // When there are no dirty items, there's nothing to do.
8630 let item1 = cx.new(TestItem::new);
8631 workspace.update_in(cx, |w, window, cx| {
8632 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
8633 });
8634 let task = workspace.update_in(cx, |w, window, cx| {
8635 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
8636 });
8637 assert!(task.await.unwrap());
8638
8639 // When there are dirty untitled items, prompt to save each one. If the user
8640 // cancels any prompt, then abort.
8641 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
8642 let item3 = cx.new(|cx| {
8643 TestItem::new(cx)
8644 .with_dirty(true)
8645 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
8646 });
8647 workspace.update_in(cx, |w, window, cx| {
8648 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
8649 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
8650 });
8651 let task = workspace.update_in(cx, |w, window, cx| {
8652 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
8653 });
8654 cx.executor().run_until_parked();
8655 cx.simulate_prompt_answer("Cancel"); // cancel save all
8656 cx.executor().run_until_parked();
8657 assert!(!cx.has_pending_prompt());
8658 assert!(!task.await.unwrap());
8659 }
8660
8661 #[gpui::test]
8662 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
8663 init_test(cx);
8664
8665 // Register TestItem as a serializable item
8666 cx.update(|cx| {
8667 register_serializable_item::<TestItem>(cx);
8668 });
8669
8670 let fs = FakeFs::new(cx.executor());
8671 fs.insert_tree("/root", json!({ "one": "" })).await;
8672
8673 let project = Project::test(fs, ["root".as_ref()], cx).await;
8674 let (workspace, cx) =
8675 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8676
8677 // When there are dirty untitled items, but they can serialize, then there is no prompt.
8678 let item1 = cx.new(|cx| {
8679 TestItem::new(cx)
8680 .with_dirty(true)
8681 .with_serialize(|| Some(Task::ready(Ok(()))))
8682 });
8683 let item2 = cx.new(|cx| {
8684 TestItem::new(cx)
8685 .with_dirty(true)
8686 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
8687 .with_serialize(|| Some(Task::ready(Ok(()))))
8688 });
8689 workspace.update_in(cx, |w, window, cx| {
8690 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
8691 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
8692 });
8693 let task = workspace.update_in(cx, |w, window, cx| {
8694 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
8695 });
8696 assert!(task.await.unwrap());
8697 }
8698
8699 #[gpui::test]
8700 async fn test_close_pane_items(cx: &mut TestAppContext) {
8701 init_test(cx);
8702
8703 let fs = FakeFs::new(cx.executor());
8704
8705 let project = Project::test(fs, None, cx).await;
8706 let (workspace, cx) =
8707 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8708
8709 let item1 = cx.new(|cx| {
8710 TestItem::new(cx)
8711 .with_dirty(true)
8712 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
8713 });
8714 let item2 = cx.new(|cx| {
8715 TestItem::new(cx)
8716 .with_dirty(true)
8717 .with_conflict(true)
8718 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
8719 });
8720 let item3 = cx.new(|cx| {
8721 TestItem::new(cx)
8722 .with_dirty(true)
8723 .with_conflict(true)
8724 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
8725 });
8726 let item4 = cx.new(|cx| {
8727 TestItem::new(cx).with_dirty(true).with_project_items(&[{
8728 let project_item = TestProjectItem::new_untitled(cx);
8729 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
8730 project_item
8731 }])
8732 });
8733 let pane = workspace.update_in(cx, |workspace, window, cx| {
8734 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
8735 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
8736 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
8737 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
8738 workspace.active_pane().clone()
8739 });
8740
8741 let close_items = pane.update_in(cx, |pane, window, cx| {
8742 pane.activate_item(1, true, true, window, cx);
8743 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
8744 let item1_id = item1.item_id();
8745 let item3_id = item3.item_id();
8746 let item4_id = item4.item_id();
8747 pane.close_items(window, cx, SaveIntent::Close, move |id| {
8748 [item1_id, item3_id, item4_id].contains(&id)
8749 })
8750 });
8751 cx.executor().run_until_parked();
8752
8753 assert!(cx.has_pending_prompt());
8754 cx.simulate_prompt_answer("Save all");
8755
8756 cx.executor().run_until_parked();
8757
8758 // Item 1 is saved. There's a prompt to save item 3.
8759 pane.update(cx, |pane, cx| {
8760 assert_eq!(item1.read(cx).save_count, 1);
8761 assert_eq!(item1.read(cx).save_as_count, 0);
8762 assert_eq!(item1.read(cx).reload_count, 0);
8763 assert_eq!(pane.items_len(), 3);
8764 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
8765 });
8766 assert!(cx.has_pending_prompt());
8767
8768 // Cancel saving item 3.
8769 cx.simulate_prompt_answer("Discard");
8770 cx.executor().run_until_parked();
8771
8772 // Item 3 is reloaded. There's a prompt to save item 4.
8773 pane.update(cx, |pane, cx| {
8774 assert_eq!(item3.read(cx).save_count, 0);
8775 assert_eq!(item3.read(cx).save_as_count, 0);
8776 assert_eq!(item3.read(cx).reload_count, 1);
8777 assert_eq!(pane.items_len(), 2);
8778 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
8779 });
8780
8781 // There's a prompt for a path for item 4.
8782 cx.simulate_new_path_selection(|_| Some(Default::default()));
8783 close_items.await.unwrap();
8784
8785 // The requested items are closed.
8786 pane.update(cx, |pane, cx| {
8787 assert_eq!(item4.read(cx).save_count, 0);
8788 assert_eq!(item4.read(cx).save_as_count, 1);
8789 assert_eq!(item4.read(cx).reload_count, 0);
8790 assert_eq!(pane.items_len(), 1);
8791 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
8792 });
8793 }
8794
8795 #[gpui::test]
8796 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
8797 init_test(cx);
8798
8799 let fs = FakeFs::new(cx.executor());
8800 let project = Project::test(fs, [], cx).await;
8801 let (workspace, cx) =
8802 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8803
8804 // Create several workspace items with single project entries, and two
8805 // workspace items with multiple project entries.
8806 let single_entry_items = (0..=4)
8807 .map(|project_entry_id| {
8808 cx.new(|cx| {
8809 TestItem::new(cx)
8810 .with_dirty(true)
8811 .with_project_items(&[dirty_project_item(
8812 project_entry_id,
8813 &format!("{project_entry_id}.txt"),
8814 cx,
8815 )])
8816 })
8817 })
8818 .collect::<Vec<_>>();
8819 let item_2_3 = cx.new(|cx| {
8820 TestItem::new(cx)
8821 .with_dirty(true)
8822 .with_buffer_kind(ItemBufferKind::Multibuffer)
8823 .with_project_items(&[
8824 single_entry_items[2].read(cx).project_items[0].clone(),
8825 single_entry_items[3].read(cx).project_items[0].clone(),
8826 ])
8827 });
8828 let item_3_4 = cx.new(|cx| {
8829 TestItem::new(cx)
8830 .with_dirty(true)
8831 .with_buffer_kind(ItemBufferKind::Multibuffer)
8832 .with_project_items(&[
8833 single_entry_items[3].read(cx).project_items[0].clone(),
8834 single_entry_items[4].read(cx).project_items[0].clone(),
8835 ])
8836 });
8837
8838 // Create two panes that contain the following project entries:
8839 // left pane:
8840 // multi-entry items: (2, 3)
8841 // single-entry items: 0, 2, 3, 4
8842 // right pane:
8843 // single-entry items: 4, 1
8844 // multi-entry items: (3, 4)
8845 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
8846 let left_pane = workspace.active_pane().clone();
8847 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
8848 workspace.add_item_to_active_pane(
8849 single_entry_items[0].boxed_clone(),
8850 None,
8851 true,
8852 window,
8853 cx,
8854 );
8855 workspace.add_item_to_active_pane(
8856 single_entry_items[2].boxed_clone(),
8857 None,
8858 true,
8859 window,
8860 cx,
8861 );
8862 workspace.add_item_to_active_pane(
8863 single_entry_items[3].boxed_clone(),
8864 None,
8865 true,
8866 window,
8867 cx,
8868 );
8869 workspace.add_item_to_active_pane(
8870 single_entry_items[4].boxed_clone(),
8871 None,
8872 true,
8873 window,
8874 cx,
8875 );
8876
8877 let right_pane =
8878 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
8879
8880 let boxed_clone = single_entry_items[1].boxed_clone();
8881 let right_pane = window.spawn(cx, async move |cx| {
8882 right_pane.await.inspect(|right_pane| {
8883 right_pane
8884 .update_in(cx, |pane, window, cx| {
8885 pane.add_item(boxed_clone, true, true, None, window, cx);
8886 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
8887 })
8888 .unwrap();
8889 })
8890 });
8891
8892 (left_pane, right_pane)
8893 });
8894 let right_pane = right_pane.await.unwrap();
8895 cx.focus(&right_pane);
8896
8897 let mut close = right_pane.update_in(cx, |pane, window, cx| {
8898 pane.close_all_items(&CloseAllItems::default(), window, cx)
8899 .unwrap()
8900 });
8901 cx.executor().run_until_parked();
8902
8903 let msg = cx.pending_prompt().unwrap().0;
8904 assert!(msg.contains("1.txt"));
8905 assert!(!msg.contains("2.txt"));
8906 assert!(!msg.contains("3.txt"));
8907 assert!(!msg.contains("4.txt"));
8908
8909 cx.simulate_prompt_answer("Cancel");
8910 close.await;
8911
8912 left_pane
8913 .update_in(cx, |left_pane, window, cx| {
8914 left_pane.close_item_by_id(
8915 single_entry_items[3].entity_id(),
8916 SaveIntent::Skip,
8917 window,
8918 cx,
8919 )
8920 })
8921 .await
8922 .unwrap();
8923
8924 close = right_pane.update_in(cx, |pane, window, cx| {
8925 pane.close_all_items(&CloseAllItems::default(), window, cx)
8926 .unwrap()
8927 });
8928 cx.executor().run_until_parked();
8929
8930 let details = cx.pending_prompt().unwrap().1;
8931 assert!(details.contains("1.txt"));
8932 assert!(!details.contains("2.txt"));
8933 assert!(details.contains("3.txt"));
8934 // ideally this assertion could be made, but today we can only
8935 // save whole items not project items, so the orphaned item 3 causes
8936 // 4 to be saved too.
8937 // assert!(!details.contains("4.txt"));
8938
8939 cx.simulate_prompt_answer("Save all");
8940
8941 cx.executor().run_until_parked();
8942 close.await;
8943 right_pane.read_with(cx, |pane, _| {
8944 assert_eq!(pane.items_len(), 0);
8945 });
8946 }
8947
8948 #[gpui::test]
8949 async fn test_autosave(cx: &mut gpui::TestAppContext) {
8950 init_test(cx);
8951
8952 let fs = FakeFs::new(cx.executor());
8953 let project = Project::test(fs, [], cx).await;
8954 let (workspace, cx) =
8955 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8956 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8957
8958 let item = cx.new(|cx| {
8959 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
8960 });
8961 let item_id = item.entity_id();
8962 workspace.update_in(cx, |workspace, window, cx| {
8963 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
8964 });
8965
8966 // Autosave on window change.
8967 item.update(cx, |item, cx| {
8968 SettingsStore::update_global(cx, |settings, cx| {
8969 settings.update_user_settings(cx, |settings| {
8970 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
8971 })
8972 });
8973 item.is_dirty = true;
8974 });
8975
8976 // Deactivating the window saves the file.
8977 cx.deactivate_window();
8978 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
8979
8980 // Re-activating the window doesn't save the file.
8981 cx.update(|window, _| window.activate_window());
8982 cx.executor().run_until_parked();
8983 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
8984
8985 // Autosave on focus change.
8986 item.update_in(cx, |item, window, cx| {
8987 cx.focus_self(window);
8988 SettingsStore::update_global(cx, |settings, cx| {
8989 settings.update_user_settings(cx, |settings| {
8990 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
8991 })
8992 });
8993 item.is_dirty = true;
8994 });
8995 // Blurring the item saves the file.
8996 item.update_in(cx, |_, window, _| window.blur());
8997 cx.executor().run_until_parked();
8998 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
8999
9000 // Deactivating the window still saves the file.
9001 item.update_in(cx, |item, window, cx| {
9002 cx.focus_self(window);
9003 item.is_dirty = true;
9004 });
9005 cx.deactivate_window();
9006 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
9007
9008 // Autosave after delay.
9009 item.update(cx, |item, cx| {
9010 SettingsStore::update_global(cx, |settings, cx| {
9011 settings.update_user_settings(cx, |settings| {
9012 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
9013 milliseconds: 500.into(),
9014 });
9015 })
9016 });
9017 item.is_dirty = true;
9018 cx.emit(ItemEvent::Edit);
9019 });
9020
9021 // Delay hasn't fully expired, so the file is still dirty and unsaved.
9022 cx.executor().advance_clock(Duration::from_millis(250));
9023 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
9024
9025 // After delay expires, the file is saved.
9026 cx.executor().advance_clock(Duration::from_millis(250));
9027 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
9028
9029 // Autosave after delay, should save earlier than delay if tab is closed
9030 item.update(cx, |item, cx| {
9031 item.is_dirty = true;
9032 cx.emit(ItemEvent::Edit);
9033 });
9034 cx.executor().advance_clock(Duration::from_millis(250));
9035 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
9036
9037 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
9038 pane.update_in(cx, |pane, window, cx| {
9039 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
9040 })
9041 .await
9042 .unwrap();
9043 assert!(!cx.has_pending_prompt());
9044 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
9045
9046 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
9047 workspace.update_in(cx, |workspace, window, cx| {
9048 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
9049 });
9050 item.update_in(cx, |item, _window, cx| {
9051 item.is_dirty = true;
9052 for project_item in &mut item.project_items {
9053 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
9054 }
9055 });
9056 cx.run_until_parked();
9057 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
9058
9059 // Autosave on focus change, ensuring closing the tab counts as such.
9060 item.update(cx, |item, cx| {
9061 SettingsStore::update_global(cx, |settings, cx| {
9062 settings.update_user_settings(cx, |settings| {
9063 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
9064 })
9065 });
9066 item.is_dirty = true;
9067 for project_item in &mut item.project_items {
9068 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
9069 }
9070 });
9071
9072 pane.update_in(cx, |pane, window, cx| {
9073 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
9074 })
9075 .await
9076 .unwrap();
9077 assert!(!cx.has_pending_prompt());
9078 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
9079
9080 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
9081 workspace.update_in(cx, |workspace, window, cx| {
9082 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
9083 });
9084 item.update_in(cx, |item, window, cx| {
9085 item.project_items[0].update(cx, |item, _| {
9086 item.entry_id = None;
9087 });
9088 item.is_dirty = true;
9089 window.blur();
9090 });
9091 cx.run_until_parked();
9092 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
9093
9094 // Ensure autosave is prevented for deleted files also when closing the buffer.
9095 let _close_items = pane.update_in(cx, |pane, window, cx| {
9096 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
9097 });
9098 cx.run_until_parked();
9099 assert!(cx.has_pending_prompt());
9100 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
9101 }
9102
9103 #[gpui::test]
9104 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
9105 init_test(cx);
9106
9107 let fs = FakeFs::new(cx.executor());
9108
9109 let project = Project::test(fs, [], cx).await;
9110 let (workspace, cx) =
9111 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9112
9113 let item = cx.new(|cx| {
9114 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
9115 });
9116 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9117 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
9118 let toolbar_notify_count = Rc::new(RefCell::new(0));
9119
9120 workspace.update_in(cx, |workspace, window, cx| {
9121 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
9122 let toolbar_notification_count = toolbar_notify_count.clone();
9123 cx.observe_in(&toolbar, window, move |_, _, _, _| {
9124 *toolbar_notification_count.borrow_mut() += 1
9125 })
9126 .detach();
9127 });
9128
9129 pane.read_with(cx, |pane, _| {
9130 assert!(!pane.can_navigate_backward());
9131 assert!(!pane.can_navigate_forward());
9132 });
9133
9134 item.update_in(cx, |item, _, cx| {
9135 item.set_state("one".to_string(), cx);
9136 });
9137
9138 // Toolbar must be notified to re-render the navigation buttons
9139 assert_eq!(*toolbar_notify_count.borrow(), 1);
9140
9141 pane.read_with(cx, |pane, _| {
9142 assert!(pane.can_navigate_backward());
9143 assert!(!pane.can_navigate_forward());
9144 });
9145
9146 workspace
9147 .update_in(cx, |workspace, window, cx| {
9148 workspace.go_back(pane.downgrade(), window, cx)
9149 })
9150 .await
9151 .unwrap();
9152
9153 assert_eq!(*toolbar_notify_count.borrow(), 2);
9154 pane.read_with(cx, |pane, _| {
9155 assert!(!pane.can_navigate_backward());
9156 assert!(pane.can_navigate_forward());
9157 });
9158 }
9159
9160 #[gpui::test]
9161 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
9162 init_test(cx);
9163 let fs = FakeFs::new(cx.executor());
9164
9165 let project = Project::test(fs, [], cx).await;
9166 let (workspace, cx) =
9167 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9168
9169 let panel = workspace.update_in(cx, |workspace, window, cx| {
9170 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
9171 workspace.add_panel(panel.clone(), window, cx);
9172
9173 workspace
9174 .right_dock()
9175 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
9176
9177 panel
9178 });
9179
9180 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9181 pane.update_in(cx, |pane, window, cx| {
9182 let item = cx.new(TestItem::new);
9183 pane.add_item(Box::new(item), true, true, None, window, cx);
9184 });
9185
9186 // Transfer focus from center to panel
9187 workspace.update_in(cx, |workspace, window, cx| {
9188 workspace.toggle_panel_focus::<TestPanel>(window, cx);
9189 });
9190
9191 workspace.update_in(cx, |workspace, window, cx| {
9192 assert!(workspace.right_dock().read(cx).is_open());
9193 assert!(!panel.is_zoomed(window, cx));
9194 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9195 });
9196
9197 // Transfer focus from panel to center
9198 workspace.update_in(cx, |workspace, window, cx| {
9199 workspace.toggle_panel_focus::<TestPanel>(window, cx);
9200 });
9201
9202 workspace.update_in(cx, |workspace, window, cx| {
9203 assert!(workspace.right_dock().read(cx).is_open());
9204 assert!(!panel.is_zoomed(window, cx));
9205 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9206 });
9207
9208 // Close the dock
9209 workspace.update_in(cx, |workspace, window, cx| {
9210 workspace.toggle_dock(DockPosition::Right, window, cx);
9211 });
9212
9213 workspace.update_in(cx, |workspace, window, cx| {
9214 assert!(!workspace.right_dock().read(cx).is_open());
9215 assert!(!panel.is_zoomed(window, cx));
9216 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9217 });
9218
9219 // Open the dock
9220 workspace.update_in(cx, |workspace, window, cx| {
9221 workspace.toggle_dock(DockPosition::Right, window, cx);
9222 });
9223
9224 workspace.update_in(cx, |workspace, window, cx| {
9225 assert!(workspace.right_dock().read(cx).is_open());
9226 assert!(!panel.is_zoomed(window, cx));
9227 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9228 });
9229
9230 // Focus and zoom panel
9231 panel.update_in(cx, |panel, window, cx| {
9232 cx.focus_self(window);
9233 panel.set_zoomed(true, window, cx)
9234 });
9235
9236 workspace.update_in(cx, |workspace, window, cx| {
9237 assert!(workspace.right_dock().read(cx).is_open());
9238 assert!(panel.is_zoomed(window, cx));
9239 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9240 });
9241
9242 // Transfer focus to the center closes the dock
9243 workspace.update_in(cx, |workspace, window, cx| {
9244 workspace.toggle_panel_focus::<TestPanel>(window, cx);
9245 });
9246
9247 workspace.update_in(cx, |workspace, window, cx| {
9248 assert!(!workspace.right_dock().read(cx).is_open());
9249 assert!(panel.is_zoomed(window, cx));
9250 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9251 });
9252
9253 // Transferring focus back to the panel keeps it zoomed
9254 workspace.update_in(cx, |workspace, window, cx| {
9255 workspace.toggle_panel_focus::<TestPanel>(window, cx);
9256 });
9257
9258 workspace.update_in(cx, |workspace, window, cx| {
9259 assert!(workspace.right_dock().read(cx).is_open());
9260 assert!(panel.is_zoomed(window, cx));
9261 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9262 });
9263
9264 // Close the dock while it is zoomed
9265 workspace.update_in(cx, |workspace, window, cx| {
9266 workspace.toggle_dock(DockPosition::Right, window, cx)
9267 });
9268
9269 workspace.update_in(cx, |workspace, window, cx| {
9270 assert!(!workspace.right_dock().read(cx).is_open());
9271 assert!(panel.is_zoomed(window, cx));
9272 assert!(workspace.zoomed.is_none());
9273 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9274 });
9275
9276 // Opening the dock, when it's zoomed, retains focus
9277 workspace.update_in(cx, |workspace, window, cx| {
9278 workspace.toggle_dock(DockPosition::Right, window, cx)
9279 });
9280
9281 workspace.update_in(cx, |workspace, window, cx| {
9282 assert!(workspace.right_dock().read(cx).is_open());
9283 assert!(panel.is_zoomed(window, cx));
9284 assert!(workspace.zoomed.is_some());
9285 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9286 });
9287
9288 // Unzoom and close the panel, zoom the active pane.
9289 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
9290 workspace.update_in(cx, |workspace, window, cx| {
9291 workspace.toggle_dock(DockPosition::Right, window, cx)
9292 });
9293 pane.update_in(cx, |pane, window, cx| {
9294 pane.toggle_zoom(&Default::default(), window, cx)
9295 });
9296
9297 // Opening a dock unzooms the pane.
9298 workspace.update_in(cx, |workspace, window, cx| {
9299 workspace.toggle_dock(DockPosition::Right, window, cx)
9300 });
9301 workspace.update_in(cx, |workspace, window, cx| {
9302 let pane = pane.read(cx);
9303 assert!(!pane.is_zoomed());
9304 assert!(!pane.focus_handle(cx).is_focused(window));
9305 assert!(workspace.right_dock().read(cx).is_open());
9306 assert!(workspace.zoomed.is_none());
9307 });
9308 }
9309
9310 #[gpui::test]
9311 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
9312 init_test(cx);
9313 let fs = FakeFs::new(cx.executor());
9314
9315 let project = Project::test(fs, [], cx).await;
9316 let (workspace, cx) =
9317 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9318 workspace.update_in(cx, |workspace, window, cx| {
9319 // Open two docks
9320 let left_dock = workspace.dock_at_position(DockPosition::Left);
9321 let right_dock = workspace.dock_at_position(DockPosition::Right);
9322
9323 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
9324 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
9325
9326 assert!(left_dock.read(cx).is_open());
9327 assert!(right_dock.read(cx).is_open());
9328 });
9329
9330 workspace.update_in(cx, |workspace, window, cx| {
9331 // Toggle all docks - should close both
9332 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
9333
9334 let left_dock = workspace.dock_at_position(DockPosition::Left);
9335 let right_dock = workspace.dock_at_position(DockPosition::Right);
9336 assert!(!left_dock.read(cx).is_open());
9337 assert!(!right_dock.read(cx).is_open());
9338 });
9339
9340 workspace.update_in(cx, |workspace, window, cx| {
9341 // Toggle again - should reopen both
9342 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
9343
9344 let left_dock = workspace.dock_at_position(DockPosition::Left);
9345 let right_dock = workspace.dock_at_position(DockPosition::Right);
9346 assert!(left_dock.read(cx).is_open());
9347 assert!(right_dock.read(cx).is_open());
9348 });
9349 }
9350
9351 #[gpui::test]
9352 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
9353 init_test(cx);
9354 let fs = FakeFs::new(cx.executor());
9355
9356 let project = Project::test(fs, [], cx).await;
9357 let (workspace, cx) =
9358 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9359 workspace.update_in(cx, |workspace, window, cx| {
9360 // Open two docks
9361 let left_dock = workspace.dock_at_position(DockPosition::Left);
9362 let right_dock = workspace.dock_at_position(DockPosition::Right);
9363
9364 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
9365 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
9366
9367 assert!(left_dock.read(cx).is_open());
9368 assert!(right_dock.read(cx).is_open());
9369 });
9370
9371 workspace.update_in(cx, |workspace, window, cx| {
9372 // Close them manually
9373 workspace.toggle_dock(DockPosition::Left, window, cx);
9374 workspace.toggle_dock(DockPosition::Right, window, cx);
9375
9376 let left_dock = workspace.dock_at_position(DockPosition::Left);
9377 let right_dock = workspace.dock_at_position(DockPosition::Right);
9378 assert!(!left_dock.read(cx).is_open());
9379 assert!(!right_dock.read(cx).is_open());
9380 });
9381
9382 workspace.update_in(cx, |workspace, window, cx| {
9383 // Toggle all docks - only last closed (right dock) should reopen
9384 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
9385
9386 let left_dock = workspace.dock_at_position(DockPosition::Left);
9387 let right_dock = workspace.dock_at_position(DockPosition::Right);
9388 assert!(!left_dock.read(cx).is_open());
9389 assert!(right_dock.read(cx).is_open());
9390 });
9391 }
9392
9393 #[gpui::test]
9394 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
9395 init_test(cx);
9396 let fs = FakeFs::new(cx.executor());
9397 let project = Project::test(fs, [], cx).await;
9398 let (workspace, cx) =
9399 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9400
9401 // Open two docks (left and right) with one panel each
9402 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
9403 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, cx));
9404 workspace.add_panel(left_panel.clone(), window, cx);
9405
9406 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
9407 workspace.add_panel(right_panel.clone(), window, cx);
9408
9409 workspace.toggle_dock(DockPosition::Left, window, cx);
9410 workspace.toggle_dock(DockPosition::Right, window, cx);
9411
9412 // Verify initial state
9413 assert!(
9414 workspace.left_dock().read(cx).is_open(),
9415 "Left dock should be open"
9416 );
9417 assert_eq!(
9418 workspace
9419 .left_dock()
9420 .read(cx)
9421 .visible_panel()
9422 .unwrap()
9423 .panel_id(),
9424 left_panel.panel_id(),
9425 "Left panel should be visible in left dock"
9426 );
9427 assert!(
9428 workspace.right_dock().read(cx).is_open(),
9429 "Right dock should be open"
9430 );
9431 assert_eq!(
9432 workspace
9433 .right_dock()
9434 .read(cx)
9435 .visible_panel()
9436 .unwrap()
9437 .panel_id(),
9438 right_panel.panel_id(),
9439 "Right panel should be visible in right dock"
9440 );
9441 assert!(
9442 !workspace.bottom_dock().read(cx).is_open(),
9443 "Bottom dock should be closed"
9444 );
9445
9446 (left_panel, right_panel)
9447 });
9448
9449 // Focus the left panel and move it to the next position (bottom dock)
9450 workspace.update_in(cx, |workspace, window, cx| {
9451 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
9452 assert!(
9453 left_panel.read(cx).focus_handle(cx).is_focused(window),
9454 "Left panel should be focused"
9455 );
9456 });
9457
9458 cx.dispatch_action(MoveFocusedPanelToNextPosition);
9459
9460 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
9461 workspace.update(cx, |workspace, cx| {
9462 assert!(
9463 !workspace.left_dock().read(cx).is_open(),
9464 "Left dock should be closed"
9465 );
9466 assert!(
9467 workspace.bottom_dock().read(cx).is_open(),
9468 "Bottom dock should now be open"
9469 );
9470 assert_eq!(
9471 left_panel.read(cx).position,
9472 DockPosition::Bottom,
9473 "Left panel should now be in the bottom dock"
9474 );
9475 assert_eq!(
9476 workspace
9477 .bottom_dock()
9478 .read(cx)
9479 .visible_panel()
9480 .unwrap()
9481 .panel_id(),
9482 left_panel.panel_id(),
9483 "Left panel should be the visible panel in the bottom dock"
9484 );
9485 });
9486
9487 // Toggle all docks off
9488 workspace.update_in(cx, |workspace, window, cx| {
9489 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
9490 assert!(
9491 !workspace.left_dock().read(cx).is_open(),
9492 "Left dock should be closed"
9493 );
9494 assert!(
9495 !workspace.right_dock().read(cx).is_open(),
9496 "Right dock should be closed"
9497 );
9498 assert!(
9499 !workspace.bottom_dock().read(cx).is_open(),
9500 "Bottom dock should be closed"
9501 );
9502 });
9503
9504 // Toggle all docks back on and verify positions are restored
9505 workspace.update_in(cx, |workspace, window, cx| {
9506 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
9507 assert!(
9508 !workspace.left_dock().read(cx).is_open(),
9509 "Left dock should remain closed"
9510 );
9511 assert!(
9512 workspace.right_dock().read(cx).is_open(),
9513 "Right dock should remain open"
9514 );
9515 assert!(
9516 workspace.bottom_dock().read(cx).is_open(),
9517 "Bottom dock should remain open"
9518 );
9519 assert_eq!(
9520 left_panel.read(cx).position,
9521 DockPosition::Bottom,
9522 "Left panel should remain in the bottom dock"
9523 );
9524 assert_eq!(
9525 right_panel.read(cx).position,
9526 DockPosition::Right,
9527 "Right panel should remain in the right dock"
9528 );
9529 assert_eq!(
9530 workspace
9531 .bottom_dock()
9532 .read(cx)
9533 .visible_panel()
9534 .unwrap()
9535 .panel_id(),
9536 left_panel.panel_id(),
9537 "Left panel should be the visible panel in the right dock"
9538 );
9539 });
9540 }
9541
9542 #[gpui::test]
9543 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
9544 init_test(cx);
9545
9546 let fs = FakeFs::new(cx.executor());
9547
9548 let project = Project::test(fs, None, cx).await;
9549 let (workspace, cx) =
9550 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9551
9552 // Let's arrange the panes like this:
9553 //
9554 // +-----------------------+
9555 // | top |
9556 // +------+--------+-------+
9557 // | left | center | right |
9558 // +------+--------+-------+
9559 // | bottom |
9560 // +-----------------------+
9561
9562 let top_item = cx.new(|cx| {
9563 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
9564 });
9565 let bottom_item = cx.new(|cx| {
9566 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
9567 });
9568 let left_item = cx.new(|cx| {
9569 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
9570 });
9571 let right_item = cx.new(|cx| {
9572 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
9573 });
9574 let center_item = cx.new(|cx| {
9575 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
9576 });
9577
9578 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
9579 let top_pane_id = workspace.active_pane().entity_id();
9580 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
9581 workspace.split_pane(
9582 workspace.active_pane().clone(),
9583 SplitDirection::Down,
9584 window,
9585 cx,
9586 );
9587 top_pane_id
9588 });
9589 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
9590 let bottom_pane_id = workspace.active_pane().entity_id();
9591 workspace.add_item_to_active_pane(
9592 Box::new(bottom_item.clone()),
9593 None,
9594 false,
9595 window,
9596 cx,
9597 );
9598 workspace.split_pane(
9599 workspace.active_pane().clone(),
9600 SplitDirection::Up,
9601 window,
9602 cx,
9603 );
9604 bottom_pane_id
9605 });
9606 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
9607 let left_pane_id = workspace.active_pane().entity_id();
9608 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
9609 workspace.split_pane(
9610 workspace.active_pane().clone(),
9611 SplitDirection::Right,
9612 window,
9613 cx,
9614 );
9615 left_pane_id
9616 });
9617 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
9618 let right_pane_id = workspace.active_pane().entity_id();
9619 workspace.add_item_to_active_pane(
9620 Box::new(right_item.clone()),
9621 None,
9622 false,
9623 window,
9624 cx,
9625 );
9626 workspace.split_pane(
9627 workspace.active_pane().clone(),
9628 SplitDirection::Left,
9629 window,
9630 cx,
9631 );
9632 right_pane_id
9633 });
9634 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
9635 let center_pane_id = workspace.active_pane().entity_id();
9636 workspace.add_item_to_active_pane(
9637 Box::new(center_item.clone()),
9638 None,
9639 false,
9640 window,
9641 cx,
9642 );
9643 center_pane_id
9644 });
9645 cx.executor().run_until_parked();
9646
9647 workspace.update_in(cx, |workspace, window, cx| {
9648 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
9649
9650 // Join into next from center pane into right
9651 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
9652 });
9653
9654 workspace.update_in(cx, |workspace, window, cx| {
9655 let active_pane = workspace.active_pane();
9656 assert_eq!(right_pane_id, active_pane.entity_id());
9657 assert_eq!(2, active_pane.read(cx).items_len());
9658 let item_ids_in_pane =
9659 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
9660 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
9661 assert!(item_ids_in_pane.contains(&right_item.item_id()));
9662
9663 // Join into next from right pane into bottom
9664 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
9665 });
9666
9667 workspace.update_in(cx, |workspace, window, cx| {
9668 let active_pane = workspace.active_pane();
9669 assert_eq!(bottom_pane_id, active_pane.entity_id());
9670 assert_eq!(3, active_pane.read(cx).items_len());
9671 let item_ids_in_pane =
9672 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
9673 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
9674 assert!(item_ids_in_pane.contains(&right_item.item_id()));
9675 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
9676
9677 // Join into next from bottom pane into left
9678 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
9679 });
9680
9681 workspace.update_in(cx, |workspace, window, cx| {
9682 let active_pane = workspace.active_pane();
9683 assert_eq!(left_pane_id, active_pane.entity_id());
9684 assert_eq!(4, active_pane.read(cx).items_len());
9685 let item_ids_in_pane =
9686 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
9687 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
9688 assert!(item_ids_in_pane.contains(&right_item.item_id()));
9689 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
9690 assert!(item_ids_in_pane.contains(&left_item.item_id()));
9691
9692 // Join into next from left pane into top
9693 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
9694 });
9695
9696 workspace.update_in(cx, |workspace, window, cx| {
9697 let active_pane = workspace.active_pane();
9698 assert_eq!(top_pane_id, active_pane.entity_id());
9699 assert_eq!(5, active_pane.read(cx).items_len());
9700 let item_ids_in_pane =
9701 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
9702 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
9703 assert!(item_ids_in_pane.contains(&right_item.item_id()));
9704 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
9705 assert!(item_ids_in_pane.contains(&left_item.item_id()));
9706 assert!(item_ids_in_pane.contains(&top_item.item_id()));
9707
9708 // Single pane left: no-op
9709 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
9710 });
9711
9712 workspace.update(cx, |workspace, _cx| {
9713 let active_pane = workspace.active_pane();
9714 assert_eq!(top_pane_id, active_pane.entity_id());
9715 });
9716 }
9717
9718 fn add_an_item_to_active_pane(
9719 cx: &mut VisualTestContext,
9720 workspace: &Entity<Workspace>,
9721 item_id: u64,
9722 ) -> Entity<TestItem> {
9723 let item = cx.new(|cx| {
9724 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
9725 item_id,
9726 "item{item_id}.txt",
9727 cx,
9728 )])
9729 });
9730 workspace.update_in(cx, |workspace, window, cx| {
9731 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
9732 });
9733 item
9734 }
9735
9736 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
9737 workspace.update_in(cx, |workspace, window, cx| {
9738 workspace.split_pane(
9739 workspace.active_pane().clone(),
9740 SplitDirection::Right,
9741 window,
9742 cx,
9743 )
9744 })
9745 }
9746
9747 #[gpui::test]
9748 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
9749 init_test(cx);
9750 let fs = FakeFs::new(cx.executor());
9751 let project = Project::test(fs, None, cx).await;
9752 let (workspace, cx) =
9753 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9754
9755 add_an_item_to_active_pane(cx, &workspace, 1);
9756 split_pane(cx, &workspace);
9757 add_an_item_to_active_pane(cx, &workspace, 2);
9758 split_pane(cx, &workspace); // empty pane
9759 split_pane(cx, &workspace);
9760 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
9761
9762 cx.executor().run_until_parked();
9763
9764 workspace.update(cx, |workspace, cx| {
9765 let num_panes = workspace.panes().len();
9766 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
9767 let active_item = workspace
9768 .active_pane()
9769 .read(cx)
9770 .active_item()
9771 .expect("item is in focus");
9772
9773 assert_eq!(num_panes, 4);
9774 assert_eq!(num_items_in_current_pane, 1);
9775 assert_eq!(active_item.item_id(), last_item.item_id());
9776 });
9777
9778 workspace.update_in(cx, |workspace, window, cx| {
9779 workspace.join_all_panes(window, cx);
9780 });
9781
9782 workspace.update(cx, |workspace, cx| {
9783 let num_panes = workspace.panes().len();
9784 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
9785 let active_item = workspace
9786 .active_pane()
9787 .read(cx)
9788 .active_item()
9789 .expect("item is in focus");
9790
9791 assert_eq!(num_panes, 1);
9792 assert_eq!(num_items_in_current_pane, 3);
9793 assert_eq!(active_item.item_id(), last_item.item_id());
9794 });
9795 }
9796 struct TestModal(FocusHandle);
9797
9798 impl TestModal {
9799 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
9800 Self(cx.focus_handle())
9801 }
9802 }
9803
9804 impl EventEmitter<DismissEvent> for TestModal {}
9805
9806 impl Focusable for TestModal {
9807 fn focus_handle(&self, _cx: &App) -> FocusHandle {
9808 self.0.clone()
9809 }
9810 }
9811
9812 impl ModalView for TestModal {}
9813
9814 impl Render for TestModal {
9815 fn render(
9816 &mut self,
9817 _window: &mut Window,
9818 _cx: &mut Context<TestModal>,
9819 ) -> impl IntoElement {
9820 div().track_focus(&self.0)
9821 }
9822 }
9823
9824 #[gpui::test]
9825 async fn test_panels(cx: &mut gpui::TestAppContext) {
9826 init_test(cx);
9827 let fs = FakeFs::new(cx.executor());
9828
9829 let project = Project::test(fs, [], cx).await;
9830 let (workspace, cx) =
9831 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9832
9833 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
9834 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, cx));
9835 workspace.add_panel(panel_1.clone(), window, cx);
9836 workspace.toggle_dock(DockPosition::Left, window, cx);
9837 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
9838 workspace.add_panel(panel_2.clone(), window, cx);
9839 workspace.toggle_dock(DockPosition::Right, window, cx);
9840
9841 let left_dock = workspace.left_dock();
9842 assert_eq!(
9843 left_dock.read(cx).visible_panel().unwrap().panel_id(),
9844 panel_1.panel_id()
9845 );
9846 assert_eq!(
9847 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
9848 panel_1.size(window, cx)
9849 );
9850
9851 left_dock.update(cx, |left_dock, cx| {
9852 left_dock.resize_active_panel(Some(px(1337.)), window, cx)
9853 });
9854 assert_eq!(
9855 workspace
9856 .right_dock()
9857 .read(cx)
9858 .visible_panel()
9859 .unwrap()
9860 .panel_id(),
9861 panel_2.panel_id(),
9862 );
9863
9864 (panel_1, panel_2)
9865 });
9866
9867 // Move panel_1 to the right
9868 panel_1.update_in(cx, |panel_1, window, cx| {
9869 panel_1.set_position(DockPosition::Right, window, cx)
9870 });
9871
9872 workspace.update_in(cx, |workspace, window, cx| {
9873 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
9874 // Since it was the only panel on the left, the left dock should now be closed.
9875 assert!(!workspace.left_dock().read(cx).is_open());
9876 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
9877 let right_dock = workspace.right_dock();
9878 assert_eq!(
9879 right_dock.read(cx).visible_panel().unwrap().panel_id(),
9880 panel_1.panel_id()
9881 );
9882 assert_eq!(
9883 right_dock.read(cx).active_panel_size(window, cx).unwrap(),
9884 px(1337.)
9885 );
9886
9887 // Now we move panel_2 to the left
9888 panel_2.set_position(DockPosition::Left, window, cx);
9889 });
9890
9891 workspace.update(cx, |workspace, cx| {
9892 // Since panel_2 was not visible on the right, we don't open the left dock.
9893 assert!(!workspace.left_dock().read(cx).is_open());
9894 // And the right dock is unaffected in its displaying of panel_1
9895 assert!(workspace.right_dock().read(cx).is_open());
9896 assert_eq!(
9897 workspace
9898 .right_dock()
9899 .read(cx)
9900 .visible_panel()
9901 .unwrap()
9902 .panel_id(),
9903 panel_1.panel_id(),
9904 );
9905 });
9906
9907 // Move panel_1 back to the left
9908 panel_1.update_in(cx, |panel_1, window, cx| {
9909 panel_1.set_position(DockPosition::Left, window, cx)
9910 });
9911
9912 workspace.update_in(cx, |workspace, window, cx| {
9913 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
9914 let left_dock = workspace.left_dock();
9915 assert!(left_dock.read(cx).is_open());
9916 assert_eq!(
9917 left_dock.read(cx).visible_panel().unwrap().panel_id(),
9918 panel_1.panel_id()
9919 );
9920 assert_eq!(
9921 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
9922 px(1337.)
9923 );
9924 // And the right dock should be closed as it no longer has any panels.
9925 assert!(!workspace.right_dock().read(cx).is_open());
9926
9927 // Now we move panel_1 to the bottom
9928 panel_1.set_position(DockPosition::Bottom, window, cx);
9929 });
9930
9931 workspace.update_in(cx, |workspace, window, cx| {
9932 // Since panel_1 was visible on the left, we close the left dock.
9933 assert!(!workspace.left_dock().read(cx).is_open());
9934 // The bottom dock is sized based on the panel's default size,
9935 // since the panel orientation changed from vertical to horizontal.
9936 let bottom_dock = workspace.bottom_dock();
9937 assert_eq!(
9938 bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
9939 panel_1.size(window, cx),
9940 );
9941 // Close bottom dock and move panel_1 back to the left.
9942 bottom_dock.update(cx, |bottom_dock, cx| {
9943 bottom_dock.set_open(false, window, cx)
9944 });
9945 panel_1.set_position(DockPosition::Left, window, cx);
9946 });
9947
9948 // Emit activated event on panel 1
9949 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
9950
9951 // Now the left dock is open and panel_1 is active and focused.
9952 workspace.update_in(cx, |workspace, window, cx| {
9953 let left_dock = workspace.left_dock();
9954 assert!(left_dock.read(cx).is_open());
9955 assert_eq!(
9956 left_dock.read(cx).visible_panel().unwrap().panel_id(),
9957 panel_1.panel_id(),
9958 );
9959 assert!(panel_1.focus_handle(cx).is_focused(window));
9960 });
9961
9962 // Emit closed event on panel 2, which is not active
9963 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
9964
9965 // Wo don't close the left dock, because panel_2 wasn't the active panel
9966 workspace.update(cx, |workspace, cx| {
9967 let left_dock = workspace.left_dock();
9968 assert!(left_dock.read(cx).is_open());
9969 assert_eq!(
9970 left_dock.read(cx).visible_panel().unwrap().panel_id(),
9971 panel_1.panel_id(),
9972 );
9973 });
9974
9975 // Emitting a ZoomIn event shows the panel as zoomed.
9976 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
9977 workspace.read_with(cx, |workspace, _| {
9978 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
9979 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
9980 });
9981
9982 // Move panel to another dock while it is zoomed
9983 panel_1.update_in(cx, |panel, window, cx| {
9984 panel.set_position(DockPosition::Right, window, cx)
9985 });
9986 workspace.read_with(cx, |workspace, _| {
9987 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
9988
9989 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
9990 });
9991
9992 // This is a helper for getting a:
9993 // - valid focus on an element,
9994 // - that isn't a part of the panes and panels system of the Workspace,
9995 // - and doesn't trigger the 'on_focus_lost' API.
9996 let focus_other_view = {
9997 let workspace = workspace.clone();
9998 move |cx: &mut VisualTestContext| {
9999 workspace.update_in(cx, |workspace, window, cx| {
10000 if workspace.active_modal::<TestModal>(cx).is_some() {
10001 workspace.toggle_modal(window, cx, TestModal::new);
10002 workspace.toggle_modal(window, cx, TestModal::new);
10003 } else {
10004 workspace.toggle_modal(window, cx, TestModal::new);
10005 }
10006 })
10007 }
10008 };
10009
10010 // If focus is transferred to another view that's not a panel or another pane, we still show
10011 // the panel as zoomed.
10012 focus_other_view(cx);
10013 workspace.read_with(cx, |workspace, _| {
10014 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10015 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
10016 });
10017
10018 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
10019 workspace.update_in(cx, |_workspace, window, cx| {
10020 cx.focus_self(window);
10021 });
10022 workspace.read_with(cx, |workspace, _| {
10023 assert_eq!(workspace.zoomed, None);
10024 assert_eq!(workspace.zoomed_position, None);
10025 });
10026
10027 // If focus is transferred again to another view that's not a panel or a pane, we won't
10028 // show the panel as zoomed because it wasn't zoomed before.
10029 focus_other_view(cx);
10030 workspace.read_with(cx, |workspace, _| {
10031 assert_eq!(workspace.zoomed, None);
10032 assert_eq!(workspace.zoomed_position, None);
10033 });
10034
10035 // When the panel is activated, it is zoomed again.
10036 cx.dispatch_action(ToggleRightDock);
10037 workspace.read_with(cx, |workspace, _| {
10038 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10039 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
10040 });
10041
10042 // Emitting a ZoomOut event unzooms the panel.
10043 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
10044 workspace.read_with(cx, |workspace, _| {
10045 assert_eq!(workspace.zoomed, None);
10046 assert_eq!(workspace.zoomed_position, None);
10047 });
10048
10049 // Emit closed event on panel 1, which is active
10050 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
10051
10052 // Now the left dock is closed, because panel_1 was the active panel
10053 workspace.update(cx, |workspace, cx| {
10054 let right_dock = workspace.right_dock();
10055 assert!(!right_dock.read(cx).is_open());
10056 });
10057 }
10058
10059 #[gpui::test]
10060 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
10061 init_test(cx);
10062
10063 let fs = FakeFs::new(cx.background_executor.clone());
10064 let project = Project::test(fs, [], cx).await;
10065 let (workspace, cx) =
10066 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10067 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10068
10069 let dirty_regular_buffer = cx.new(|cx| {
10070 TestItem::new(cx)
10071 .with_dirty(true)
10072 .with_label("1.txt")
10073 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10074 });
10075 let dirty_regular_buffer_2 = cx.new(|cx| {
10076 TestItem::new(cx)
10077 .with_dirty(true)
10078 .with_label("2.txt")
10079 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10080 });
10081 let dirty_multi_buffer_with_both = cx.new(|cx| {
10082 TestItem::new(cx)
10083 .with_dirty(true)
10084 .with_buffer_kind(ItemBufferKind::Multibuffer)
10085 .with_label("Fake Project Search")
10086 .with_project_items(&[
10087 dirty_regular_buffer.read(cx).project_items[0].clone(),
10088 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
10089 ])
10090 });
10091 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
10092 workspace.update_in(cx, |workspace, window, cx| {
10093 workspace.add_item(
10094 pane.clone(),
10095 Box::new(dirty_regular_buffer.clone()),
10096 None,
10097 false,
10098 false,
10099 window,
10100 cx,
10101 );
10102 workspace.add_item(
10103 pane.clone(),
10104 Box::new(dirty_regular_buffer_2.clone()),
10105 None,
10106 false,
10107 false,
10108 window,
10109 cx,
10110 );
10111 workspace.add_item(
10112 pane.clone(),
10113 Box::new(dirty_multi_buffer_with_both.clone()),
10114 None,
10115 false,
10116 false,
10117 window,
10118 cx,
10119 );
10120 });
10121
10122 pane.update_in(cx, |pane, window, cx| {
10123 pane.activate_item(2, true, true, window, cx);
10124 assert_eq!(
10125 pane.active_item().unwrap().item_id(),
10126 multi_buffer_with_both_files_id,
10127 "Should select the multi buffer in the pane"
10128 );
10129 });
10130 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10131 pane.close_other_items(
10132 &CloseOtherItems {
10133 save_intent: Some(SaveIntent::Save),
10134 close_pinned: true,
10135 },
10136 None,
10137 window,
10138 cx,
10139 )
10140 });
10141 cx.background_executor.run_until_parked();
10142 assert!(!cx.has_pending_prompt());
10143 close_all_but_multi_buffer_task
10144 .await
10145 .expect("Closing all buffers but the multi buffer failed");
10146 pane.update(cx, |pane, cx| {
10147 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
10148 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
10149 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
10150 assert_eq!(pane.items_len(), 1);
10151 assert_eq!(
10152 pane.active_item().unwrap().item_id(),
10153 multi_buffer_with_both_files_id,
10154 "Should have only the multi buffer left in the pane"
10155 );
10156 assert!(
10157 dirty_multi_buffer_with_both.read(cx).is_dirty,
10158 "The multi buffer containing the unsaved buffer should still be dirty"
10159 );
10160 });
10161
10162 dirty_regular_buffer.update(cx, |buffer, cx| {
10163 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
10164 });
10165
10166 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10167 pane.close_active_item(
10168 &CloseActiveItem {
10169 save_intent: Some(SaveIntent::Close),
10170 close_pinned: false,
10171 },
10172 window,
10173 cx,
10174 )
10175 });
10176 cx.background_executor.run_until_parked();
10177 assert!(
10178 cx.has_pending_prompt(),
10179 "Dirty multi buffer should prompt a save dialog"
10180 );
10181 cx.simulate_prompt_answer("Save");
10182 cx.background_executor.run_until_parked();
10183 close_multi_buffer_task
10184 .await
10185 .expect("Closing the multi buffer failed");
10186 pane.update(cx, |pane, cx| {
10187 assert_eq!(
10188 dirty_multi_buffer_with_both.read(cx).save_count,
10189 1,
10190 "Multi buffer item should get be saved"
10191 );
10192 // Test impl does not save inner items, so we do not assert them
10193 assert_eq!(
10194 pane.items_len(),
10195 0,
10196 "No more items should be left in the pane"
10197 );
10198 assert!(pane.active_item().is_none());
10199 });
10200 }
10201
10202 #[gpui::test]
10203 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
10204 cx: &mut TestAppContext,
10205 ) {
10206 init_test(cx);
10207
10208 let fs = FakeFs::new(cx.background_executor.clone());
10209 let project = Project::test(fs, [], cx).await;
10210 let (workspace, cx) =
10211 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10212 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10213
10214 let dirty_regular_buffer = cx.new(|cx| {
10215 TestItem::new(cx)
10216 .with_dirty(true)
10217 .with_label("1.txt")
10218 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10219 });
10220 let dirty_regular_buffer_2 = cx.new(|cx| {
10221 TestItem::new(cx)
10222 .with_dirty(true)
10223 .with_label("2.txt")
10224 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10225 });
10226 let clear_regular_buffer = cx.new(|cx| {
10227 TestItem::new(cx)
10228 .with_label("3.txt")
10229 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
10230 });
10231
10232 let dirty_multi_buffer_with_both = cx.new(|cx| {
10233 TestItem::new(cx)
10234 .with_dirty(true)
10235 .with_buffer_kind(ItemBufferKind::Multibuffer)
10236 .with_label("Fake Project Search")
10237 .with_project_items(&[
10238 dirty_regular_buffer.read(cx).project_items[0].clone(),
10239 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
10240 clear_regular_buffer.read(cx).project_items[0].clone(),
10241 ])
10242 });
10243 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
10244 workspace.update_in(cx, |workspace, window, cx| {
10245 workspace.add_item(
10246 pane.clone(),
10247 Box::new(dirty_regular_buffer.clone()),
10248 None,
10249 false,
10250 false,
10251 window,
10252 cx,
10253 );
10254 workspace.add_item(
10255 pane.clone(),
10256 Box::new(dirty_multi_buffer_with_both.clone()),
10257 None,
10258 false,
10259 false,
10260 window,
10261 cx,
10262 );
10263 });
10264
10265 pane.update_in(cx, |pane, window, cx| {
10266 pane.activate_item(1, true, true, window, cx);
10267 assert_eq!(
10268 pane.active_item().unwrap().item_id(),
10269 multi_buffer_with_both_files_id,
10270 "Should select the multi buffer in the pane"
10271 );
10272 });
10273 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10274 pane.close_active_item(
10275 &CloseActiveItem {
10276 save_intent: None,
10277 close_pinned: false,
10278 },
10279 window,
10280 cx,
10281 )
10282 });
10283 cx.background_executor.run_until_parked();
10284 assert!(
10285 cx.has_pending_prompt(),
10286 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
10287 );
10288 }
10289
10290 /// Tests that when `close_on_file_delete` is enabled, files are automatically
10291 /// closed when they are deleted from disk.
10292 #[gpui::test]
10293 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
10294 init_test(cx);
10295
10296 // Enable the close_on_disk_deletion setting
10297 cx.update_global(|store: &mut SettingsStore, cx| {
10298 store.update_user_settings(cx, |settings| {
10299 settings.workspace.close_on_file_delete = Some(true);
10300 });
10301 });
10302
10303 let fs = FakeFs::new(cx.background_executor.clone());
10304 let project = Project::test(fs, [], cx).await;
10305 let (workspace, cx) =
10306 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10307 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10308
10309 // Create a test item that simulates a file
10310 let item = cx.new(|cx| {
10311 TestItem::new(cx)
10312 .with_label("test.txt")
10313 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
10314 });
10315
10316 // Add item to workspace
10317 workspace.update_in(cx, |workspace, window, cx| {
10318 workspace.add_item(
10319 pane.clone(),
10320 Box::new(item.clone()),
10321 None,
10322 false,
10323 false,
10324 window,
10325 cx,
10326 );
10327 });
10328
10329 // Verify the item is in the pane
10330 pane.read_with(cx, |pane, _| {
10331 assert_eq!(pane.items().count(), 1);
10332 });
10333
10334 // Simulate file deletion by setting the item's deleted state
10335 item.update(cx, |item, _| {
10336 item.set_has_deleted_file(true);
10337 });
10338
10339 // Emit UpdateTab event to trigger the close behavior
10340 cx.run_until_parked();
10341 item.update(cx, |_, cx| {
10342 cx.emit(ItemEvent::UpdateTab);
10343 });
10344
10345 // Allow the close operation to complete
10346 cx.run_until_parked();
10347
10348 // Verify the item was automatically closed
10349 pane.read_with(cx, |pane, _| {
10350 assert_eq!(
10351 pane.items().count(),
10352 0,
10353 "Item should be automatically closed when file is deleted"
10354 );
10355 });
10356 }
10357
10358 /// Tests that when `close_on_file_delete` is disabled (default), files remain
10359 /// open with a strikethrough when they are deleted from disk.
10360 #[gpui::test]
10361 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
10362 init_test(cx);
10363
10364 // Ensure close_on_disk_deletion is disabled (default)
10365 cx.update_global(|store: &mut SettingsStore, cx| {
10366 store.update_user_settings(cx, |settings| {
10367 settings.workspace.close_on_file_delete = Some(false);
10368 });
10369 });
10370
10371 let fs = FakeFs::new(cx.background_executor.clone());
10372 let project = Project::test(fs, [], cx).await;
10373 let (workspace, cx) =
10374 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10375 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10376
10377 // Create a test item that simulates a file
10378 let item = cx.new(|cx| {
10379 TestItem::new(cx)
10380 .with_label("test.txt")
10381 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
10382 });
10383
10384 // Add item to workspace
10385 workspace.update_in(cx, |workspace, window, cx| {
10386 workspace.add_item(
10387 pane.clone(),
10388 Box::new(item.clone()),
10389 None,
10390 false,
10391 false,
10392 window,
10393 cx,
10394 );
10395 });
10396
10397 // Verify the item is in the pane
10398 pane.read_with(cx, |pane, _| {
10399 assert_eq!(pane.items().count(), 1);
10400 });
10401
10402 // Simulate file deletion
10403 item.update(cx, |item, _| {
10404 item.set_has_deleted_file(true);
10405 });
10406
10407 // Emit UpdateTab event
10408 cx.run_until_parked();
10409 item.update(cx, |_, cx| {
10410 cx.emit(ItemEvent::UpdateTab);
10411 });
10412
10413 // Allow any potential close operation to complete
10414 cx.run_until_parked();
10415
10416 // Verify the item remains open (with strikethrough)
10417 pane.read_with(cx, |pane, _| {
10418 assert_eq!(
10419 pane.items().count(),
10420 1,
10421 "Item should remain open when close_on_disk_deletion is disabled"
10422 );
10423 });
10424
10425 // Verify the item shows as deleted
10426 item.read_with(cx, |item, _| {
10427 assert!(
10428 item.has_deleted_file,
10429 "Item should be marked as having deleted file"
10430 );
10431 });
10432 }
10433
10434 /// Tests that dirty files are not automatically closed when deleted from disk,
10435 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
10436 /// unsaved changes without being prompted.
10437 #[gpui::test]
10438 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
10439 init_test(cx);
10440
10441 // Enable the close_on_file_delete setting
10442 cx.update_global(|store: &mut SettingsStore, cx| {
10443 store.update_user_settings(cx, |settings| {
10444 settings.workspace.close_on_file_delete = Some(true);
10445 });
10446 });
10447
10448 let fs = FakeFs::new(cx.background_executor.clone());
10449 let project = Project::test(fs, [], cx).await;
10450 let (workspace, cx) =
10451 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10452 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10453
10454 // Create a dirty test item
10455 let item = cx.new(|cx| {
10456 TestItem::new(cx)
10457 .with_dirty(true)
10458 .with_label("test.txt")
10459 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
10460 });
10461
10462 // Add item to workspace
10463 workspace.update_in(cx, |workspace, window, cx| {
10464 workspace.add_item(
10465 pane.clone(),
10466 Box::new(item.clone()),
10467 None,
10468 false,
10469 false,
10470 window,
10471 cx,
10472 );
10473 });
10474
10475 // Simulate file deletion
10476 item.update(cx, |item, _| {
10477 item.set_has_deleted_file(true);
10478 });
10479
10480 // Emit UpdateTab event to trigger the close behavior
10481 cx.run_until_parked();
10482 item.update(cx, |_, cx| {
10483 cx.emit(ItemEvent::UpdateTab);
10484 });
10485
10486 // Allow any potential close operation to complete
10487 cx.run_until_parked();
10488
10489 // Verify the item remains open (dirty files are not auto-closed)
10490 pane.read_with(cx, |pane, _| {
10491 assert_eq!(
10492 pane.items().count(),
10493 1,
10494 "Dirty items should not be automatically closed even when file is deleted"
10495 );
10496 });
10497
10498 // Verify the item is marked as deleted and still dirty
10499 item.read_with(cx, |item, _| {
10500 assert!(
10501 item.has_deleted_file,
10502 "Item should be marked as having deleted file"
10503 );
10504 assert!(item.is_dirty, "Item should still be dirty");
10505 });
10506 }
10507
10508 /// Tests that navigation history is cleaned up when files are auto-closed
10509 /// due to deletion from disk.
10510 #[gpui::test]
10511 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
10512 init_test(cx);
10513
10514 // Enable the close_on_file_delete setting
10515 cx.update_global(|store: &mut SettingsStore, cx| {
10516 store.update_user_settings(cx, |settings| {
10517 settings.workspace.close_on_file_delete = Some(true);
10518 });
10519 });
10520
10521 let fs = FakeFs::new(cx.background_executor.clone());
10522 let project = Project::test(fs, [], cx).await;
10523 let (workspace, cx) =
10524 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10525 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10526
10527 // Create test items
10528 let item1 = cx.new(|cx| {
10529 TestItem::new(cx)
10530 .with_label("test1.txt")
10531 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
10532 });
10533 let item1_id = item1.item_id();
10534
10535 let item2 = cx.new(|cx| {
10536 TestItem::new(cx)
10537 .with_label("test2.txt")
10538 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
10539 });
10540
10541 // Add items to workspace
10542 workspace.update_in(cx, |workspace, window, cx| {
10543 workspace.add_item(
10544 pane.clone(),
10545 Box::new(item1.clone()),
10546 None,
10547 false,
10548 false,
10549 window,
10550 cx,
10551 );
10552 workspace.add_item(
10553 pane.clone(),
10554 Box::new(item2.clone()),
10555 None,
10556 false,
10557 false,
10558 window,
10559 cx,
10560 );
10561 });
10562
10563 // Activate item1 to ensure it gets navigation entries
10564 pane.update_in(cx, |pane, window, cx| {
10565 pane.activate_item(0, true, true, window, cx);
10566 });
10567
10568 // Switch to item2 and back to create navigation history
10569 pane.update_in(cx, |pane, window, cx| {
10570 pane.activate_item(1, true, true, window, cx);
10571 });
10572 cx.run_until_parked();
10573
10574 pane.update_in(cx, |pane, window, cx| {
10575 pane.activate_item(0, true, true, window, cx);
10576 });
10577 cx.run_until_parked();
10578
10579 // Simulate file deletion for item1
10580 item1.update(cx, |item, _| {
10581 item.set_has_deleted_file(true);
10582 });
10583
10584 // Emit UpdateTab event to trigger the close behavior
10585 item1.update(cx, |_, cx| {
10586 cx.emit(ItemEvent::UpdateTab);
10587 });
10588 cx.run_until_parked();
10589
10590 // Verify item1 was closed
10591 pane.read_with(cx, |pane, _| {
10592 assert_eq!(
10593 pane.items().count(),
10594 1,
10595 "Should have 1 item remaining after auto-close"
10596 );
10597 });
10598
10599 // Check navigation history after close
10600 let has_item = pane.read_with(cx, |pane, cx| {
10601 let mut has_item = false;
10602 pane.nav_history().for_each_entry(cx, |entry, _| {
10603 if entry.item.id() == item1_id {
10604 has_item = true;
10605 }
10606 });
10607 has_item
10608 });
10609
10610 assert!(
10611 !has_item,
10612 "Navigation history should not contain closed item entries"
10613 );
10614 }
10615
10616 #[gpui::test]
10617 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
10618 cx: &mut TestAppContext,
10619 ) {
10620 init_test(cx);
10621
10622 let fs = FakeFs::new(cx.background_executor.clone());
10623 let project = Project::test(fs, [], cx).await;
10624 let (workspace, cx) =
10625 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10626 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10627
10628 let dirty_regular_buffer = cx.new(|cx| {
10629 TestItem::new(cx)
10630 .with_dirty(true)
10631 .with_label("1.txt")
10632 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10633 });
10634 let dirty_regular_buffer_2 = cx.new(|cx| {
10635 TestItem::new(cx)
10636 .with_dirty(true)
10637 .with_label("2.txt")
10638 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10639 });
10640 let clear_regular_buffer = cx.new(|cx| {
10641 TestItem::new(cx)
10642 .with_label("3.txt")
10643 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
10644 });
10645
10646 let dirty_multi_buffer = cx.new(|cx| {
10647 TestItem::new(cx)
10648 .with_dirty(true)
10649 .with_buffer_kind(ItemBufferKind::Multibuffer)
10650 .with_label("Fake Project Search")
10651 .with_project_items(&[
10652 dirty_regular_buffer.read(cx).project_items[0].clone(),
10653 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
10654 clear_regular_buffer.read(cx).project_items[0].clone(),
10655 ])
10656 });
10657 workspace.update_in(cx, |workspace, window, cx| {
10658 workspace.add_item(
10659 pane.clone(),
10660 Box::new(dirty_regular_buffer.clone()),
10661 None,
10662 false,
10663 false,
10664 window,
10665 cx,
10666 );
10667 workspace.add_item(
10668 pane.clone(),
10669 Box::new(dirty_regular_buffer_2.clone()),
10670 None,
10671 false,
10672 false,
10673 window,
10674 cx,
10675 );
10676 workspace.add_item(
10677 pane.clone(),
10678 Box::new(dirty_multi_buffer.clone()),
10679 None,
10680 false,
10681 false,
10682 window,
10683 cx,
10684 );
10685 });
10686
10687 pane.update_in(cx, |pane, window, cx| {
10688 pane.activate_item(2, true, true, window, cx);
10689 assert_eq!(
10690 pane.active_item().unwrap().item_id(),
10691 dirty_multi_buffer.item_id(),
10692 "Should select the multi buffer in the pane"
10693 );
10694 });
10695 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10696 pane.close_active_item(
10697 &CloseActiveItem {
10698 save_intent: None,
10699 close_pinned: false,
10700 },
10701 window,
10702 cx,
10703 )
10704 });
10705 cx.background_executor.run_until_parked();
10706 assert!(
10707 !cx.has_pending_prompt(),
10708 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
10709 );
10710 close_multi_buffer_task
10711 .await
10712 .expect("Closing multi buffer failed");
10713 pane.update(cx, |pane, cx| {
10714 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
10715 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
10716 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
10717 assert_eq!(
10718 pane.items()
10719 .map(|item| item.item_id())
10720 .sorted()
10721 .collect::<Vec<_>>(),
10722 vec![
10723 dirty_regular_buffer.item_id(),
10724 dirty_regular_buffer_2.item_id(),
10725 ],
10726 "Should have no multi buffer left in the pane"
10727 );
10728 assert!(dirty_regular_buffer.read(cx).is_dirty);
10729 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
10730 });
10731 }
10732
10733 #[gpui::test]
10734 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
10735 init_test(cx);
10736 let fs = FakeFs::new(cx.executor());
10737 let project = Project::test(fs, [], cx).await;
10738 let (workspace, cx) =
10739 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10740
10741 // Add a new panel to the right dock, opening the dock and setting the
10742 // focus to the new panel.
10743 let panel = workspace.update_in(cx, |workspace, window, cx| {
10744 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
10745 workspace.add_panel(panel.clone(), window, cx);
10746
10747 workspace
10748 .right_dock()
10749 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10750
10751 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10752
10753 panel
10754 });
10755
10756 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
10757 // panel to the next valid position which, in this case, is the left
10758 // dock.
10759 cx.dispatch_action(MoveFocusedPanelToNextPosition);
10760 workspace.update(cx, |workspace, cx| {
10761 assert!(workspace.left_dock().read(cx).is_open());
10762 assert_eq!(panel.read(cx).position, DockPosition::Left);
10763 });
10764
10765 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
10766 // panel to the next valid position which, in this case, is the bottom
10767 // dock.
10768 cx.dispatch_action(MoveFocusedPanelToNextPosition);
10769 workspace.update(cx, |workspace, cx| {
10770 assert!(workspace.bottom_dock().read(cx).is_open());
10771 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
10772 });
10773
10774 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
10775 // around moving the panel to its initial position, the right dock.
10776 cx.dispatch_action(MoveFocusedPanelToNextPosition);
10777 workspace.update(cx, |workspace, cx| {
10778 assert!(workspace.right_dock().read(cx).is_open());
10779 assert_eq!(panel.read(cx).position, DockPosition::Right);
10780 });
10781
10782 // Remove focus from the panel, ensuring that, if the panel is not
10783 // focused, the `MoveFocusedPanelToNextPosition` action does not update
10784 // the panel's position, so the panel is still in the right dock.
10785 workspace.update_in(cx, |workspace, window, cx| {
10786 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10787 });
10788
10789 cx.dispatch_action(MoveFocusedPanelToNextPosition);
10790 workspace.update(cx, |workspace, cx| {
10791 assert!(workspace.right_dock().read(cx).is_open());
10792 assert_eq!(panel.read(cx).position, DockPosition::Right);
10793 });
10794 }
10795
10796 #[gpui::test]
10797 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
10798 init_test(cx);
10799
10800 let fs = FakeFs::new(cx.executor());
10801 let project = Project::test(fs, [], cx).await;
10802 let (workspace, cx) =
10803 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10804
10805 let item_1 = cx.new(|cx| {
10806 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
10807 });
10808 workspace.update_in(cx, |workspace, window, cx| {
10809 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
10810 workspace.move_item_to_pane_in_direction(
10811 &MoveItemToPaneInDirection {
10812 direction: SplitDirection::Right,
10813 focus: true,
10814 clone: false,
10815 },
10816 window,
10817 cx,
10818 );
10819 workspace.move_item_to_pane_at_index(
10820 &MoveItemToPane {
10821 destination: 3,
10822 focus: true,
10823 clone: false,
10824 },
10825 window,
10826 cx,
10827 );
10828
10829 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
10830 assert_eq!(
10831 pane_items_paths(&workspace.active_pane, cx),
10832 vec!["first.txt".to_string()],
10833 "Single item was not moved anywhere"
10834 );
10835 });
10836
10837 let item_2 = cx.new(|cx| {
10838 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
10839 });
10840 workspace.update_in(cx, |workspace, window, cx| {
10841 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
10842 assert_eq!(
10843 pane_items_paths(&workspace.panes[0], cx),
10844 vec!["first.txt".to_string(), "second.txt".to_string()],
10845 );
10846 workspace.move_item_to_pane_in_direction(
10847 &MoveItemToPaneInDirection {
10848 direction: SplitDirection::Right,
10849 focus: true,
10850 clone: false,
10851 },
10852 window,
10853 cx,
10854 );
10855
10856 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
10857 assert_eq!(
10858 pane_items_paths(&workspace.panes[0], cx),
10859 vec!["first.txt".to_string()],
10860 "After moving, one item should be left in the original pane"
10861 );
10862 assert_eq!(
10863 pane_items_paths(&workspace.panes[1], cx),
10864 vec!["second.txt".to_string()],
10865 "New item should have been moved to the new pane"
10866 );
10867 });
10868
10869 let item_3 = cx.new(|cx| {
10870 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
10871 });
10872 workspace.update_in(cx, |workspace, window, cx| {
10873 let original_pane = workspace.panes[0].clone();
10874 workspace.set_active_pane(&original_pane, window, cx);
10875 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
10876 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
10877 assert_eq!(
10878 pane_items_paths(&workspace.active_pane, cx),
10879 vec!["first.txt".to_string(), "third.txt".to_string()],
10880 "New pane should be ready to move one item out"
10881 );
10882
10883 workspace.move_item_to_pane_at_index(
10884 &MoveItemToPane {
10885 destination: 3,
10886 focus: true,
10887 clone: false,
10888 },
10889 window,
10890 cx,
10891 );
10892 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
10893 assert_eq!(
10894 pane_items_paths(&workspace.active_pane, cx),
10895 vec!["first.txt".to_string()],
10896 "After moving, one item should be left in the original pane"
10897 );
10898 assert_eq!(
10899 pane_items_paths(&workspace.panes[1], cx),
10900 vec!["second.txt".to_string()],
10901 "Previously created pane should be unchanged"
10902 );
10903 assert_eq!(
10904 pane_items_paths(&workspace.panes[2], cx),
10905 vec!["third.txt".to_string()],
10906 "New item should have been moved to the new pane"
10907 );
10908 });
10909 }
10910
10911 #[gpui::test]
10912 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
10913 init_test(cx);
10914
10915 let fs = FakeFs::new(cx.executor());
10916 let project = Project::test(fs, [], cx).await;
10917 let (workspace, cx) =
10918 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10919
10920 let item_1 = cx.new(|cx| {
10921 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
10922 });
10923 workspace.update_in(cx, |workspace, window, cx| {
10924 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
10925 workspace.move_item_to_pane_in_direction(
10926 &MoveItemToPaneInDirection {
10927 direction: SplitDirection::Right,
10928 focus: true,
10929 clone: true,
10930 },
10931 window,
10932 cx,
10933 );
10934 workspace.move_item_to_pane_at_index(
10935 &MoveItemToPane {
10936 destination: 3,
10937 focus: true,
10938 clone: true,
10939 },
10940 window,
10941 cx,
10942 );
10943 });
10944 cx.run_until_parked();
10945
10946 workspace.update(cx, |workspace, cx| {
10947 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
10948 for pane in workspace.panes() {
10949 assert_eq!(
10950 pane_items_paths(pane, cx),
10951 vec!["first.txt".to_string()],
10952 "Single item exists in all panes"
10953 );
10954 }
10955 });
10956
10957 // verify that the active pane has been updated after waiting for the
10958 // pane focus event to fire and resolve
10959 workspace.read_with(cx, |workspace, _app| {
10960 assert_eq!(
10961 workspace.active_pane(),
10962 &workspace.panes[2],
10963 "The third pane should be the active one: {:?}",
10964 workspace.panes
10965 );
10966 })
10967 }
10968
10969 mod register_project_item_tests {
10970
10971 use super::*;
10972
10973 // View
10974 struct TestPngItemView {
10975 focus_handle: FocusHandle,
10976 }
10977 // Model
10978 struct TestPngItem {}
10979
10980 impl project::ProjectItem for TestPngItem {
10981 fn try_open(
10982 _project: &Entity<Project>,
10983 path: &ProjectPath,
10984 cx: &mut App,
10985 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
10986 if path.path.extension().unwrap() == "png" {
10987 Some(cx.spawn(async move |cx| cx.new(|_| TestPngItem {})))
10988 } else {
10989 None
10990 }
10991 }
10992
10993 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
10994 None
10995 }
10996
10997 fn project_path(&self, _: &App) -> Option<ProjectPath> {
10998 None
10999 }
11000
11001 fn is_dirty(&self) -> bool {
11002 false
11003 }
11004 }
11005
11006 impl Item for TestPngItemView {
11007 type Event = ();
11008 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
11009 "".into()
11010 }
11011 }
11012 impl EventEmitter<()> for TestPngItemView {}
11013 impl Focusable for TestPngItemView {
11014 fn focus_handle(&self, _cx: &App) -> FocusHandle {
11015 self.focus_handle.clone()
11016 }
11017 }
11018
11019 impl Render for TestPngItemView {
11020 fn render(
11021 &mut self,
11022 _window: &mut Window,
11023 _cx: &mut Context<Self>,
11024 ) -> impl IntoElement {
11025 Empty
11026 }
11027 }
11028
11029 impl ProjectItem for TestPngItemView {
11030 type Item = TestPngItem;
11031
11032 fn for_project_item(
11033 _project: Entity<Project>,
11034 _pane: Option<&Pane>,
11035 _item: Entity<Self::Item>,
11036 _: &mut Window,
11037 cx: &mut Context<Self>,
11038 ) -> Self
11039 where
11040 Self: Sized,
11041 {
11042 Self {
11043 focus_handle: cx.focus_handle(),
11044 }
11045 }
11046 }
11047
11048 // View
11049 struct TestIpynbItemView {
11050 focus_handle: FocusHandle,
11051 }
11052 // Model
11053 struct TestIpynbItem {}
11054
11055 impl project::ProjectItem for TestIpynbItem {
11056 fn try_open(
11057 _project: &Entity<Project>,
11058 path: &ProjectPath,
11059 cx: &mut App,
11060 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
11061 if path.path.extension().unwrap() == "ipynb" {
11062 Some(cx.spawn(async move |cx| cx.new(|_| TestIpynbItem {})))
11063 } else {
11064 None
11065 }
11066 }
11067
11068 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
11069 None
11070 }
11071
11072 fn project_path(&self, _: &App) -> Option<ProjectPath> {
11073 None
11074 }
11075
11076 fn is_dirty(&self) -> bool {
11077 false
11078 }
11079 }
11080
11081 impl Item for TestIpynbItemView {
11082 type Event = ();
11083 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
11084 "".into()
11085 }
11086 }
11087 impl EventEmitter<()> for TestIpynbItemView {}
11088 impl Focusable for TestIpynbItemView {
11089 fn focus_handle(&self, _cx: &App) -> FocusHandle {
11090 self.focus_handle.clone()
11091 }
11092 }
11093
11094 impl Render for TestIpynbItemView {
11095 fn render(
11096 &mut self,
11097 _window: &mut Window,
11098 _cx: &mut Context<Self>,
11099 ) -> impl IntoElement {
11100 Empty
11101 }
11102 }
11103
11104 impl ProjectItem for TestIpynbItemView {
11105 type Item = TestIpynbItem;
11106
11107 fn for_project_item(
11108 _project: Entity<Project>,
11109 _pane: Option<&Pane>,
11110 _item: Entity<Self::Item>,
11111 _: &mut Window,
11112 cx: &mut Context<Self>,
11113 ) -> Self
11114 where
11115 Self: Sized,
11116 {
11117 Self {
11118 focus_handle: cx.focus_handle(),
11119 }
11120 }
11121 }
11122
11123 struct TestAlternatePngItemView {
11124 focus_handle: FocusHandle,
11125 }
11126
11127 impl Item for TestAlternatePngItemView {
11128 type Event = ();
11129 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
11130 "".into()
11131 }
11132 }
11133
11134 impl EventEmitter<()> for TestAlternatePngItemView {}
11135 impl Focusable for TestAlternatePngItemView {
11136 fn focus_handle(&self, _cx: &App) -> FocusHandle {
11137 self.focus_handle.clone()
11138 }
11139 }
11140
11141 impl Render for TestAlternatePngItemView {
11142 fn render(
11143 &mut self,
11144 _window: &mut Window,
11145 _cx: &mut Context<Self>,
11146 ) -> impl IntoElement {
11147 Empty
11148 }
11149 }
11150
11151 impl ProjectItem for TestAlternatePngItemView {
11152 type Item = TestPngItem;
11153
11154 fn for_project_item(
11155 _project: Entity<Project>,
11156 _pane: Option<&Pane>,
11157 _item: Entity<Self::Item>,
11158 _: &mut Window,
11159 cx: &mut Context<Self>,
11160 ) -> Self
11161 where
11162 Self: Sized,
11163 {
11164 Self {
11165 focus_handle: cx.focus_handle(),
11166 }
11167 }
11168 }
11169
11170 #[gpui::test]
11171 async fn test_register_project_item(cx: &mut TestAppContext) {
11172 init_test(cx);
11173
11174 cx.update(|cx| {
11175 register_project_item::<TestPngItemView>(cx);
11176 register_project_item::<TestIpynbItemView>(cx);
11177 });
11178
11179 let fs = FakeFs::new(cx.executor());
11180 fs.insert_tree(
11181 "/root1",
11182 json!({
11183 "one.png": "BINARYDATAHERE",
11184 "two.ipynb": "{ totally a notebook }",
11185 "three.txt": "editing text, sure why not?"
11186 }),
11187 )
11188 .await;
11189
11190 let project = Project::test(fs, ["root1".as_ref()], cx).await;
11191 let (workspace, cx) =
11192 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11193
11194 let worktree_id = project.update(cx, |project, cx| {
11195 project.worktrees(cx).next().unwrap().read(cx).id()
11196 });
11197
11198 let handle = workspace
11199 .update_in(cx, |workspace, window, cx| {
11200 let project_path = (worktree_id, rel_path("one.png"));
11201 workspace.open_path(project_path, None, true, window, cx)
11202 })
11203 .await
11204 .unwrap();
11205
11206 // Now we can check if the handle we got back errored or not
11207 assert_eq!(
11208 handle.to_any().entity_type(),
11209 TypeId::of::<TestPngItemView>()
11210 );
11211
11212 let handle = workspace
11213 .update_in(cx, |workspace, window, cx| {
11214 let project_path = (worktree_id, rel_path("two.ipynb"));
11215 workspace.open_path(project_path, None, true, window, cx)
11216 })
11217 .await
11218 .unwrap();
11219
11220 assert_eq!(
11221 handle.to_any().entity_type(),
11222 TypeId::of::<TestIpynbItemView>()
11223 );
11224
11225 let handle = workspace
11226 .update_in(cx, |workspace, window, cx| {
11227 let project_path = (worktree_id, rel_path("three.txt"));
11228 workspace.open_path(project_path, None, true, window, cx)
11229 })
11230 .await;
11231 assert!(handle.is_err());
11232 }
11233
11234 #[gpui::test]
11235 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
11236 init_test(cx);
11237
11238 cx.update(|cx| {
11239 register_project_item::<TestPngItemView>(cx);
11240 register_project_item::<TestAlternatePngItemView>(cx);
11241 });
11242
11243 let fs = FakeFs::new(cx.executor());
11244 fs.insert_tree(
11245 "/root1",
11246 json!({
11247 "one.png": "BINARYDATAHERE",
11248 "two.ipynb": "{ totally a notebook }",
11249 "three.txt": "editing text, sure why not?"
11250 }),
11251 )
11252 .await;
11253 let project = Project::test(fs, ["root1".as_ref()], cx).await;
11254 let (workspace, cx) =
11255 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11256 let worktree_id = project.update(cx, |project, cx| {
11257 project.worktrees(cx).next().unwrap().read(cx).id()
11258 });
11259
11260 let handle = workspace
11261 .update_in(cx, |workspace, window, cx| {
11262 let project_path = (worktree_id, rel_path("one.png"));
11263 workspace.open_path(project_path, None, true, window, cx)
11264 })
11265 .await
11266 .unwrap();
11267
11268 // This _must_ be the second item registered
11269 assert_eq!(
11270 handle.to_any().entity_type(),
11271 TypeId::of::<TestAlternatePngItemView>()
11272 );
11273
11274 let handle = workspace
11275 .update_in(cx, |workspace, window, cx| {
11276 let project_path = (worktree_id, rel_path("three.txt"));
11277 workspace.open_path(project_path, None, true, window, cx)
11278 })
11279 .await;
11280 assert!(handle.is_err());
11281 }
11282 }
11283
11284 #[gpui::test]
11285 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
11286 init_test(cx);
11287
11288 let fs = FakeFs::new(cx.executor());
11289 let project = Project::test(fs, [], cx).await;
11290 let (workspace, _cx) =
11291 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11292
11293 // Test with status bar shown (default)
11294 workspace.read_with(cx, |workspace, cx| {
11295 let visible = workspace.status_bar_visible(cx);
11296 assert!(visible, "Status bar should be visible by default");
11297 });
11298
11299 // Test with status bar hidden
11300 cx.update_global(|store: &mut SettingsStore, cx| {
11301 store.update_user_settings(cx, |settings| {
11302 settings.status_bar.get_or_insert_default().show = Some(false);
11303 });
11304 });
11305
11306 workspace.read_with(cx, |workspace, cx| {
11307 let visible = workspace.status_bar_visible(cx);
11308 assert!(!visible, "Status bar should be hidden when show is false");
11309 });
11310
11311 // Test with status bar shown explicitly
11312 cx.update_global(|store: &mut SettingsStore, cx| {
11313 store.update_user_settings(cx, |settings| {
11314 settings.status_bar.get_or_insert_default().show = Some(true);
11315 });
11316 });
11317
11318 workspace.read_with(cx, |workspace, cx| {
11319 let visible = workspace.status_bar_visible(cx);
11320 assert!(visible, "Status bar should be visible when show is true");
11321 });
11322 }
11323
11324 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
11325 pane.read(cx)
11326 .items()
11327 .flat_map(|item| {
11328 item.project_paths(cx)
11329 .into_iter()
11330 .map(|path| path.path.display(PathStyle::local()).into_owned())
11331 })
11332 .collect()
11333 }
11334
11335 pub fn init_test(cx: &mut TestAppContext) {
11336 cx.update(|cx| {
11337 let settings_store = SettingsStore::test(cx);
11338 cx.set_global(settings_store);
11339 theme::init(theme::LoadThemes::JustBase, cx);
11340 language::init(cx);
11341 crate::init_settings(cx);
11342 Project::init_settings(cx);
11343 });
11344 }
11345
11346 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
11347 let item = TestProjectItem::new(id, path, cx);
11348 item.update(cx, |item, _| {
11349 item.is_dirty = true;
11350 });
11351 item
11352 }
11353}