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