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