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