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