1mod dragged_item_receiver;
2
3use super::{ItemHandle, SplitDirection};
4use crate::{
5 dock::{icon_for_dock_anchor, AnchorDockBottom, AnchorDockRight, ExpandDock, HideDock},
6 item::WeakItemHandle,
7 toolbar::Toolbar,
8 Item, NewFile, NewSearch, NewTerminal, Workspace,
9};
10use anyhow::{anyhow, Result};
11use collections::{HashMap, HashSet, VecDeque};
12use context_menu::{ContextMenu, ContextMenuItem};
13use drag_and_drop::Draggable;
14pub use dragged_item_receiver::{dragged_item_receiver, handle_dropped_item};
15use futures::StreamExt;
16use gpui::{
17 actions,
18 elements::*,
19 geometry::{
20 rect::RectF,
21 vector::{vec2f, Vector2F},
22 },
23 impl_actions, impl_internal_actions,
24 keymap_matcher::KeymapContext,
25 platform::{CursorStyle, MouseButton, NavigationDirection, PromptLevel},
26 Action, AnyViewHandle, AnyWeakViewHandle, AppContext, AsyncAppContext, Entity, ModelHandle,
27 MouseRegion, Quad, Task, View, ViewContext, ViewHandle, WeakViewHandle, WindowContext,
28};
29use project::{Project, ProjectEntryId, ProjectPath};
30use serde::Deserialize;
31use settings::{Autosave, DockAnchor, Settings};
32use std::{any::Any, cell::RefCell, cmp, mem, path::Path, rc::Rc};
33use theme::Theme;
34use util::ResultExt;
35
36#[derive(Clone, Deserialize, PartialEq)]
37pub struct ActivateItem(pub usize);
38
39#[derive(Clone, PartialEq)]
40pub struct CloseItemById {
41 pub item_id: usize,
42 pub pane: WeakViewHandle<Pane>,
43}
44
45#[derive(Clone, PartialEq)]
46pub struct CloseItemsToTheLeftById {
47 pub item_id: usize,
48 pub pane: WeakViewHandle<Pane>,
49}
50
51#[derive(Clone, PartialEq)]
52pub struct CloseItemsToTheRightById {
53 pub item_id: usize,
54 pub pane: WeakViewHandle<Pane>,
55}
56
57actions!(
58 pane,
59 [
60 ActivatePrevItem,
61 ActivateNextItem,
62 ActivateLastItem,
63 CloseActiveItem,
64 CloseInactiveItems,
65 CloseCleanItems,
66 CloseItemsToTheLeft,
67 CloseItemsToTheRight,
68 CloseAllItems,
69 ReopenClosedItem,
70 SplitLeft,
71 SplitUp,
72 SplitRight,
73 SplitDown,
74 ]
75);
76
77#[derive(Clone, PartialEq)]
78pub struct MoveItem {
79 pub item_id: usize,
80 pub from: WeakViewHandle<Pane>,
81 pub to: WeakViewHandle<Pane>,
82 pub destination_index: usize,
83}
84
85#[derive(Clone, Deserialize, PartialEq)]
86pub struct GoBack {
87 #[serde(skip_deserializing)]
88 pub pane: Option<WeakViewHandle<Pane>>,
89}
90
91#[derive(Clone, Deserialize, PartialEq)]
92pub struct GoForward {
93 #[serde(skip_deserializing)]
94 pub pane: Option<WeakViewHandle<Pane>>,
95}
96
97#[derive(Clone, PartialEq)]
98pub struct DeploySplitMenu;
99
100#[derive(Clone, PartialEq)]
101pub struct DeployDockMenu;
102
103#[derive(Clone, PartialEq)]
104pub struct DeployNewMenu;
105
106#[derive(Clone, PartialEq)]
107pub struct DeployTabContextMenu {
108 pub position: Vector2F,
109 pub item_id: usize,
110 pub pane: WeakViewHandle<Pane>,
111}
112
113impl_actions!(pane, [GoBack, GoForward, ActivateItem]);
114impl_internal_actions!(
115 pane,
116 [
117 CloseItemById,
118 CloseItemsToTheLeftById,
119 CloseItemsToTheRightById,
120 DeployTabContextMenu,
121 DeploySplitMenu,
122 DeployNewMenu,
123 DeployDockMenu,
124 MoveItem
125 ]
126);
127
128const MAX_NAVIGATION_HISTORY_LEN: usize = 1024;
129
130pub type BackgroundActions = fn() -> &'static [(&'static str, &'static dyn Action)];
131
132pub fn init(cx: &mut AppContext) {
133 cx.add_action(|pane: &mut Pane, action: &ActivateItem, cx| {
134 pane.activate_item(action.0, true, true, cx);
135 });
136 cx.add_action(|pane: &mut Pane, _: &ActivateLastItem, cx| {
137 pane.activate_item(pane.items.len() - 1, true, true, cx);
138 });
139 cx.add_action(|pane: &mut Pane, _: &ActivatePrevItem, cx| {
140 pane.activate_prev_item(true, cx);
141 });
142 cx.add_action(|pane: &mut Pane, _: &ActivateNextItem, cx| {
143 pane.activate_next_item(true, cx);
144 });
145 cx.add_async_action(Pane::close_active_item);
146 cx.add_async_action(Pane::close_inactive_items);
147 cx.add_async_action(Pane::close_clean_items);
148 cx.add_async_action(Pane::close_items_to_the_left);
149 cx.add_async_action(Pane::close_items_to_the_right);
150 cx.add_async_action(Pane::close_all_items);
151 cx.add_async_action(|workspace: &mut Workspace, action: &CloseItemById, cx| {
152 let pane = action.pane.upgrade(cx)?;
153 let task = Pane::close_item_by_id(workspace, pane, action.item_id, cx);
154 Some(cx.foreground().spawn(async move {
155 task.await?;
156 Ok(())
157 }))
158 });
159 cx.add_async_action(
160 |workspace: &mut Workspace, action: &CloseItemsToTheLeftById, cx| {
161 let pane = action.pane.upgrade(cx)?;
162 let task = Pane::close_items_to_the_left_by_id(workspace, pane, action.item_id, cx);
163 Some(cx.foreground().spawn(async move {
164 task.await?;
165 Ok(())
166 }))
167 },
168 );
169 cx.add_async_action(
170 |workspace: &mut Workspace, action: &CloseItemsToTheRightById, cx| {
171 let pane = action.pane.upgrade(cx)?;
172 let task = Pane::close_items_to_the_right_by_id(workspace, pane, action.item_id, cx);
173 Some(cx.foreground().spawn(async move {
174 task.await?;
175 Ok(())
176 }))
177 },
178 );
179 cx.add_action(
180 |workspace,
181 MoveItem {
182 from,
183 to,
184 item_id,
185 destination_index,
186 },
187 cx| {
188 // Get item handle to move
189 let from = if let Some(from) = from.upgrade(cx) {
190 from
191 } else {
192 return;
193 };
194
195 // Add item to new pane at given index
196 let to = if let Some(to) = to.upgrade(cx) {
197 to
198 } else {
199 return;
200 };
201
202 Pane::move_item(workspace, from, to, *item_id, *destination_index, cx)
203 },
204 );
205 cx.add_action(|pane: &mut Pane, _: &SplitLeft, cx| pane.split(SplitDirection::Left, cx));
206 cx.add_action(|pane: &mut Pane, _: &SplitUp, cx| pane.split(SplitDirection::Up, cx));
207 cx.add_action(|pane: &mut Pane, _: &SplitRight, cx| pane.split(SplitDirection::Right, cx));
208 cx.add_action(|pane: &mut Pane, _: &SplitDown, cx| pane.split(SplitDirection::Down, cx));
209 cx.add_action(Pane::deploy_split_menu);
210 cx.add_action(Pane::deploy_dock_menu);
211 cx.add_action(Pane::deploy_new_menu);
212 cx.add_action(Pane::deploy_tab_context_menu);
213 cx.add_action(|workspace: &mut Workspace, _: &ReopenClosedItem, cx| {
214 Pane::reopen_closed_item(workspace, cx).detach();
215 });
216 cx.add_action(|workspace: &mut Workspace, action: &GoBack, cx| {
217 Pane::go_back(
218 workspace,
219 action
220 .pane
221 .as_ref()
222 .and_then(|weak_handle| weak_handle.upgrade(cx)),
223 cx,
224 )
225 .detach();
226 });
227 cx.add_action(|workspace: &mut Workspace, action: &GoForward, cx| {
228 Pane::go_forward(
229 workspace,
230 action
231 .pane
232 .as_ref()
233 .and_then(|weak_handle| weak_handle.upgrade(cx)),
234 cx,
235 )
236 .detach();
237 });
238}
239
240#[derive(Debug)]
241pub enum Event {
242 ActivateItem { local: bool },
243 Remove,
244 RemoveItem { item_id: usize },
245 Split(SplitDirection),
246 ChangeItemTitle,
247}
248
249pub struct Pane {
250 items: Vec<Box<dyn ItemHandle>>,
251 activation_history: Vec<usize>,
252 is_active: bool,
253 active_item_index: usize,
254 last_focused_view_by_item: HashMap<usize, AnyWeakViewHandle>,
255 autoscroll: bool,
256 nav_history: Rc<RefCell<NavHistory>>,
257 toolbar: ViewHandle<Toolbar>,
258 tab_bar_context_menu: TabBarContextMenu,
259 tab_context_menu: ViewHandle<ContextMenu>,
260 docked: Option<DockAnchor>,
261 _background_actions: BackgroundActions,
262 _workspace_id: usize,
263}
264
265pub struct ItemNavHistory {
266 history: Rc<RefCell<NavHistory>>,
267 item: Rc<dyn WeakItemHandle>,
268}
269
270struct NavHistory {
271 mode: NavigationMode,
272 backward_stack: VecDeque<NavigationEntry>,
273 forward_stack: VecDeque<NavigationEntry>,
274 closed_stack: VecDeque<NavigationEntry>,
275 paths_by_item: HashMap<usize, ProjectPath>,
276 pane: WeakViewHandle<Pane>,
277}
278
279#[derive(Copy, Clone)]
280enum NavigationMode {
281 Normal,
282 GoingBack,
283 GoingForward,
284 ClosingItem,
285 ReopeningClosedItem,
286 Disabled,
287}
288
289impl Default for NavigationMode {
290 fn default() -> Self {
291 Self::Normal
292 }
293}
294
295pub struct NavigationEntry {
296 pub item: Rc<dyn WeakItemHandle>,
297 pub data: Option<Box<dyn Any>>,
298}
299
300struct DraggedItem {
301 item: Box<dyn ItemHandle>,
302 pane: WeakViewHandle<Pane>,
303}
304
305pub enum ReorderBehavior {
306 None,
307 MoveAfterActive,
308 MoveToIndex(usize),
309}
310
311#[derive(Debug, Clone, Copy, PartialEq, Eq)]
312enum TabBarContextMenuKind {
313 New,
314 Split,
315 Dock,
316}
317
318struct TabBarContextMenu {
319 kind: TabBarContextMenuKind,
320 handle: ViewHandle<ContextMenu>,
321}
322
323impl TabBarContextMenu {
324 fn handle_if_kind(&self, kind: TabBarContextMenuKind) -> Option<ViewHandle<ContextMenu>> {
325 if self.kind == kind {
326 return Some(self.handle.clone());
327 }
328 None
329 }
330}
331
332impl Pane {
333 pub fn new(
334 workspace_id: usize,
335 docked: Option<DockAnchor>,
336 background_actions: BackgroundActions,
337 cx: &mut ViewContext<Self>,
338 ) -> Self {
339 let handle = cx.weak_handle();
340 let context_menu = cx.add_view(ContextMenu::new);
341 context_menu.update(cx, |menu, _| {
342 menu.set_position_mode(OverlayPositionMode::Local)
343 });
344
345 Self {
346 items: Vec::new(),
347 activation_history: Vec::new(),
348 is_active: true,
349 active_item_index: 0,
350 last_focused_view_by_item: Default::default(),
351 autoscroll: false,
352 nav_history: Rc::new(RefCell::new(NavHistory {
353 mode: NavigationMode::Normal,
354 backward_stack: Default::default(),
355 forward_stack: Default::default(),
356 closed_stack: Default::default(),
357 paths_by_item: Default::default(),
358 pane: handle.clone(),
359 })),
360 toolbar: cx.add_view(|_| Toolbar::new(handle)),
361 tab_bar_context_menu: TabBarContextMenu {
362 kind: TabBarContextMenuKind::New,
363 handle: context_menu,
364 },
365 tab_context_menu: cx.add_view(ContextMenu::new),
366 docked,
367 _background_actions: background_actions,
368 _workspace_id: workspace_id,
369 }
370 }
371
372 pub fn is_active(&self) -> bool {
373 self.is_active
374 }
375
376 pub fn set_active(&mut self, is_active: bool, cx: &mut ViewContext<Self>) {
377 self.is_active = is_active;
378 cx.notify();
379 }
380
381 pub fn set_docked(&mut self, docked: Option<DockAnchor>, cx: &mut ViewContext<Self>) {
382 self.docked = docked;
383 cx.notify();
384 }
385
386 pub fn nav_history_for_item<T: Item>(&self, item: &ViewHandle<T>) -> ItemNavHistory {
387 ItemNavHistory {
388 history: self.nav_history.clone(),
389 item: Rc::new(item.downgrade()),
390 }
391 }
392
393 pub fn go_back(
394 workspace: &mut Workspace,
395 pane: Option<ViewHandle<Pane>>,
396 cx: &mut ViewContext<Workspace>,
397 ) -> Task<Result<()>> {
398 Self::navigate_history(
399 workspace,
400 pane.unwrap_or_else(|| workspace.active_pane().clone()),
401 NavigationMode::GoingBack,
402 cx,
403 )
404 }
405
406 pub fn go_forward(
407 workspace: &mut Workspace,
408 pane: Option<ViewHandle<Pane>>,
409 cx: &mut ViewContext<Workspace>,
410 ) -> Task<Result<()>> {
411 Self::navigate_history(
412 workspace,
413 pane.unwrap_or_else(|| workspace.active_pane().clone()),
414 NavigationMode::GoingForward,
415 cx,
416 )
417 }
418
419 pub fn reopen_closed_item(
420 workspace: &mut Workspace,
421 cx: &mut ViewContext<Workspace>,
422 ) -> Task<Result<()>> {
423 Self::navigate_history(
424 workspace,
425 workspace.active_pane().clone(),
426 NavigationMode::ReopeningClosedItem,
427 cx,
428 )
429 }
430
431 pub fn disable_history(&mut self) {
432 self.nav_history.borrow_mut().disable();
433 }
434
435 pub fn enable_history(&mut self) {
436 self.nav_history.borrow_mut().enable();
437 }
438
439 pub fn can_navigate_backward(&self) -> bool {
440 !self.nav_history.borrow().backward_stack.is_empty()
441 }
442
443 pub fn can_navigate_forward(&self) -> bool {
444 !self.nav_history.borrow().forward_stack.is_empty()
445 }
446
447 fn history_updated(&mut self, cx: &mut ViewContext<Self>) {
448 self.toolbar.update(cx, |_, cx| cx.notify());
449 }
450
451 fn navigate_history(
452 workspace: &mut Workspace,
453 pane: ViewHandle<Pane>,
454 mode: NavigationMode,
455 cx: &mut ViewContext<Workspace>,
456 ) -> Task<Result<()>> {
457 cx.focus(&pane);
458
459 let to_load = pane.update(cx, |pane, cx| {
460 loop {
461 // Retrieve the weak item handle from the history.
462 let entry = pane.nav_history.borrow_mut().pop(mode, cx)?;
463
464 // If the item is still present in this pane, then activate it.
465 if let Some(index) = entry
466 .item
467 .upgrade(cx)
468 .and_then(|v| pane.index_for_item(v.as_ref()))
469 {
470 let prev_active_item_index = pane.active_item_index;
471 pane.nav_history.borrow_mut().set_mode(mode);
472 pane.activate_item(index, true, true, cx);
473 pane.nav_history
474 .borrow_mut()
475 .set_mode(NavigationMode::Normal);
476
477 let mut navigated = prev_active_item_index != pane.active_item_index;
478 if let Some(data) = entry.data {
479 navigated |= pane.active_item()?.navigate(data, cx);
480 }
481
482 if navigated {
483 break None;
484 }
485 }
486 // If the item is no longer present in this pane, then retrieve its
487 // project path in order to reopen it.
488 else {
489 break pane
490 .nav_history
491 .borrow()
492 .paths_by_item
493 .get(&entry.item.id())
494 .cloned()
495 .map(|project_path| (project_path, entry));
496 }
497 }
498 });
499
500 if let Some((project_path, entry)) = to_load {
501 // If the item was no longer present, then load it again from its previous path.
502 let pane = pane.downgrade();
503 let task = workspace.load_path(project_path, cx);
504 cx.spawn(|workspace, mut cx| async move {
505 let task = task.await;
506 let pane = pane
507 .upgrade(&cx)
508 .ok_or_else(|| anyhow!("pane was dropped"))?;
509 let mut navigated = false;
510 if let Some((project_entry_id, build_item)) = task.log_err() {
511 let prev_active_item_id = pane.update(&mut cx, |pane, _| {
512 pane.nav_history.borrow_mut().set_mode(mode);
513 pane.active_item().map(|p| p.id())
514 })?;
515
516 let item = workspace.update(&mut cx, |workspace, cx| {
517 Self::open_item(
518 workspace,
519 pane.clone(),
520 project_entry_id,
521 true,
522 cx,
523 build_item,
524 )
525 })?;
526
527 pane.update(&mut cx, |pane, cx| {
528 navigated |= Some(item.id()) != prev_active_item_id;
529 pane.nav_history
530 .borrow_mut()
531 .set_mode(NavigationMode::Normal);
532 if let Some(data) = entry.data {
533 navigated |= item.navigate(data, cx);
534 }
535 })?;
536 }
537
538 if !navigated {
539 workspace
540 .update(&mut cx, |workspace, cx| {
541 Self::navigate_history(workspace, pane, mode, cx)
542 })?
543 .await?;
544 }
545
546 Ok(())
547 })
548 } else {
549 Task::ready(Ok(()))
550 }
551 }
552
553 pub(crate) fn open_item(
554 workspace: &mut Workspace,
555 pane: ViewHandle<Pane>,
556 project_entry_id: ProjectEntryId,
557 focus_item: bool,
558 cx: &mut ViewContext<Workspace>,
559 build_item: impl FnOnce(&mut ViewContext<Pane>) -> Box<dyn ItemHandle>,
560 ) -> Box<dyn ItemHandle> {
561 let existing_item = pane.update(cx, |pane, cx| {
562 for (index, item) in pane.items.iter().enumerate() {
563 if item.is_singleton(cx)
564 && item.project_entry_ids(cx).as_slice() == [project_entry_id]
565 {
566 let item = item.boxed_clone();
567 return Some((index, item));
568 }
569 }
570 None
571 });
572
573 if let Some((index, existing_item)) = existing_item {
574 pane.update(cx, |pane, cx| {
575 pane.activate_item(index, focus_item, focus_item, cx);
576 });
577 existing_item
578 } else {
579 let new_item = pane.update(cx, |_, cx| build_item(cx));
580 Pane::add_item(
581 workspace,
582 &pane,
583 new_item.clone(),
584 true,
585 focus_item,
586 None,
587 cx,
588 );
589 new_item
590 }
591 }
592
593 pub(crate) fn add_item(
594 workspace: &mut Workspace,
595 pane: &ViewHandle<Pane>,
596 item: Box<dyn ItemHandle>,
597 activate_pane: bool,
598 focus_item: bool,
599 destination_index: Option<usize>,
600 cx: &mut ViewContext<Workspace>,
601 ) {
602 // If no destination index is specified, add or move the item after the active item.
603 let mut insertion_index = {
604 let pane = pane.read(cx);
605 cmp::min(
606 if let Some(destination_index) = destination_index {
607 destination_index
608 } else {
609 pane.active_item_index + 1
610 },
611 pane.items.len(),
612 )
613 };
614
615 item.added_to_pane(workspace, pane.clone(), cx);
616
617 // Does the item already exist?
618 let project_entry_id = if item.is_singleton(cx) {
619 item.project_entry_ids(cx).get(0).copied()
620 } else {
621 None
622 };
623
624 let existing_item_index = pane.read(cx).items.iter().position(|existing_item| {
625 if existing_item.id() == item.id() {
626 true
627 } else if existing_item.is_singleton(cx) {
628 existing_item
629 .project_entry_ids(cx)
630 .get(0)
631 .map_or(false, |existing_entry_id| {
632 Some(existing_entry_id) == project_entry_id.as_ref()
633 })
634 } else {
635 false
636 }
637 });
638
639 if let Some(existing_item_index) = existing_item_index {
640 // If the item already exists, move it to the desired destination and activate it
641 pane.update(cx, |pane, cx| {
642 if existing_item_index != insertion_index {
643 cx.reparent(item.as_any());
644 let existing_item_is_active = existing_item_index == pane.active_item_index;
645
646 // If the caller didn't specify a destination and the added item is already
647 // the active one, don't move it
648 if existing_item_is_active && destination_index.is_none() {
649 insertion_index = existing_item_index;
650 } else {
651 pane.items.remove(existing_item_index);
652 if existing_item_index < pane.active_item_index {
653 pane.active_item_index -= 1;
654 }
655 insertion_index = insertion_index.min(pane.items.len());
656
657 pane.items.insert(insertion_index, item.clone());
658
659 if existing_item_is_active {
660 pane.active_item_index = insertion_index;
661 } else if insertion_index <= pane.active_item_index {
662 pane.active_item_index += 1;
663 }
664 }
665
666 cx.notify();
667 }
668
669 pane.activate_item(insertion_index, activate_pane, focus_item, cx);
670 });
671 } else {
672 pane.update(cx, |pane, cx| {
673 cx.reparent(item.as_any());
674 pane.items.insert(insertion_index, item);
675 if insertion_index <= pane.active_item_index {
676 pane.active_item_index += 1;
677 }
678
679 pane.activate_item(insertion_index, activate_pane, focus_item, cx);
680 cx.notify();
681 });
682 }
683 }
684
685 pub fn items_len(&self) -> usize {
686 self.items.len()
687 }
688
689 pub fn items(&self) -> impl Iterator<Item = &Box<dyn ItemHandle>> + DoubleEndedIterator {
690 self.items.iter()
691 }
692
693 pub fn items_of_type<T: View>(&self) -> impl '_ + Iterator<Item = ViewHandle<T>> {
694 self.items
695 .iter()
696 .filter_map(|item| item.as_any().clone().downcast())
697 }
698
699 pub fn active_item(&self) -> Option<Box<dyn ItemHandle>> {
700 self.items.get(self.active_item_index).cloned()
701 }
702
703 pub fn item_for_entry(
704 &self,
705 entry_id: ProjectEntryId,
706 cx: &AppContext,
707 ) -> Option<Box<dyn ItemHandle>> {
708 self.items.iter().find_map(|item| {
709 if item.is_singleton(cx) && item.project_entry_ids(cx).as_slice() == [entry_id] {
710 Some(item.boxed_clone())
711 } else {
712 None
713 }
714 })
715 }
716
717 pub fn index_for_item(&self, item: &dyn ItemHandle) -> Option<usize> {
718 self.items.iter().position(|i| i.id() == item.id())
719 }
720
721 pub fn activate_item(
722 &mut self,
723 index: usize,
724 activate_pane: bool,
725 focus_item: bool,
726 cx: &mut ViewContext<Self>,
727 ) {
728 use NavigationMode::{GoingBack, GoingForward};
729
730 if index < self.items.len() {
731 let prev_active_item_ix = mem::replace(&mut self.active_item_index, index);
732 if prev_active_item_ix != self.active_item_index
733 || matches!(self.nav_history.borrow().mode, GoingBack | GoingForward)
734 {
735 if let Some(prev_item) = self.items.get(prev_active_item_ix) {
736 prev_item.deactivated(cx);
737 }
738
739 cx.emit(Event::ActivateItem {
740 local: activate_pane,
741 });
742 }
743
744 if let Some(newly_active_item) = self.items.get(index) {
745 self.activation_history
746 .retain(|&previously_active_item_id| {
747 previously_active_item_id != newly_active_item.id()
748 });
749 self.activation_history.push(newly_active_item.id());
750 }
751
752 self.update_toolbar(cx);
753
754 if focus_item {
755 self.focus_active_item(cx);
756 }
757
758 self.autoscroll = true;
759 cx.notify();
760 }
761 }
762
763 pub fn activate_prev_item(&mut self, activate_pane: bool, cx: &mut ViewContext<Self>) {
764 let mut index = self.active_item_index;
765 if index > 0 {
766 index -= 1;
767 } else if !self.items.is_empty() {
768 index = self.items.len() - 1;
769 }
770 self.activate_item(index, activate_pane, activate_pane, cx);
771 }
772
773 pub fn activate_next_item(&mut self, activate_pane: bool, cx: &mut ViewContext<Self>) {
774 let mut index = self.active_item_index;
775 if index + 1 < self.items.len() {
776 index += 1;
777 } else {
778 index = 0;
779 }
780 self.activate_item(index, activate_pane, activate_pane, cx);
781 }
782
783 pub fn close_active_item(
784 workspace: &mut Workspace,
785 _: &CloseActiveItem,
786 cx: &mut ViewContext<Workspace>,
787 ) -> Option<Task<Result<()>>> {
788 let pane_handle = workspace.active_pane().clone();
789 let pane = pane_handle.read(cx);
790
791 if pane.items.is_empty() {
792 return None;
793 }
794 let active_item_id = pane.items[pane.active_item_index].id();
795
796 let task = Self::close_item_by_id(workspace, pane_handle, active_item_id, cx);
797
798 Some(cx.foreground().spawn(async move {
799 task.await?;
800 Ok(())
801 }))
802 }
803
804 pub fn close_item_by_id(
805 workspace: &mut Workspace,
806 pane: ViewHandle<Pane>,
807 item_id_to_close: usize,
808 cx: &mut ViewContext<Workspace>,
809 ) -> Task<Result<()>> {
810 Self::close_items(workspace, pane, cx, move |view_id| {
811 view_id == item_id_to_close
812 })
813 }
814
815 pub fn close_inactive_items(
816 workspace: &mut Workspace,
817 _: &CloseInactiveItems,
818 cx: &mut ViewContext<Workspace>,
819 ) -> Option<Task<Result<()>>> {
820 let pane_handle = workspace.active_pane().clone();
821 let pane = pane_handle.read(cx);
822 let active_item_id = pane.items[pane.active_item_index].id();
823
824 let task = Self::close_items(workspace, pane_handle, cx, move |item_id| {
825 item_id != active_item_id
826 });
827
828 Some(cx.foreground().spawn(async move {
829 task.await?;
830 Ok(())
831 }))
832 }
833
834 pub fn close_clean_items(
835 workspace: &mut Workspace,
836 _: &CloseCleanItems,
837 cx: &mut ViewContext<Workspace>,
838 ) -> Option<Task<Result<()>>> {
839 let pane_handle = workspace.active_pane().clone();
840 let pane = pane_handle.read(cx);
841
842 let item_ids: Vec<_> = pane
843 .items()
844 .filter(|item| !item.is_dirty(cx))
845 .map(|item| item.id())
846 .collect();
847
848 let task = Self::close_items(workspace, pane_handle, cx, move |item_id| {
849 item_ids.contains(&item_id)
850 });
851
852 Some(cx.foreground().spawn(async move {
853 task.await?;
854 Ok(())
855 }))
856 }
857
858 pub fn close_items_to_the_left(
859 workspace: &mut Workspace,
860 _: &CloseItemsToTheLeft,
861 cx: &mut ViewContext<Workspace>,
862 ) -> Option<Task<Result<()>>> {
863 let pane_handle = workspace.active_pane().clone();
864 let pane = pane_handle.read(cx);
865 let active_item_id = pane.items[pane.active_item_index].id();
866
867 let task = Self::close_items_to_the_left_by_id(workspace, pane_handle, active_item_id, cx);
868
869 Some(cx.foreground().spawn(async move {
870 task.await?;
871 Ok(())
872 }))
873 }
874
875 pub fn close_items_to_the_left_by_id(
876 workspace: &mut Workspace,
877 pane: ViewHandle<Pane>,
878 item_id: usize,
879 cx: &mut ViewContext<Workspace>,
880 ) -> Task<Result<()>> {
881 let item_ids: Vec<_> = pane
882 .read(cx)
883 .items()
884 .take_while(|item| item.id() != item_id)
885 .map(|item| item.id())
886 .collect();
887
888 let task = Self::close_items(workspace, pane, cx, move |item_id| {
889 item_ids.contains(&item_id)
890 });
891
892 cx.foreground().spawn(async move {
893 task.await?;
894 Ok(())
895 })
896 }
897
898 pub fn close_items_to_the_right(
899 workspace: &mut Workspace,
900 _: &CloseItemsToTheRight,
901 cx: &mut ViewContext<Workspace>,
902 ) -> Option<Task<Result<()>>> {
903 let pane_handle = workspace.active_pane().clone();
904 let pane = pane_handle.read(cx);
905 let active_item_id = pane.items[pane.active_item_index].id();
906
907 let task = Self::close_items_to_the_right_by_id(workspace, pane_handle, active_item_id, cx);
908
909 Some(cx.foreground().spawn(async move {
910 task.await?;
911 Ok(())
912 }))
913 }
914
915 pub fn close_items_to_the_right_by_id(
916 workspace: &mut Workspace,
917 pane: ViewHandle<Pane>,
918 item_id: usize,
919 cx: &mut ViewContext<Workspace>,
920 ) -> Task<Result<()>> {
921 let item_ids: Vec<_> = pane
922 .read(cx)
923 .items()
924 .rev()
925 .take_while(|item| item.id() != item_id)
926 .map(|item| item.id())
927 .collect();
928
929 let task = Self::close_items(workspace, pane, cx, move |item_id| {
930 item_ids.contains(&item_id)
931 });
932
933 cx.foreground().spawn(async move {
934 task.await?;
935 Ok(())
936 })
937 }
938
939 pub fn close_all_items(
940 workspace: &mut Workspace,
941 _: &CloseAllItems,
942 cx: &mut ViewContext<Workspace>,
943 ) -> Option<Task<Result<()>>> {
944 let pane_handle = workspace.active_pane().clone();
945
946 let task = Self::close_items(workspace, pane_handle, cx, move |_| true);
947
948 Some(cx.foreground().spawn(async move {
949 task.await?;
950 Ok(())
951 }))
952 }
953
954 pub fn close_items(
955 workspace: &mut Workspace,
956 pane: ViewHandle<Pane>,
957 cx: &mut ViewContext<Workspace>,
958 should_close: impl 'static + Fn(usize) -> bool,
959 ) -> Task<Result<()>> {
960 let project = workspace.project().clone();
961
962 // Find the items to close.
963 let mut items_to_close = Vec::new();
964 for item in &pane.read(cx).items {
965 if should_close(item.id()) {
966 items_to_close.push(item.boxed_clone());
967 }
968 }
969
970 // If a buffer is open both in a singleton editor and in a multibuffer, make sure
971 // to focus the singleton buffer when prompting to save that buffer, as opposed
972 // to focusing the multibuffer, because this gives the user a more clear idea
973 // of what content they would be saving.
974 items_to_close.sort_by_key(|item| !item.is_singleton(cx));
975
976 cx.spawn(|workspace, mut cx| async move {
977 let mut saved_project_items_ids = HashSet::default();
978 for item in items_to_close.clone() {
979 // Find the item's current index and its set of project item models. Avoid
980 // storing these in advance, in case they have changed since this task
981 // was started.
982 let (item_ix, mut project_item_ids) = pane.read_with(&cx, |pane, cx| {
983 (pane.index_for_item(&*item), item.project_item_model_ids(cx))
984 })?;
985 let item_ix = if let Some(ix) = item_ix {
986 ix
987 } else {
988 continue;
989 };
990
991 // Check if this view has any project items that are not open anywhere else
992 // in the workspace, AND that the user has not already been prompted to save.
993 // If there are any such project entries, prompt the user to save this item.
994 workspace.read_with(&cx, |workspace, cx| {
995 for item in workspace.items(cx) {
996 if !items_to_close
997 .iter()
998 .any(|item_to_close| item_to_close.id() == item.id())
999 {
1000 let other_project_item_ids = item.project_item_model_ids(cx);
1001 project_item_ids.retain(|id| !other_project_item_ids.contains(id));
1002 }
1003 }
1004 })?;
1005 let should_save = project_item_ids
1006 .iter()
1007 .any(|id| saved_project_items_ids.insert(*id));
1008
1009 if should_save
1010 && !Self::save_item(project.clone(), &pane, item_ix, &*item, true, &mut cx)
1011 .await?
1012 {
1013 break;
1014 }
1015
1016 // Remove the item from the pane.
1017 pane.update(&mut cx, |pane, cx| {
1018 if let Some(item_ix) = pane.items.iter().position(|i| i.id() == item.id()) {
1019 pane.remove_item(item_ix, false, cx);
1020 }
1021 })?;
1022 }
1023
1024 pane.update(&mut cx, |_, cx| cx.notify())?;
1025 Ok(())
1026 })
1027 }
1028
1029 fn remove_item(&mut self, item_index: usize, activate_pane: bool, cx: &mut ViewContext<Self>) {
1030 self.activation_history
1031 .retain(|&history_entry| history_entry != self.items[item_index].id());
1032
1033 if item_index == self.active_item_index {
1034 let index_to_activate = self
1035 .activation_history
1036 .pop()
1037 .and_then(|last_activated_item| {
1038 self.items.iter().enumerate().find_map(|(index, item)| {
1039 (item.id() == last_activated_item).then_some(index)
1040 })
1041 })
1042 // We didn't have a valid activation history entry, so fallback
1043 // to activating the item to the left
1044 .unwrap_or_else(|| item_index.min(self.items.len()).saturating_sub(1));
1045
1046 self.activate_item(index_to_activate, activate_pane, activate_pane, cx);
1047 }
1048
1049 let item = self.items.remove(item_index);
1050
1051 cx.emit(Event::RemoveItem { item_id: item.id() });
1052 if self.items.is_empty() {
1053 item.deactivated(cx);
1054 self.update_toolbar(cx);
1055 cx.emit(Event::Remove);
1056 }
1057
1058 if item_index < self.active_item_index {
1059 self.active_item_index -= 1;
1060 }
1061
1062 self.nav_history
1063 .borrow_mut()
1064 .set_mode(NavigationMode::ClosingItem);
1065 item.deactivated(cx);
1066 self.nav_history
1067 .borrow_mut()
1068 .set_mode(NavigationMode::Normal);
1069
1070 if let Some(path) = item.project_path(cx) {
1071 self.nav_history
1072 .borrow_mut()
1073 .paths_by_item
1074 .insert(item.id(), path);
1075 } else {
1076 self.nav_history
1077 .borrow_mut()
1078 .paths_by_item
1079 .remove(&item.id());
1080 }
1081
1082 cx.notify();
1083 }
1084
1085 pub async fn save_item(
1086 project: ModelHandle<Project>,
1087 pane: &ViewHandle<Pane>,
1088 item_ix: usize,
1089 item: &dyn ItemHandle,
1090 should_prompt_for_save: bool,
1091 cx: &mut AsyncAppContext,
1092 ) -> Result<bool> {
1093 const CONFLICT_MESSAGE: &str =
1094 "This file has changed on disk since you started editing it. Do you want to overwrite it?";
1095 const DIRTY_MESSAGE: &str = "This file contains unsaved edits. Do you want to save it?";
1096
1097 let (has_conflict, is_dirty, can_save, is_singleton) = cx.read(|cx| {
1098 (
1099 item.has_conflict(cx),
1100 item.is_dirty(cx),
1101 item.can_save(cx),
1102 item.is_singleton(cx),
1103 )
1104 });
1105
1106 if has_conflict && can_save {
1107 let mut answer = pane.update(cx, |pane, cx| {
1108 pane.activate_item(item_ix, true, true, cx);
1109 cx.prompt(
1110 PromptLevel::Warning,
1111 CONFLICT_MESSAGE,
1112 &["Overwrite", "Discard", "Cancel"],
1113 )
1114 })?;
1115 match answer.next().await {
1116 Some(0) => pane.update(cx, |_, cx| item.save(project, cx))?.await?,
1117 Some(1) => pane.update(cx, |_, cx| item.reload(project, cx))?.await?,
1118 _ => return Ok(false),
1119 }
1120 } else if is_dirty && (can_save || is_singleton) {
1121 let will_autosave = cx.read(|cx| {
1122 matches!(
1123 cx.global::<Settings>().autosave,
1124 Autosave::OnFocusChange | Autosave::OnWindowChange
1125 ) && Self::can_autosave_item(&*item, cx)
1126 });
1127 let should_save = if should_prompt_for_save && !will_autosave {
1128 let mut answer = pane.update(cx, |pane, cx| {
1129 pane.activate_item(item_ix, true, true, cx);
1130 cx.prompt(
1131 PromptLevel::Warning,
1132 DIRTY_MESSAGE,
1133 &["Save", "Don't Save", "Cancel"],
1134 )
1135 })?;
1136 match answer.next().await {
1137 Some(0) => true,
1138 Some(1) => false,
1139 _ => return Ok(false),
1140 }
1141 } else {
1142 true
1143 };
1144
1145 if should_save {
1146 if can_save {
1147 pane.update(cx, |_, cx| item.save(project, cx))?.await?;
1148 } else if is_singleton {
1149 let start_abs_path = project
1150 .read_with(cx, |project, cx| {
1151 let worktree = project.visible_worktrees(cx).next()?;
1152 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
1153 })
1154 .unwrap_or_else(|| Path::new("").into());
1155
1156 let mut abs_path = cx.update(|cx| cx.prompt_for_new_path(&start_abs_path));
1157 if let Some(abs_path) = abs_path.next().await.flatten() {
1158 pane.update(cx, |_, cx| item.save_as(project, abs_path, cx))?
1159 .await?;
1160 } else {
1161 return Ok(false);
1162 }
1163 }
1164 }
1165 }
1166 Ok(true)
1167 }
1168
1169 fn can_autosave_item(item: &dyn ItemHandle, cx: &AppContext) -> bool {
1170 let is_deleted = item.project_entry_ids(cx).is_empty();
1171 item.is_dirty(cx) && !item.has_conflict(cx) && item.can_save(cx) && !is_deleted
1172 }
1173
1174 pub fn autosave_item(
1175 item: &dyn ItemHandle,
1176 project: ModelHandle<Project>,
1177 cx: &mut WindowContext,
1178 ) -> Task<Result<()>> {
1179 if Self::can_autosave_item(item, cx) {
1180 item.save(project, cx)
1181 } else {
1182 Task::ready(Ok(()))
1183 }
1184 }
1185
1186 pub fn focus_active_item(&mut self, cx: &mut ViewContext<Self>) {
1187 if let Some(active_item) = self.active_item() {
1188 cx.focus(active_item.as_any());
1189 }
1190 }
1191
1192 pub fn move_item(
1193 workspace: &mut Workspace,
1194 from: ViewHandle<Pane>,
1195 to: ViewHandle<Pane>,
1196 item_id_to_move: usize,
1197 destination_index: usize,
1198 cx: &mut ViewContext<Workspace>,
1199 ) {
1200 let item_to_move = from
1201 .read(cx)
1202 .items()
1203 .enumerate()
1204 .find(|(_, item_handle)| item_handle.id() == item_id_to_move);
1205
1206 if item_to_move.is_none() {
1207 log::warn!("Tried to move item handle which was not in `from` pane. Maybe tab was closed during drop");
1208 return;
1209 }
1210 let (item_ix, item_handle) = item_to_move.unwrap();
1211 let item_handle = item_handle.clone();
1212
1213 if from != to {
1214 // Close item from previous pane
1215 from.update(cx, |from, cx| {
1216 from.remove_item(item_ix, false, cx);
1217 });
1218 }
1219
1220 // This automatically removes duplicate items in the pane
1221 Pane::add_item(
1222 workspace,
1223 &to,
1224 item_handle,
1225 true,
1226 true,
1227 Some(destination_index),
1228 cx,
1229 );
1230
1231 cx.focus(&to);
1232 }
1233
1234 pub fn split(&mut self, direction: SplitDirection, cx: &mut ViewContext<Self>) {
1235 cx.emit(Event::Split(direction));
1236 }
1237
1238 fn deploy_split_menu(&mut self, _: &DeploySplitMenu, cx: &mut ViewContext<Self>) {
1239 self.tab_bar_context_menu.handle.update(cx, |menu, cx| {
1240 menu.show(
1241 Default::default(),
1242 AnchorCorner::TopRight,
1243 vec![
1244 ContextMenuItem::item("Split Right", SplitRight),
1245 ContextMenuItem::item("Split Left", SplitLeft),
1246 ContextMenuItem::item("Split Up", SplitUp),
1247 ContextMenuItem::item("Split Down", SplitDown),
1248 ],
1249 cx,
1250 );
1251 });
1252
1253 self.tab_bar_context_menu.kind = TabBarContextMenuKind::Split;
1254 }
1255
1256 fn deploy_dock_menu(&mut self, _: &DeployDockMenu, cx: &mut ViewContext<Self>) {
1257 self.tab_bar_context_menu.handle.update(cx, |menu, cx| {
1258 menu.show(
1259 Default::default(),
1260 AnchorCorner::TopRight,
1261 vec![
1262 ContextMenuItem::item("Anchor Dock Right", AnchorDockRight),
1263 ContextMenuItem::item("Anchor Dock Bottom", AnchorDockBottom),
1264 ContextMenuItem::item("Expand Dock", ExpandDock),
1265 ],
1266 cx,
1267 );
1268 });
1269
1270 self.tab_bar_context_menu.kind = TabBarContextMenuKind::Dock;
1271 }
1272
1273 fn deploy_new_menu(&mut self, _: &DeployNewMenu, cx: &mut ViewContext<Self>) {
1274 self.tab_bar_context_menu.handle.update(cx, |menu, cx| {
1275 menu.show(
1276 Default::default(),
1277 AnchorCorner::TopRight,
1278 vec![
1279 ContextMenuItem::item("New File", NewFile),
1280 ContextMenuItem::item("New Terminal", NewTerminal),
1281 ContextMenuItem::item("New Search", NewSearch),
1282 ],
1283 cx,
1284 );
1285 });
1286
1287 self.tab_bar_context_menu.kind = TabBarContextMenuKind::New;
1288 }
1289
1290 fn deploy_tab_context_menu(
1291 &mut self,
1292 action: &DeployTabContextMenu,
1293 cx: &mut ViewContext<Self>,
1294 ) {
1295 let target_item_id = action.item_id;
1296 let target_pane = action.pane.clone();
1297 let active_item_id = self.items[self.active_item_index].id();
1298 let is_active_item = target_item_id == active_item_id;
1299
1300 // The `CloseInactiveItems` action should really be called "CloseOthers" and the behaviour should be dynamically based on the tab the action is ran on. Currenlty, this is a weird action because you can run it on a non-active tab and it will close everything by the actual active tab
1301
1302 self.tab_context_menu.update(cx, |menu, cx| {
1303 menu.show(
1304 action.position,
1305 AnchorCorner::TopLeft,
1306 if is_active_item {
1307 vec![
1308 ContextMenuItem::item("Close Active Item", CloseActiveItem),
1309 ContextMenuItem::item("Close Inactive Items", CloseInactiveItems),
1310 ContextMenuItem::item("Close Clean Items", CloseCleanItems),
1311 ContextMenuItem::item("Close Items To The Left", CloseItemsToTheLeft),
1312 ContextMenuItem::item("Close Items To The Right", CloseItemsToTheRight),
1313 ContextMenuItem::item("Close All Items", CloseAllItems),
1314 ]
1315 } else {
1316 // In the case of the user right clicking on a non-active tab, for some item-closing commands, we need to provide the id of the tab, for the others, we can reuse the existing command.
1317 vec![
1318 ContextMenuItem::item(
1319 "Close Inactive Item",
1320 CloseItemById {
1321 item_id: target_item_id,
1322 pane: target_pane.clone(),
1323 },
1324 ),
1325 ContextMenuItem::item("Close Inactive Items", CloseInactiveItems),
1326 ContextMenuItem::item("Close Clean Items", CloseCleanItems),
1327 ContextMenuItem::item(
1328 "Close Items To The Left",
1329 CloseItemsToTheLeftById {
1330 item_id: target_item_id,
1331 pane: target_pane.clone(),
1332 },
1333 ),
1334 ContextMenuItem::item(
1335 "Close Items To The Right",
1336 CloseItemsToTheRightById {
1337 item_id: target_item_id,
1338 pane: target_pane.clone(),
1339 },
1340 ),
1341 ContextMenuItem::item("Close All Items", CloseAllItems),
1342 ]
1343 },
1344 cx,
1345 );
1346 });
1347 }
1348
1349 pub fn toolbar(&self) -> &ViewHandle<Toolbar> {
1350 &self.toolbar
1351 }
1352
1353 fn update_toolbar(&mut self, cx: &mut ViewContext<Self>) {
1354 let active_item = self
1355 .items
1356 .get(self.active_item_index)
1357 .map(|item| item.as_ref());
1358 self.toolbar.update(cx, |toolbar, cx| {
1359 toolbar.set_active_pane_item(active_item, cx);
1360 });
1361 }
1362
1363 fn render_tabs(&mut self, cx: &mut ViewContext<Self>) -> impl Element<Self> {
1364 let theme = cx.global::<Settings>().theme.clone();
1365
1366 let pane = cx.handle().downgrade();
1367 let autoscroll = if mem::take(&mut self.autoscroll) {
1368 Some(self.active_item_index)
1369 } else {
1370 None
1371 };
1372
1373 let pane_active = self.is_active;
1374
1375 enum Tabs {}
1376 let mut row = Flex::row().scrollable::<Tabs>(1, autoscroll, cx);
1377 for (ix, (item, detail)) in self
1378 .items
1379 .iter()
1380 .cloned()
1381 .zip(self.tab_details(cx))
1382 .enumerate()
1383 {
1384 let detail = if detail == 0 { None } else { Some(detail) };
1385 let tab_active = ix == self.active_item_index;
1386
1387 row.add_child({
1388 enum TabDragReceiver {}
1389 let mut receiver =
1390 dragged_item_receiver::<TabDragReceiver, _, _>(ix, ix, true, None, cx, {
1391 let item = item.clone();
1392 let pane = pane.clone();
1393 let detail = detail.clone();
1394
1395 let theme = cx.global::<Settings>().theme.clone();
1396 let mut tooltip_theme = theme.tooltip.clone();
1397 tooltip_theme.max_text_width = None;
1398 let tab_tooltip_text = item.tab_tooltip_text(cx).map(|a| a.to_string());
1399
1400 move |mouse_state, cx| {
1401 let tab_style =
1402 theme.workspace.tab_bar.tab_style(pane_active, tab_active);
1403 let hovered = mouse_state.hovered();
1404
1405 enum Tab {}
1406 let mouse_event_handler =
1407 MouseEventHandler::<Tab, Pane>::new(ix, cx, |_, cx| {
1408 Self::render_tab(
1409 &item,
1410 pane.clone(),
1411 ix == 0,
1412 detail,
1413 hovered,
1414 tab_style,
1415 cx,
1416 )
1417 })
1418 .on_down(MouseButton::Left, move |_, _, cx| {
1419 cx.dispatch_action(ActivateItem(ix));
1420 })
1421 .on_click(MouseButton::Middle, {
1422 let item = item.clone();
1423 let pane = pane.clone();
1424 move |_, _, cx| {
1425 cx.dispatch_action(CloseItemById {
1426 item_id: item.id(),
1427 pane: pane.clone(),
1428 })
1429 }
1430 })
1431 .on_down(
1432 MouseButton::Right,
1433 move |e, _, cx| {
1434 let item = item.clone();
1435 cx.dispatch_action(DeployTabContextMenu {
1436 position: e.position,
1437 item_id: item.id(),
1438 pane: pane.clone(),
1439 });
1440 },
1441 );
1442
1443 if let Some(tab_tooltip_text) = tab_tooltip_text {
1444 mouse_event_handler
1445 .with_tooltip::<Self>(
1446 ix,
1447 tab_tooltip_text,
1448 None,
1449 tooltip_theme,
1450 cx,
1451 )
1452 .into_any()
1453 } else {
1454 mouse_event_handler.into_any()
1455 }
1456 }
1457 });
1458
1459 if !pane_active || !tab_active {
1460 receiver = receiver.with_cursor_style(CursorStyle::PointingHand);
1461 }
1462
1463 receiver.as_draggable(
1464 DraggedItem {
1465 item,
1466 pane: pane.clone(),
1467 },
1468 {
1469 let theme = cx.global::<Settings>().theme.clone();
1470
1471 let detail = detail.clone();
1472 move |dragged_item: &DraggedItem, cx: &mut ViewContext<Workspace>| {
1473 let tab_style = &theme.workspace.tab_bar.dragged_tab;
1474 Self::render_dragged_tab(
1475 &dragged_item.item,
1476 dragged_item.pane.clone(),
1477 false,
1478 detail,
1479 false,
1480 &tab_style,
1481 cx,
1482 )
1483 }
1484 },
1485 )
1486 })
1487 }
1488
1489 // Use the inactive tab style along with the current pane's active status to decide how to render
1490 // the filler
1491 let filler_index = self.items.len();
1492 let filler_style = theme.workspace.tab_bar.tab_style(pane_active, false);
1493 enum Filler {}
1494 row.add_child(
1495 dragged_item_receiver::<Filler, _, _>(0, filler_index, true, None, cx, |_, _| {
1496 Empty::new()
1497 .contained()
1498 .with_style(filler_style.container)
1499 .with_border(filler_style.container.border)
1500 })
1501 .flex(1., true)
1502 .into_any_named("filler"),
1503 );
1504
1505 row
1506 }
1507
1508 fn tab_details(&self, cx: &AppContext) -> Vec<usize> {
1509 let mut tab_details = (0..self.items.len()).map(|_| 0).collect::<Vec<_>>();
1510
1511 let mut tab_descriptions = HashMap::default();
1512 let mut done = false;
1513 while !done {
1514 done = true;
1515
1516 // Store item indices by their tab description.
1517 for (ix, (item, detail)) in self.items.iter().zip(&tab_details).enumerate() {
1518 if let Some(description) = item.tab_description(*detail, cx) {
1519 if *detail == 0
1520 || Some(&description) != item.tab_description(detail - 1, cx).as_ref()
1521 {
1522 tab_descriptions
1523 .entry(description)
1524 .or_insert(Vec::new())
1525 .push(ix);
1526 }
1527 }
1528 }
1529
1530 // If two or more items have the same tab description, increase their level
1531 // of detail and try again.
1532 for (_, item_ixs) in tab_descriptions.drain() {
1533 if item_ixs.len() > 1 {
1534 done = false;
1535 for ix in item_ixs {
1536 tab_details[ix] += 1;
1537 }
1538 }
1539 }
1540 }
1541
1542 tab_details
1543 }
1544
1545 fn render_tab(
1546 item: &Box<dyn ItemHandle>,
1547 pane: WeakViewHandle<Pane>,
1548 first: bool,
1549 detail: Option<usize>,
1550 hovered: bool,
1551 tab_style: &theme::Tab,
1552 cx: &mut ViewContext<Self>,
1553 ) -> AnyElement<Self> {
1554 let title = item.tab_content(detail, &tab_style, cx);
1555 Self::render_tab_with_title(title, item, pane, first, hovered, tab_style, cx)
1556 }
1557
1558 fn render_dragged_tab(
1559 item: &Box<dyn ItemHandle>,
1560 pane: WeakViewHandle<Pane>,
1561 first: bool,
1562 detail: Option<usize>,
1563 hovered: bool,
1564 tab_style: &theme::Tab,
1565 cx: &mut ViewContext<Workspace>,
1566 ) -> AnyElement<Workspace> {
1567 let title = item.dragged_tab_content(detail, &tab_style, cx);
1568 Self::render_tab_with_title(title, item, pane, first, hovered, tab_style, cx)
1569 }
1570
1571 fn render_tab_with_title<T: View>(
1572 title: AnyElement<T>,
1573 item: &Box<dyn ItemHandle>,
1574 pane: WeakViewHandle<Pane>,
1575 first: bool,
1576 hovered: bool,
1577 tab_style: &theme::Tab,
1578 cx: &mut ViewContext<T>,
1579 ) -> AnyElement<T> {
1580 let mut container = tab_style.container.clone();
1581 if first {
1582 container.border.left = false;
1583 }
1584
1585 Flex::row()
1586 .with_child({
1587 let diameter = 7.0;
1588 let icon_color = if item.has_conflict(cx) {
1589 Some(tab_style.icon_conflict)
1590 } else if item.is_dirty(cx) {
1591 Some(tab_style.icon_dirty)
1592 } else {
1593 None
1594 };
1595
1596 Canvas::new(move |scene, bounds, _, _, _| {
1597 if let Some(color) = icon_color {
1598 let square = RectF::new(bounds.origin(), vec2f(diameter, diameter));
1599 scene.push_quad(Quad {
1600 bounds: square,
1601 background: Some(color),
1602 border: Default::default(),
1603 corner_radius: diameter / 2.,
1604 });
1605 }
1606 })
1607 .constrained()
1608 .with_width(diameter)
1609 .with_height(diameter)
1610 .aligned()
1611 })
1612 .with_child(title.aligned().contained().with_style(ContainerStyle {
1613 margin: Margin {
1614 left: tab_style.spacing,
1615 right: tab_style.spacing,
1616 ..Default::default()
1617 },
1618 ..Default::default()
1619 }))
1620 .with_child(
1621 if hovered {
1622 let item_id = item.id();
1623 enum TabCloseButton {}
1624 let icon = Svg::new("icons/x_mark_8.svg");
1625 MouseEventHandler::<TabCloseButton, _>::new(item_id, cx, |mouse_state, _| {
1626 if mouse_state.hovered() {
1627 icon.with_color(tab_style.icon_close_active)
1628 } else {
1629 icon.with_color(tab_style.icon_close)
1630 }
1631 })
1632 .with_padding(Padding::uniform(4.))
1633 .with_cursor_style(CursorStyle::PointingHand)
1634 .on_click(MouseButton::Left, {
1635 let pane = pane.clone();
1636 move |_, _, cx| {
1637 cx.dispatch_action(CloseItemById {
1638 item_id,
1639 pane: pane.clone(),
1640 })
1641 }
1642 })
1643 .into_any_named("close-tab-icon")
1644 .constrained()
1645 } else {
1646 Empty::new().constrained()
1647 }
1648 .with_width(tab_style.close_icon_width)
1649 .aligned(),
1650 )
1651 .contained()
1652 .with_style(container)
1653 .constrained()
1654 .with_height(tab_style.height)
1655 .into_any()
1656 }
1657
1658 fn render_tab_bar_buttons(
1659 &mut self,
1660 theme: &Theme,
1661 cx: &mut ViewContext<Self>,
1662 ) -> AnyElement<Self> {
1663 Flex::row()
1664 // New menu
1665 .with_child(render_tab_bar_button(
1666 0,
1667 "icons/plus_12.svg",
1668 cx,
1669 DeployNewMenu,
1670 self.tab_bar_context_menu
1671 .handle_if_kind(TabBarContextMenuKind::New),
1672 ))
1673 .with_child(
1674 self.docked
1675 .map(|anchor| {
1676 // Add the dock menu button if this pane is a dock
1677 let dock_icon = icon_for_dock_anchor(anchor);
1678
1679 render_tab_bar_button(
1680 1,
1681 dock_icon,
1682 cx,
1683 DeployDockMenu,
1684 self.tab_bar_context_menu
1685 .handle_if_kind(TabBarContextMenuKind::Dock),
1686 )
1687 })
1688 .unwrap_or_else(|| {
1689 // Add the split menu if this pane is not a dock
1690 render_tab_bar_button(
1691 2,
1692 "icons/split_12.svg",
1693 cx,
1694 DeploySplitMenu,
1695 self.tab_bar_context_menu
1696 .handle_if_kind(TabBarContextMenuKind::Split),
1697 )
1698 }),
1699 )
1700 // Add the close dock button if this pane is a dock
1701 .with_children(
1702 self.docked
1703 .map(|_| render_tab_bar_button(3, "icons/x_mark_8.svg", cx, HideDock, None)),
1704 )
1705 .contained()
1706 .with_style(theme.workspace.tab_bar.pane_button_container)
1707 .flex(1., false)
1708 .into_any()
1709 }
1710
1711 fn render_blank_pane(
1712 &mut self,
1713 theme: &Theme,
1714 _cx: &mut ViewContext<Self>,
1715 ) -> AnyElement<Self> {
1716 let background = theme.workspace.background;
1717 Empty::new()
1718 .contained()
1719 .with_background_color(background)
1720 .into_any()
1721 }
1722}
1723
1724impl Entity for Pane {
1725 type Event = Event;
1726}
1727
1728impl View for Pane {
1729 fn ui_name() -> &'static str {
1730 "Pane"
1731 }
1732
1733 fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
1734 enum MouseNavigationHandler {}
1735
1736 MouseEventHandler::<MouseNavigationHandler, _>::new(0, cx, |_, cx| {
1737 let active_item_index = self.active_item_index;
1738
1739 if let Some(active_item) = self.active_item() {
1740 Flex::column()
1741 .with_child({
1742 let theme = cx.global::<Settings>().theme.clone();
1743
1744 let mut stack = Stack::new();
1745
1746 enum TabBarEventHandler {}
1747 stack.add_child(
1748 MouseEventHandler::<TabBarEventHandler, _>::new(0, cx, |_, _| {
1749 Empty::new()
1750 .contained()
1751 .with_style(theme.workspace.tab_bar.container)
1752 })
1753 .on_down(
1754 MouseButton::Left,
1755 move |_, _, cx| {
1756 cx.dispatch_action(ActivateItem(active_item_index));
1757 },
1758 ),
1759 );
1760
1761 let mut tab_row = Flex::row()
1762 .with_child(self.render_tabs(cx).flex(1., true).into_any_named("tabs"));
1763
1764 if self.is_active {
1765 tab_row.add_child(self.render_tab_bar_buttons(&theme, cx))
1766 }
1767
1768 stack.add_child(tab_row);
1769 stack
1770 .constrained()
1771 .with_height(theme.workspace.tab_bar.height)
1772 .flex(1., false)
1773 .into_any_named("tab bar")
1774 })
1775 .with_child({
1776 enum PaneContentTabDropTarget {}
1777 dragged_item_receiver::<PaneContentTabDropTarget, _, _>(
1778 0,
1779 self.active_item_index + 1,
1780 false,
1781 if self.docked.is_some() {
1782 None
1783 } else {
1784 Some(100.)
1785 },
1786 cx,
1787 {
1788 let toolbar = self.toolbar.clone();
1789 let toolbar_hidden = toolbar.read(cx).hidden();
1790 move |_, cx| {
1791 Flex::column()
1792 .with_children(
1793 (!toolbar_hidden)
1794 .then(|| ChildView::new(&toolbar, cx).expanded()),
1795 )
1796 .with_child(
1797 ChildView::new(active_item.as_any(), cx).flex(1., true),
1798 )
1799 }
1800 },
1801 )
1802 .flex(1., true)
1803 })
1804 .with_child(ChildView::new(&self.tab_context_menu, cx))
1805 .into_any()
1806 } else {
1807 enum EmptyPane {}
1808 let theme = cx.global::<Settings>().theme.clone();
1809
1810 dragged_item_receiver::<EmptyPane, _, _>(0, 0, false, None, cx, |_, cx| {
1811 self.render_blank_pane(&theme, cx)
1812 })
1813 .on_down(MouseButton::Left, |_, _, cx| {
1814 cx.focus_parent_view();
1815 })
1816 .into_any()
1817 }
1818 })
1819 .on_down(
1820 MouseButton::Navigate(NavigationDirection::Back),
1821 move |_, _, cx| {
1822 let pane = cx.weak_handle();
1823 cx.dispatch_action(GoBack { pane: Some(pane) });
1824 },
1825 )
1826 .on_down(MouseButton::Navigate(NavigationDirection::Forward), {
1827 move |_, _, cx| {
1828 let pane = cx.weak_handle();
1829 cx.dispatch_action(GoForward { pane: Some(pane) })
1830 }
1831 })
1832 .into_any_named("pane")
1833 }
1834
1835 fn focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
1836 self.toolbar.update(cx, |toolbar, cx| {
1837 toolbar.pane_focus_update(true, cx);
1838 });
1839
1840 if let Some(active_item) = self.active_item() {
1841 if cx.is_self_focused() {
1842 // Pane was focused directly. We need to either focus a view inside the active item,
1843 // or focus the active item itself
1844 if let Some(weak_last_focused_view) =
1845 self.last_focused_view_by_item.get(&active_item.id())
1846 {
1847 if let Some(last_focused_view) = weak_last_focused_view.upgrade(cx) {
1848 cx.focus(&last_focused_view);
1849 return;
1850 } else {
1851 self.last_focused_view_by_item.remove(&active_item.id());
1852 }
1853 }
1854
1855 cx.focus(active_item.as_any());
1856 } else if focused != self.tab_bar_context_menu.handle {
1857 self.last_focused_view_by_item
1858 .insert(active_item.id(), focused.downgrade());
1859 }
1860 }
1861 }
1862
1863 fn focus_out(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
1864 self.toolbar.update(cx, |toolbar, cx| {
1865 toolbar.pane_focus_update(false, cx);
1866 });
1867 }
1868
1869 fn keymap_context(&self, _: &AppContext) -> KeymapContext {
1870 let mut keymap = Self::default_keymap_context();
1871 if self.docked.is_some() {
1872 keymap.add_identifier("docked");
1873 }
1874 keymap
1875 }
1876}
1877
1878fn render_tab_bar_button<A: Action + Clone>(
1879 index: usize,
1880 icon: &'static str,
1881 cx: &mut ViewContext<Pane>,
1882 action: A,
1883 context_menu: Option<ViewHandle<ContextMenu>>,
1884) -> AnyElement<Pane> {
1885 enum TabBarButton {}
1886
1887 Stack::new()
1888 .with_child(
1889 MouseEventHandler::<TabBarButton, _>::new(index, cx, |mouse_state, cx| {
1890 let theme = &cx.global::<Settings>().theme.workspace.tab_bar;
1891 let style = theme.pane_button.style_for(mouse_state, false);
1892 Svg::new(icon)
1893 .with_color(style.color)
1894 .constrained()
1895 .with_width(style.icon_width)
1896 .aligned()
1897 .constrained()
1898 .with_width(style.button_width)
1899 .with_height(style.button_width)
1900 })
1901 .with_cursor_style(CursorStyle::PointingHand)
1902 .on_click(MouseButton::Left, move |_, _, cx| {
1903 cx.dispatch_action(action.clone());
1904 }),
1905 )
1906 .with_children(
1907 context_menu.map(|menu| ChildView::new(&menu, cx).aligned().bottom().right()),
1908 )
1909 .flex(1., false)
1910 .into_any_named("tab bar button")
1911}
1912
1913impl ItemNavHistory {
1914 pub fn push<D: 'static + Any>(&self, data: Option<D>, cx: &mut WindowContext) {
1915 self.history.borrow_mut().push(data, self.item.clone(), cx);
1916 }
1917
1918 pub fn pop_backward(&self, cx: &mut WindowContext) -> Option<NavigationEntry> {
1919 self.history.borrow_mut().pop(NavigationMode::GoingBack, cx)
1920 }
1921
1922 pub fn pop_forward(&self, cx: &mut WindowContext) -> Option<NavigationEntry> {
1923 self.history
1924 .borrow_mut()
1925 .pop(NavigationMode::GoingForward, cx)
1926 }
1927}
1928
1929impl NavHistory {
1930 fn set_mode(&mut self, mode: NavigationMode) {
1931 self.mode = mode;
1932 }
1933
1934 fn disable(&mut self) {
1935 self.mode = NavigationMode::Disabled;
1936 }
1937
1938 fn enable(&mut self) {
1939 self.mode = NavigationMode::Normal;
1940 }
1941
1942 fn pop(&mut self, mode: NavigationMode, cx: &mut WindowContext) -> Option<NavigationEntry> {
1943 let entry = match mode {
1944 NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
1945 return None
1946 }
1947 NavigationMode::GoingBack => &mut self.backward_stack,
1948 NavigationMode::GoingForward => &mut self.forward_stack,
1949 NavigationMode::ReopeningClosedItem => &mut self.closed_stack,
1950 }
1951 .pop_back();
1952 if entry.is_some() {
1953 self.did_update(cx);
1954 }
1955 entry
1956 }
1957
1958 fn push<D: 'static + Any>(
1959 &mut self,
1960 data: Option<D>,
1961 item: Rc<dyn WeakItemHandle>,
1962 cx: &mut WindowContext,
1963 ) {
1964 match self.mode {
1965 NavigationMode::Disabled => {}
1966 NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
1967 if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1968 self.backward_stack.pop_front();
1969 }
1970 self.backward_stack.push_back(NavigationEntry {
1971 item,
1972 data: data.map(|data| Box::new(data) as Box<dyn Any>),
1973 });
1974 self.forward_stack.clear();
1975 }
1976 NavigationMode::GoingBack => {
1977 if self.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1978 self.forward_stack.pop_front();
1979 }
1980 self.forward_stack.push_back(NavigationEntry {
1981 item,
1982 data: data.map(|data| Box::new(data) as Box<dyn Any>),
1983 });
1984 }
1985 NavigationMode::GoingForward => {
1986 if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1987 self.backward_stack.pop_front();
1988 }
1989 self.backward_stack.push_back(NavigationEntry {
1990 item,
1991 data: data.map(|data| Box::new(data) as Box<dyn Any>),
1992 });
1993 }
1994 NavigationMode::ClosingItem => {
1995 if self.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1996 self.closed_stack.pop_front();
1997 }
1998 self.closed_stack.push_back(NavigationEntry {
1999 item,
2000 data: data.map(|data| Box::new(data) as Box<dyn Any>),
2001 });
2002 }
2003 }
2004 self.did_update(cx);
2005 }
2006
2007 fn did_update(&self, cx: &mut WindowContext) {
2008 if let Some(pane) = self.pane.upgrade(cx) {
2009 cx.defer(move |cx| {
2010 pane.update(cx, |pane, cx| pane.history_updated(cx));
2011 });
2012 }
2013 }
2014}
2015
2016pub struct PaneBackdrop<V: View> {
2017 child_view: usize,
2018 child: AnyElement<V>,
2019}
2020
2021impl<V: View> PaneBackdrop<V> {
2022 pub fn new(pane_item_view: usize, child: AnyElement<V>) -> Self {
2023 PaneBackdrop {
2024 child,
2025 child_view: pane_item_view,
2026 }
2027 }
2028}
2029
2030impl<V: View> Element<V> for PaneBackdrop<V> {
2031 type LayoutState = ();
2032
2033 type PaintState = ();
2034
2035 fn layout(
2036 &mut self,
2037 constraint: gpui::SizeConstraint,
2038 view: &mut V,
2039 cx: &mut ViewContext<V>,
2040 ) -> (Vector2F, Self::LayoutState) {
2041 let size = self.child.layout(constraint, view, cx);
2042 (size, ())
2043 }
2044
2045 fn paint(
2046 &mut self,
2047 scene: &mut gpui::SceneBuilder,
2048 bounds: RectF,
2049 visible_bounds: RectF,
2050 _: &mut Self::LayoutState,
2051 view: &mut V,
2052 cx: &mut ViewContext<V>,
2053 ) -> Self::PaintState {
2054 let background = cx.global::<Settings>().theme.editor.background;
2055
2056 let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
2057
2058 scene.push_quad(gpui::Quad {
2059 bounds: RectF::new(bounds.origin(), bounds.size()),
2060 background: Some(background),
2061 ..Default::default()
2062 });
2063
2064 let child_view_id = self.child_view;
2065 scene.push_mouse_region(
2066 MouseRegion::new::<Self>(child_view_id, 0, visible_bounds).on_down(
2067 gpui::platform::MouseButton::Left,
2068 move |_, _: &mut V, cx| {
2069 let window_id = cx.window_id();
2070 cx.app_context().focus(window_id, Some(child_view_id))
2071 },
2072 ),
2073 );
2074
2075 scene.paint_layer(Some(bounds), |scene| {
2076 self.child
2077 .paint(scene, bounds.origin(), visible_bounds, view, cx)
2078 })
2079 }
2080
2081 fn rect_for_text_range(
2082 &self,
2083 range_utf16: std::ops::Range<usize>,
2084 _bounds: RectF,
2085 _visible_bounds: RectF,
2086 _layout: &Self::LayoutState,
2087 _paint: &Self::PaintState,
2088 view: &V,
2089 cx: &gpui::ViewContext<V>,
2090 ) -> Option<RectF> {
2091 self.child.rect_for_text_range(range_utf16, view, cx)
2092 }
2093
2094 fn debug(
2095 &self,
2096 _bounds: RectF,
2097 _layout: &Self::LayoutState,
2098 _paint: &Self::PaintState,
2099 view: &V,
2100 cx: &gpui::ViewContext<V>,
2101 ) -> serde_json::Value {
2102 gpui::json::json!({
2103 "type": "Pane Back Drop",
2104 "view": self.child_view,
2105 "child": self.child.debug(view, cx),
2106 })
2107 }
2108}
2109
2110#[cfg(test)]
2111mod tests {
2112 use std::sync::Arc;
2113
2114 use super::*;
2115 use crate::item::test::{TestItem, TestProjectItem};
2116 use gpui::{executor::Deterministic, TestAppContext};
2117 use project::FakeFs;
2118
2119 #[gpui::test]
2120 async fn test_remove_active_empty(cx: &mut TestAppContext) {
2121 Settings::test_async(cx);
2122 let fs = FakeFs::new(cx.background());
2123
2124 let project = Project::test(fs, None, cx).await;
2125 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2126
2127 workspace.update(cx, |workspace, cx| {
2128 assert!(Pane::close_active_item(workspace, &CloseActiveItem, cx).is_none())
2129 });
2130 }
2131
2132 #[gpui::test]
2133 async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
2134 cx.foreground().forbid_parking();
2135 Settings::test_async(cx);
2136 let fs = FakeFs::new(cx.background());
2137
2138 let project = Project::test(fs, None, cx).await;
2139 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2140 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2141
2142 // 1. Add with a destination index
2143 // a. Add before the active item
2144 set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
2145 workspace.update(cx, |workspace, cx| {
2146 Pane::add_item(
2147 workspace,
2148 &pane,
2149 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2150 false,
2151 false,
2152 Some(0),
2153 cx,
2154 );
2155 });
2156 assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2157
2158 // b. Add after the active item
2159 set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
2160 workspace.update(cx, |workspace, cx| {
2161 Pane::add_item(
2162 workspace,
2163 &pane,
2164 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2165 false,
2166 false,
2167 Some(2),
2168 cx,
2169 );
2170 });
2171 assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2172
2173 // c. Add at the end of the item list (including off the length)
2174 set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
2175 workspace.update(cx, |workspace, cx| {
2176 Pane::add_item(
2177 workspace,
2178 &pane,
2179 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2180 false,
2181 false,
2182 Some(5),
2183 cx,
2184 );
2185 });
2186 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2187
2188 // 2. Add without a destination index
2189 // a. Add with active item at the start of the item list
2190 set_labeled_items(&workspace, &pane, ["A*", "B", "C"], cx);
2191 workspace.update(cx, |workspace, cx| {
2192 Pane::add_item(
2193 workspace,
2194 &pane,
2195 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2196 false,
2197 false,
2198 None,
2199 cx,
2200 );
2201 });
2202 set_labeled_items(&workspace, &pane, ["A", "D*", "B", "C"], cx);
2203
2204 // b. Add with active item at the end of the item list
2205 set_labeled_items(&workspace, &pane, ["A", "B", "C*"], cx);
2206 workspace.update(cx, |workspace, cx| {
2207 Pane::add_item(
2208 workspace,
2209 &pane,
2210 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2211 false,
2212 false,
2213 None,
2214 cx,
2215 );
2216 });
2217 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2218 }
2219
2220 #[gpui::test]
2221 async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
2222 cx.foreground().forbid_parking();
2223 Settings::test_async(cx);
2224 let fs = FakeFs::new(cx.background());
2225
2226 let project = Project::test(fs, None, cx).await;
2227 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2228 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2229
2230 // 1. Add with a destination index
2231 // 1a. Add before the active item
2232 let [_, _, _, d] = set_labeled_items(&workspace, &pane, ["A", "B*", "C", "D"], cx);
2233 workspace.update(cx, |workspace, cx| {
2234 Pane::add_item(workspace, &pane, d, false, false, Some(0), cx);
2235 });
2236 assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2237
2238 // 1b. Add after the active item
2239 let [_, _, _, d] = set_labeled_items(&workspace, &pane, ["A", "B*", "C", "D"], cx);
2240 workspace.update(cx, |workspace, cx| {
2241 Pane::add_item(workspace, &pane, d, false, false, Some(2), cx);
2242 });
2243 assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2244
2245 // 1c. Add at the end of the item list (including off the length)
2246 let [a, _, _, _] = set_labeled_items(&workspace, &pane, ["A", "B*", "C", "D"], cx);
2247 workspace.update(cx, |workspace, cx| {
2248 Pane::add_item(workspace, &pane, a, false, false, Some(5), cx);
2249 });
2250 assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2251
2252 // 1d. Add same item to active index
2253 let [_, b, _] = set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
2254 workspace.update(cx, |workspace, cx| {
2255 Pane::add_item(workspace, &pane, b, false, false, Some(1), cx);
2256 });
2257 assert_item_labels(&pane, ["A", "B*", "C"], cx);
2258
2259 // 1e. Add item to index after same item in last position
2260 let [_, _, c] = set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
2261 workspace.update(cx, |workspace, cx| {
2262 Pane::add_item(workspace, &pane, c, false, false, Some(2), cx);
2263 });
2264 assert_item_labels(&pane, ["A", "B", "C*"], cx);
2265
2266 // 2. Add without a destination index
2267 // 2a. Add with active item at the start of the item list
2268 let [_, _, _, d] = set_labeled_items(&workspace, &pane, ["A*", "B", "C", "D"], cx);
2269 workspace.update(cx, |workspace, cx| {
2270 Pane::add_item(workspace, &pane, d, false, false, None, cx);
2271 });
2272 assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
2273
2274 // 2b. Add with active item at the end of the item list
2275 let [a, _, _, _] = set_labeled_items(&workspace, &pane, ["A", "B", "C", "D*"], cx);
2276 workspace.update(cx, |workspace, cx| {
2277 Pane::add_item(workspace, &pane, a, false, false, None, cx);
2278 });
2279 assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2280
2281 // 2c. Add active item to active item at end of list
2282 let [_, _, c] = set_labeled_items(&workspace, &pane, ["A", "B", "C*"], cx);
2283 workspace.update(cx, |workspace, cx| {
2284 Pane::add_item(workspace, &pane, c, false, false, None, cx);
2285 });
2286 assert_item_labels(&pane, ["A", "B", "C*"], cx);
2287
2288 // 2d. Add active item to active item at start of list
2289 let [a, _, _] = set_labeled_items(&workspace, &pane, ["A*", "B", "C"], cx);
2290 workspace.update(cx, |workspace, cx| {
2291 Pane::add_item(workspace, &pane, a, false, false, None, cx);
2292 });
2293 assert_item_labels(&pane, ["A*", "B", "C"], cx);
2294 }
2295
2296 #[gpui::test]
2297 async fn test_add_item_with_same_project_entries(cx: &mut TestAppContext) {
2298 cx.foreground().forbid_parking();
2299 Settings::test_async(cx);
2300 let fs = FakeFs::new(cx.background());
2301
2302 let project = Project::test(fs, None, cx).await;
2303 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2304 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2305
2306 // singleton view
2307 workspace.update(cx, |workspace, cx| {
2308 let item = TestItem::new()
2309 .with_singleton(true)
2310 .with_label("buffer 1")
2311 .with_project_items(&[TestProjectItem::new(1, "one.txt", cx)]);
2312
2313 Pane::add_item(
2314 workspace,
2315 &pane,
2316 Box::new(cx.add_view(|_| item)),
2317 false,
2318 false,
2319 None,
2320 cx,
2321 );
2322 });
2323 assert_item_labels(&pane, ["buffer 1*"], cx);
2324
2325 // new singleton view with the same project entry
2326 workspace.update(cx, |workspace, cx| {
2327 let item = TestItem::new()
2328 .with_singleton(true)
2329 .with_label("buffer 1")
2330 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2331
2332 Pane::add_item(
2333 workspace,
2334 &pane,
2335 Box::new(cx.add_view(|_| item)),
2336 false,
2337 false,
2338 None,
2339 cx,
2340 );
2341 });
2342 assert_item_labels(&pane, ["buffer 1*"], cx);
2343
2344 // new singleton view with different project entry
2345 workspace.update(cx, |workspace, cx| {
2346 let item = TestItem::new()
2347 .with_singleton(true)
2348 .with_label("buffer 2")
2349 .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)]);
2350
2351 Pane::add_item(
2352 workspace,
2353 &pane,
2354 Box::new(cx.add_view(|_| item)),
2355 false,
2356 false,
2357 None,
2358 cx,
2359 );
2360 });
2361 assert_item_labels(&pane, ["buffer 1", "buffer 2*"], cx);
2362
2363 // new multibuffer view with the same project entry
2364 workspace.update(cx, |workspace, cx| {
2365 let item = TestItem::new()
2366 .with_singleton(false)
2367 .with_label("multibuffer 1")
2368 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2369
2370 Pane::add_item(
2371 workspace,
2372 &pane,
2373 Box::new(cx.add_view(|_| item)),
2374 false,
2375 false,
2376 None,
2377 cx,
2378 );
2379 });
2380 assert_item_labels(&pane, ["buffer 1", "buffer 2", "multibuffer 1*"], cx);
2381
2382 // another multibuffer view with the same project entry
2383 workspace.update(cx, |workspace, cx| {
2384 let item = TestItem::new()
2385 .with_singleton(false)
2386 .with_label("multibuffer 1b")
2387 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2388
2389 Pane::add_item(
2390 workspace,
2391 &pane,
2392 Box::new(cx.add_view(|_| item)),
2393 false,
2394 false,
2395 None,
2396 cx,
2397 );
2398 });
2399 assert_item_labels(
2400 &pane,
2401 ["buffer 1", "buffer 2", "multibuffer 1", "multibuffer 1b*"],
2402 cx,
2403 );
2404 }
2405
2406 #[gpui::test]
2407 async fn test_remove_item_ordering(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
2408 Settings::test_async(cx);
2409 let fs = FakeFs::new(cx.background());
2410
2411 let project = Project::test(fs, None, cx).await;
2412 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2413 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2414
2415 add_labeled_item(&workspace, &pane, "A", false, cx);
2416 add_labeled_item(&workspace, &pane, "B", false, cx);
2417 add_labeled_item(&workspace, &pane, "C", false, cx);
2418 add_labeled_item(&workspace, &pane, "D", false, cx);
2419 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2420
2421 pane.update(cx, |pane, cx| pane.activate_item(1, false, false, cx));
2422 add_labeled_item(&workspace, &pane, "1", false, cx);
2423 assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
2424
2425 workspace.update(cx, |workspace, cx| {
2426 Pane::close_active_item(workspace, &CloseActiveItem, cx);
2427 });
2428 deterministic.run_until_parked();
2429 assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
2430
2431 pane.update(cx, |pane, cx| pane.activate_item(3, false, false, cx));
2432 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2433
2434 workspace.update(cx, |workspace, cx| {
2435 Pane::close_active_item(workspace, &CloseActiveItem, cx);
2436 });
2437 deterministic.run_until_parked();
2438 assert_item_labels(&pane, ["A", "B*", "C"], cx);
2439
2440 workspace.update(cx, |workspace, cx| {
2441 Pane::close_active_item(workspace, &CloseActiveItem, cx);
2442 });
2443 deterministic.run_until_parked();
2444 assert_item_labels(&pane, ["A", "C*"], cx);
2445
2446 workspace.update(cx, |workspace, cx| {
2447 Pane::close_active_item(workspace, &CloseActiveItem, cx);
2448 });
2449 deterministic.run_until_parked();
2450 assert_item_labels(&pane, ["A*"], cx);
2451 }
2452
2453 #[gpui::test]
2454 async fn test_close_inactive_items(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
2455 Settings::test_async(cx);
2456 let fs = FakeFs::new(cx.background());
2457
2458 let project = Project::test(fs, None, cx).await;
2459 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2460 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2461
2462 set_labeled_items(&workspace, &pane, ["A", "B", "C*", "D", "E"], cx);
2463
2464 workspace.update(cx, |workspace, cx| {
2465 Pane::close_inactive_items(workspace, &CloseInactiveItems, cx);
2466 });
2467
2468 deterministic.run_until_parked();
2469 assert_item_labels(&pane, ["C*"], cx);
2470 }
2471
2472 #[gpui::test]
2473 async fn test_close_clean_items(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
2474 Settings::test_async(cx);
2475 let fs = FakeFs::new(cx.background());
2476
2477 let project = Project::test(fs, None, cx).await;
2478 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2479 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2480
2481 add_labeled_item(&workspace, &pane, "A", true, cx);
2482 add_labeled_item(&workspace, &pane, "B", false, cx);
2483 add_labeled_item(&workspace, &pane, "C", true, cx);
2484 add_labeled_item(&workspace, &pane, "D", false, cx);
2485 add_labeled_item(&workspace, &pane, "E", false, cx);
2486 assert_item_labels(&pane, ["A^", "B", "C^", "D", "E*"], cx);
2487
2488 workspace.update(cx, |workspace, cx| {
2489 Pane::close_clean_items(workspace, &CloseCleanItems, cx);
2490 });
2491
2492 deterministic.run_until_parked();
2493 assert_item_labels(&pane, ["A^", "C*^"], cx);
2494 }
2495
2496 #[gpui::test]
2497 async fn test_close_items_to_the_left(
2498 deterministic: Arc<Deterministic>,
2499 cx: &mut TestAppContext,
2500 ) {
2501 Settings::test_async(cx);
2502 let fs = FakeFs::new(cx.background());
2503
2504 let project = Project::test(fs, None, cx).await;
2505 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2506 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2507
2508 set_labeled_items(&workspace, &pane, ["A", "B", "C*", "D", "E"], cx);
2509
2510 workspace.update(cx, |workspace, cx| {
2511 Pane::close_items_to_the_left(workspace, &CloseItemsToTheLeft, cx);
2512 });
2513
2514 deterministic.run_until_parked();
2515 assert_item_labels(&pane, ["C*", "D", "E"], cx);
2516 }
2517
2518 #[gpui::test]
2519 async fn test_close_items_to_the_right(
2520 deterministic: Arc<Deterministic>,
2521 cx: &mut TestAppContext,
2522 ) {
2523 Settings::test_async(cx);
2524 let fs = FakeFs::new(cx.background());
2525
2526 let project = Project::test(fs, None, cx).await;
2527 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2528 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2529
2530 set_labeled_items(&workspace, &pane, ["A", "B", "C*", "D", "E"], cx);
2531
2532 workspace.update(cx, |workspace, cx| {
2533 Pane::close_items_to_the_right(workspace, &CloseItemsToTheRight, cx);
2534 });
2535
2536 deterministic.run_until_parked();
2537 assert_item_labels(&pane, ["A", "B", "C*"], cx);
2538 }
2539
2540 #[gpui::test]
2541 async fn test_close_all_items(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
2542 Settings::test_async(cx);
2543 let fs = FakeFs::new(cx.background());
2544
2545 let project = Project::test(fs, None, cx).await;
2546 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2547 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2548
2549 add_labeled_item(&workspace, &pane, "A", false, cx);
2550 add_labeled_item(&workspace, &pane, "B", false, cx);
2551 add_labeled_item(&workspace, &pane, "C", false, cx);
2552 assert_item_labels(&pane, ["A", "B", "C*"], cx);
2553
2554 workspace.update(cx, |workspace, cx| {
2555 Pane::close_all_items(workspace, &CloseAllItems, cx);
2556 });
2557
2558 deterministic.run_until_parked();
2559 assert_item_labels(&pane, [], cx);
2560 }
2561
2562 fn add_labeled_item(
2563 workspace: &ViewHandle<Workspace>,
2564 pane: &ViewHandle<Pane>,
2565 label: &str,
2566 is_dirty: bool,
2567 cx: &mut TestAppContext,
2568 ) -> Box<ViewHandle<TestItem>> {
2569 workspace.update(cx, |workspace, cx| {
2570 let labeled_item =
2571 Box::new(cx.add_view(|_| TestItem::new().with_label(label).with_dirty(is_dirty)));
2572
2573 Pane::add_item(
2574 workspace,
2575 pane,
2576 labeled_item.clone(),
2577 false,
2578 false,
2579 None,
2580 cx,
2581 );
2582
2583 labeled_item
2584 })
2585 }
2586
2587 fn set_labeled_items<const COUNT: usize>(
2588 workspace: &ViewHandle<Workspace>,
2589 pane: &ViewHandle<Pane>,
2590 labels: [&str; COUNT],
2591 cx: &mut TestAppContext,
2592 ) -> [Box<ViewHandle<TestItem>>; COUNT] {
2593 pane.update(cx, |pane, _| {
2594 pane.items.clear();
2595 });
2596
2597 workspace.update(cx, |workspace, cx| {
2598 let mut active_item_index = 0;
2599
2600 let mut index = 0;
2601 let items = labels.map(|mut label| {
2602 if label.ends_with("*") {
2603 label = label.trim_end_matches("*");
2604 active_item_index = index;
2605 }
2606
2607 let labeled_item = Box::new(cx.add_view(|_| TestItem::new().with_label(label)));
2608 Pane::add_item(
2609 workspace,
2610 pane,
2611 labeled_item.clone(),
2612 false,
2613 false,
2614 None,
2615 cx,
2616 );
2617 index += 1;
2618 labeled_item
2619 });
2620
2621 pane.update(cx, |pane, cx| {
2622 pane.activate_item(active_item_index, false, false, cx)
2623 });
2624
2625 items
2626 })
2627 }
2628
2629 // Assert the item label, with the active item label suffixed with a '*'
2630 fn assert_item_labels<const COUNT: usize>(
2631 pane: &ViewHandle<Pane>,
2632 expected_states: [&str; COUNT],
2633 cx: &mut TestAppContext,
2634 ) {
2635 pane.read_with(cx, |pane, cx| {
2636 let actual_states = pane
2637 .items
2638 .iter()
2639 .enumerate()
2640 .map(|(ix, item)| {
2641 let mut state = item
2642 .as_any()
2643 .downcast_ref::<TestItem>()
2644 .unwrap()
2645 .read(cx)
2646 .label
2647 .clone();
2648 if ix == pane.active_item_index {
2649 state.push('*');
2650 }
2651 if item.is_dirty(cx) {
2652 state.push('^');
2653 }
2654 state
2655 })
2656 .collect::<Vec<_>>();
2657
2658 assert_eq!(
2659 actual_states, expected_states,
2660 "pane items do not match expectation"
2661 );
2662 })
2663 }
2664}