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