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