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