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