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