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