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