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