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