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 )
1602 .start_child(
1603 IconButton::new("navigate_forward", Icon::ArrowRight)
1604 .icon_size(IconSize::Small)
1605 .on_click({
1606 let view = cx.view().clone();
1607 move |_, cx| view.update(cx, Self::navigate_backward)
1608 })
1609 .disabled(!self.can_navigate_forward()),
1610 )
1611 .end_child(
1612 div()
1613 .child(
1614 IconButton::new("plus", Icon::Plus)
1615 .icon_size(IconSize::Small)
1616 .on_click(cx.listener(|this, _, cx| {
1617 let menu = ContextMenu::build(cx, |menu, cx| {
1618 menu.action("New File", NewFile.boxed_clone())
1619 .action("New Terminal", NewCenterTerminal.boxed_clone())
1620 .action("New Search", NewSearch.boxed_clone())
1621 });
1622 cx.subscribe(&menu, |this, _, event: &DismissEvent, cx| {
1623 this.focus(cx);
1624 this.new_item_menu = None;
1625 })
1626 .detach();
1627 this.new_item_menu = Some(menu);
1628 })),
1629 )
1630 .when_some(self.new_item_menu.as_ref(), |el, new_item_menu| {
1631 el.child(Self::render_menu_overlay(new_item_menu))
1632 }),
1633 )
1634 .end_child(
1635 div()
1636 .child(
1637 IconButton::new("split", Icon::Split)
1638 .icon_size(IconSize::Small)
1639 .on_click(cx.listener(|this, _, cx| {
1640 let menu = ContextMenu::build(cx, |menu, cx| {
1641 menu.action("Split Right", SplitRight.boxed_clone())
1642 .action("Split Left", SplitLeft.boxed_clone())
1643 .action("Split Up", SplitUp.boxed_clone())
1644 .action("Split Down", SplitDown.boxed_clone())
1645 });
1646 cx.subscribe(&menu, |this, _, event: &DismissEvent, cx| {
1647 this.focus(cx);
1648 this.split_item_menu = None;
1649 })
1650 .detach();
1651 this.split_item_menu = Some(menu);
1652 })),
1653 )
1654 .when_some(self.split_item_menu.as_ref(), |el, split_item_menu| {
1655 el.child(Self::render_menu_overlay(split_item_menu))
1656 }),
1657 )
1658 .children(
1659 self.items
1660 .iter()
1661 .enumerate()
1662 .zip(self.tab_details(cx))
1663 .map(|((ix, item), detail)| self.render_tab(ix, item, detail, cx)),
1664 )
1665 .child(
1666 div()
1667 .h_full()
1668 .flex_grow()
1669 .drag_over::<DraggedTab>(|bar| {
1670 bar.bg(cx.theme().colors().tab_active_background)
1671 })
1672 .on_drop(
1673 cx.listener(move |this, dragged_tab: &View<DraggedTab>, cx| {
1674 this.handle_tab_drop(dragged_tab, this.items.len(), cx)
1675 }),
1676 ),
1677 )
1678 }
1679
1680 fn render_menu_overlay(menu: &View<ContextMenu>) -> Div {
1681 div()
1682 .absolute()
1683 .z_index(1)
1684 .bottom_0()
1685 .right_0()
1686 .size_0()
1687 .child(overlay().anchor(AnchorCorner::TopRight).child(menu.clone()))
1688 }
1689
1690 fn tab_details(&self, cx: &AppContext) -> Vec<usize> {
1691 let mut tab_details = self.items.iter().map(|_| 0).collect::<Vec<_>>();
1692
1693 let mut tab_descriptions = HashMap::default();
1694 let mut done = false;
1695 while !done {
1696 done = true;
1697
1698 // Store item indices by their tab description.
1699 for (ix, (item, detail)) in self.items.iter().zip(&tab_details).enumerate() {
1700 if let Some(description) = item.tab_description(*detail, cx) {
1701 if *detail == 0
1702 || Some(&description) != item.tab_description(detail - 1, cx).as_ref()
1703 {
1704 tab_descriptions
1705 .entry(description)
1706 .or_insert(Vec::new())
1707 .push(ix);
1708 }
1709 }
1710 }
1711
1712 // If two or more items have the same tab description, increase eir level
1713 // of detail and try again.
1714 for (_, item_ixs) in tab_descriptions.drain() {
1715 if item_ixs.len() > 1 {
1716 done = false;
1717 for ix in item_ixs {
1718 tab_details[ix] += 1;
1719 }
1720 }
1721 }
1722 }
1723
1724 tab_details
1725 }
1726
1727 pub fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
1728 self.zoomed = zoomed;
1729 cx.notify();
1730 }
1731
1732 pub fn is_zoomed(&self) -> bool {
1733 self.zoomed
1734 }
1735
1736 fn handle_tab_drop(
1737 &mut self,
1738 dragged_tab: &View<DraggedTab>,
1739 ix: usize,
1740 cx: &mut ViewContext<'_, Pane>,
1741 ) {
1742 let dragged_tab = dragged_tab.read(cx);
1743 let item_id = dragged_tab.item_id;
1744 let from_pane = dragged_tab.pane.clone();
1745 let to_pane = cx.view().clone();
1746 self.workspace
1747 .update(cx, |workspace, cx| {
1748 cx.defer(move |workspace, cx| {
1749 workspace.move_item(from_pane, to_pane, item_id, ix, cx);
1750 });
1751 })
1752 .log_err();
1753 }
1754}
1755
1756impl FocusableView for Pane {
1757 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
1758 self.focus_handle.clone()
1759 }
1760}
1761
1762impl Render for Pane {
1763 type Element = Focusable<Div>;
1764
1765 fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
1766 let this = cx.view().downgrade();
1767
1768 v_stack()
1769 .key_context("Pane")
1770 .track_focus(&self.focus_handle)
1771 .size_full()
1772 .flex_none()
1773 .overflow_hidden()
1774 .on_action(cx.listener(|pane, _: &SplitLeft, cx| pane.split(SplitDirection::Left, cx)))
1775 .on_action(cx.listener(|pane, _: &SplitUp, cx| pane.split(SplitDirection::Up, cx)))
1776 .on_action(
1777 cx.listener(|pane, _: &SplitRight, cx| pane.split(SplitDirection::Right, cx)),
1778 )
1779 .on_action(cx.listener(|pane, _: &SplitDown, cx| pane.split(SplitDirection::Down, cx)))
1780 .on_action(cx.listener(|pane, _: &GoBack, cx| pane.navigate_backward(cx)))
1781 .on_action(cx.listener(|pane, _: &GoForward, cx| pane.navigate_forward(cx)))
1782 .on_action(cx.listener(Pane::toggle_zoom))
1783 .on_action(cx.listener(|pane: &mut Pane, action: &ActivateItem, cx| {
1784 pane.activate_item(action.0, true, true, cx);
1785 }))
1786 .on_action(cx.listener(|pane: &mut Pane, _: &ActivateLastItem, cx| {
1787 pane.activate_item(pane.items.len() - 1, true, true, cx);
1788 }))
1789 .on_action(cx.listener(|pane: &mut Pane, _: &ActivatePrevItem, cx| {
1790 pane.activate_prev_item(true, cx);
1791 }))
1792 .on_action(cx.listener(|pane: &mut Pane, _: &ActivateNextItem, cx| {
1793 pane.activate_next_item(true, cx);
1794 }))
1795 .on_action(
1796 cx.listener(|pane: &mut Self, action: &CloseActiveItem, cx| {
1797 pane.close_active_item(action, cx)
1798 .map(|task| task.detach_and_log_err(cx));
1799 }),
1800 )
1801 .on_action(
1802 cx.listener(|pane: &mut Self, action: &CloseInactiveItems, cx| {
1803 pane.close_inactive_items(action, cx)
1804 .map(|task| task.detach_and_log_err(cx));
1805 }),
1806 )
1807 .on_action(
1808 cx.listener(|pane: &mut Self, action: &CloseCleanItems, cx| {
1809 pane.close_clean_items(action, cx)
1810 .map(|task| task.detach_and_log_err(cx));
1811 }),
1812 )
1813 .on_action(
1814 cx.listener(|pane: &mut Self, action: &CloseItemsToTheLeft, cx| {
1815 pane.close_items_to_the_left(action, cx)
1816 .map(|task| task.detach_and_log_err(cx));
1817 }),
1818 )
1819 .on_action(
1820 cx.listener(|pane: &mut Self, action: &CloseItemsToTheRight, cx| {
1821 pane.close_items_to_the_right(action, cx)
1822 .map(|task| task.detach_and_log_err(cx));
1823 }),
1824 )
1825 .on_action(cx.listener(|pane: &mut Self, action: &CloseAllItems, cx| {
1826 pane.close_all_items(action, cx)
1827 .map(|task| task.detach_and_log_err(cx));
1828 }))
1829 .on_action(
1830 cx.listener(|pane: &mut Self, action: &CloseActiveItem, cx| {
1831 pane.close_active_item(action, cx)
1832 .map(|task| task.detach_and_log_err(cx));
1833 }),
1834 )
1835 .on_action(
1836 cx.listener(|pane: &mut Self, action: &RevealInProjectPanel, cx| {
1837 pane.project.update(cx, |_, cx| {
1838 cx.emit(project::Event::RevealInProjectPanel(
1839 ProjectEntryId::from_proto(action.entry_id),
1840 ))
1841 })
1842 }),
1843 )
1844 .child(self.render_tab_bar(cx))
1845 .child(self.toolbar.clone())
1846 .child(if let Some(item) = self.active_item() {
1847 div().flex().flex_1().child(item.to_any())
1848 } else {
1849 h_stack()
1850 .items_center()
1851 .size_full()
1852 .justify_center()
1853 .child(Label::new("Open a file or project to get started.").color(Color::Muted))
1854 })
1855 .on_mouse_down(
1856 MouseButton::Navigate(NavigationDirection::Back),
1857 cx.listener(|pane, _, cx| {
1858 if let Some(workspace) = pane.workspace.upgrade() {
1859 let pane = cx.view().downgrade();
1860 cx.window_context().defer(move |cx| {
1861 workspace.update(cx, |workspace, cx| {
1862 workspace.go_back(pane, cx).detach_and_log_err(cx)
1863 })
1864 })
1865 }
1866 }),
1867 )
1868 .on_mouse_down(
1869 MouseButton::Navigate(NavigationDirection::Forward),
1870 cx.listener(|pane, _, cx| {
1871 if let Some(workspace) = pane.workspace.upgrade() {
1872 let pane = cx.view().downgrade();
1873 cx.window_context().defer(move |cx| {
1874 workspace.update(cx, |workspace, cx| {
1875 workspace.go_forward(pane, cx).detach_and_log_err(cx)
1876 })
1877 })
1878 }
1879 }),
1880 )
1881 }
1882
1883 // fn focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
1884 // if !self.has_focus {
1885 // self.has_focus = true;
1886 // cx.emit(Event::Focus);
1887 // cx.notify();
1888 // }
1889
1890 // self.toolbar.update(cx, |toolbar, cx| {
1891 // toolbar.focus_changed(true, cx);
1892 // });
1893
1894 // if let Some(active_item) = self.active_item() {
1895 // if cx.is_self_focused() {
1896 // // Pane was focused directly. We need to either focus a view inside the active item,
1897 // // or focus the active item itself
1898 // if let Some(weak_last_focused_view) =
1899 // self.last_focused_view_by_item.get(&active_item.id())
1900 // {
1901 // if let Some(last_focused_view) = weak_last_focused_view.upgrade(cx) {
1902 // cx.focus(&last_focused_view);
1903 // return;
1904 // } else {
1905 // self.last_focused_view_by_item.remove(&active_item.id());
1906 // }
1907 // }
1908
1909 // cx.focus(active_item.as_any());
1910 // } else if focused != self.tab_bar_context_menu.handle {
1911 // self.last_focused_view_by_item
1912 // .insert(active_item.id(), focused.downgrade());
1913 // }
1914 // }
1915 // }
1916
1917 // fn focus_out(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
1918 // self.has_focus = false;
1919 // self.toolbar.update(cx, |toolbar, cx| {
1920 // toolbar.focus_changed(false, cx);
1921 // });
1922 // cx.notify();
1923 // }
1924
1925 // fn update_keymap_context(&self, keymap: &mut KeymapContext, _: &AppContext) {
1926 // Self::reset_to_default_keymap_context(keymap);
1927 // }
1928}
1929
1930impl ItemNavHistory {
1931 pub fn push<D: 'static + Send + Any>(&mut self, data: Option<D>, cx: &mut WindowContext) {
1932 self.history.push(data, self.item.clone(), cx);
1933 }
1934
1935 pub fn pop_backward(&mut self, cx: &mut WindowContext) -> Option<NavigationEntry> {
1936 self.history.pop(NavigationMode::GoingBack, cx)
1937 }
1938
1939 pub fn pop_forward(&mut self, cx: &mut WindowContext) -> Option<NavigationEntry> {
1940 self.history.pop(NavigationMode::GoingForward, cx)
1941 }
1942}
1943
1944impl NavHistory {
1945 pub fn for_each_entry(
1946 &self,
1947 cx: &AppContext,
1948 mut f: impl FnMut(&NavigationEntry, (ProjectPath, Option<PathBuf>)),
1949 ) {
1950 let borrowed_history = self.0.lock();
1951 borrowed_history
1952 .forward_stack
1953 .iter()
1954 .chain(borrowed_history.backward_stack.iter())
1955 .chain(borrowed_history.closed_stack.iter())
1956 .for_each(|entry| {
1957 if let Some(project_and_abs_path) =
1958 borrowed_history.paths_by_item.get(&entry.item.id())
1959 {
1960 f(entry, project_and_abs_path.clone());
1961 } else if let Some(item) = entry.item.upgrade() {
1962 if let Some(path) = item.project_path(cx) {
1963 f(entry, (path, None));
1964 }
1965 }
1966 })
1967 }
1968
1969 pub fn set_mode(&mut self, mode: NavigationMode) {
1970 self.0.lock().mode = mode;
1971 }
1972
1973 pub fn mode(&self) -> NavigationMode {
1974 self.0.lock().mode
1975 }
1976
1977 pub fn disable(&mut self) {
1978 self.0.lock().mode = NavigationMode::Disabled;
1979 }
1980
1981 pub fn enable(&mut self) {
1982 self.0.lock().mode = NavigationMode::Normal;
1983 }
1984
1985 pub fn pop(&mut self, mode: NavigationMode, cx: &mut WindowContext) -> Option<NavigationEntry> {
1986 let mut state = self.0.lock();
1987 let entry = match mode {
1988 NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
1989 return None
1990 }
1991 NavigationMode::GoingBack => &mut state.backward_stack,
1992 NavigationMode::GoingForward => &mut state.forward_stack,
1993 NavigationMode::ReopeningClosedItem => &mut state.closed_stack,
1994 }
1995 .pop_back();
1996 if entry.is_some() {
1997 state.did_update(cx);
1998 }
1999 entry
2000 }
2001
2002 pub fn push<D: 'static + Send + Any>(
2003 &mut self,
2004 data: Option<D>,
2005 item: Arc<dyn WeakItemHandle>,
2006 cx: &mut WindowContext,
2007 ) {
2008 let state = &mut *self.0.lock();
2009 match state.mode {
2010 NavigationMode::Disabled => {}
2011 NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
2012 if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2013 state.backward_stack.pop_front();
2014 }
2015 state.backward_stack.push_back(NavigationEntry {
2016 item,
2017 data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2018 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2019 });
2020 state.forward_stack.clear();
2021 }
2022 NavigationMode::GoingBack => {
2023 if state.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2024 state.forward_stack.pop_front();
2025 }
2026 state.forward_stack.push_back(NavigationEntry {
2027 item,
2028 data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2029 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2030 });
2031 }
2032 NavigationMode::GoingForward => {
2033 if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2034 state.backward_stack.pop_front();
2035 }
2036 state.backward_stack.push_back(NavigationEntry {
2037 item,
2038 data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2039 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2040 });
2041 }
2042 NavigationMode::ClosingItem => {
2043 if state.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2044 state.closed_stack.pop_front();
2045 }
2046 state.closed_stack.push_back(NavigationEntry {
2047 item,
2048 data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2049 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2050 });
2051 }
2052 }
2053 state.did_update(cx);
2054 }
2055
2056 pub fn remove_item(&mut self, item_id: EntityId) {
2057 let mut state = self.0.lock();
2058 state.paths_by_item.remove(&item_id);
2059 state
2060 .backward_stack
2061 .retain(|entry| entry.item.id() != item_id);
2062 state
2063 .forward_stack
2064 .retain(|entry| entry.item.id() != item_id);
2065 state
2066 .closed_stack
2067 .retain(|entry| entry.item.id() != item_id);
2068 }
2069
2070 pub fn path_for_item(&self, item_id: EntityId) -> Option<(ProjectPath, Option<PathBuf>)> {
2071 self.0.lock().paths_by_item.get(&item_id).cloned()
2072 }
2073}
2074
2075impl NavHistoryState {
2076 pub fn did_update(&self, cx: &mut WindowContext) {
2077 if let Some(pane) = self.pane.upgrade() {
2078 cx.defer(move |cx| {
2079 pane.update(cx, |pane, cx| pane.history_updated(cx));
2080 });
2081 }
2082 }
2083}
2084
2085// pub struct PaneBackdrop<V> {
2086// child_view: usize,
2087// child: AnyElement<V>,
2088// }
2089
2090// impl<V> PaneBackdrop<V> {
2091// pub fn new(pane_item_view: usize, child: AnyElement<V>) -> Self {
2092// PaneBackdrop {
2093// child,
2094// child_view: pane_item_view,
2095// }
2096// }
2097// }
2098
2099// impl<V: 'static> Element<V> for PaneBackdrop<V> {
2100// type LayoutState = ();
2101
2102// type PaintState = ();
2103
2104// fn layout(
2105// &mut self,
2106// constraint: gpui::SizeConstraint,
2107// view: &mut V,
2108// cx: &mut ViewContext<V>,
2109// ) -> (Vector2F, Self::LayoutState) {
2110// let size = self.child.layout(constraint, view, cx);
2111// (size, ())
2112// }
2113
2114// fn paint(
2115// &mut self,
2116// bounds: RectF,
2117// visible_bounds: RectF,
2118// _: &mut Self::LayoutState,
2119// view: &mut V,
2120// cx: &mut ViewContext<V>,
2121// ) -> Self::PaintState {
2122// let background = theme::current(cx).editor.background;
2123
2124// let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
2125
2126// cx.scene().push_quad(gpui::Quad {
2127// bounds: RectF::new(bounds.origin(), bounds.size()),
2128// background: Some(background),
2129// ..Default::default()
2130// });
2131
2132// let child_view_id = self.child_view;
2133// cx.scene().push_mouse_region(
2134// MouseRegion::new::<Self>(child_view_id, 0, visible_bounds).on_down(
2135// gpui::platform::MouseButton::Left,
2136// move |_, _: &mut V, cx| {
2137// let window = cx.window();
2138// cx.app_context().focus(window, Some(child_view_id))
2139// },
2140// ),
2141// );
2142
2143// cx.scene().push_layer(Some(bounds));
2144// self.child.paint(bounds.origin(), visible_bounds, view, cx);
2145// cx.scene().pop_layer();
2146// }
2147
2148// fn rect_for_text_range(
2149// &self,
2150// range_utf16: std::ops::Range<usize>,
2151// _bounds: RectF,
2152// _visible_bounds: RectF,
2153// _layout: &Self::LayoutState,
2154// _paint: &Self::PaintState,
2155// view: &V,
2156// cx: &gpui::ViewContext<V>,
2157// ) -> Option<RectF> {
2158// self.child.rect_for_text_range(range_utf16, view, cx)
2159// }
2160
2161// fn debug(
2162// &self,
2163// _bounds: RectF,
2164// _layout: &Self::LayoutState,
2165// _paint: &Self::PaintState,
2166// view: &V,
2167// cx: &gpui::ViewContext<V>,
2168// ) -> serde_json::Value {
2169// gpui::json::json!({
2170// "type": "Pane Back Drop",
2171// "view": self.child_view,
2172// "child": self.child.debug(view, cx),
2173// })
2174// }
2175// }
2176
2177fn dirty_message_for(buffer_path: Option<ProjectPath>) -> String {
2178 let path = buffer_path
2179 .as_ref()
2180 .and_then(|p| p.path.to_str())
2181 .unwrap_or(&"This buffer");
2182 let path = truncate_and_remove_front(path, 80);
2183 format!("{path} contains unsaved edits. Do you want to save it?")
2184}
2185
2186// todo!("uncomment tests")
2187// #[cfg(test)]
2188// mod tests {
2189// use super::*;
2190// use crate::item::test::{TestItem, TestProjectItem};
2191// use gpui::TestAppContext;
2192// use project::FakeFs;
2193// use settings::SettingsStore;
2194
2195// #[gpui::test]
2196// async fn test_remove_active_empty(cx: &mut TestAppContext) {
2197// init_test(cx);
2198// let fs = FakeFs::new(cx.background());
2199
2200// let project = Project::test(fs, None, cx).await;
2201// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2202// let workspace = window.root(cx);
2203// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2204
2205// pane.update(cx, |pane, cx| {
2206// assert!(pane
2207// .close_active_item(&CloseActiveItem { save_intent: None }, cx)
2208// .is_none())
2209// });
2210// }
2211
2212// #[gpui::test]
2213// async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
2214// cx.foreground().forbid_parking();
2215// init_test(cx);
2216// let fs = FakeFs::new(cx.background());
2217
2218// let project = Project::test(fs, None, cx).await;
2219// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2220// let workspace = window.root(cx);
2221// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2222
2223// // 1. Add with a destination index
2224// // a. Add before the active item
2225// set_labeled_items(&pane, ["A", "B*", "C"], cx);
2226// pane.update(cx, |pane, cx| {
2227// pane.add_item(
2228// Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2229// false,
2230// false,
2231// Some(0),
2232// cx,
2233// );
2234// });
2235// assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2236
2237// // b. Add after the active item
2238// set_labeled_items(&pane, ["A", "B*", "C"], cx);
2239// pane.update(cx, |pane, cx| {
2240// pane.add_item(
2241// Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2242// false,
2243// false,
2244// Some(2),
2245// cx,
2246// );
2247// });
2248// assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2249
2250// // c. Add at the end of the item list (including off the length)
2251// set_labeled_items(&pane, ["A", "B*", "C"], cx);
2252// pane.update(cx, |pane, cx| {
2253// pane.add_item(
2254// Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2255// false,
2256// false,
2257// Some(5),
2258// cx,
2259// );
2260// });
2261// assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2262
2263// // 2. Add without a destination index
2264// // a. Add with active item at the start of the item list
2265// set_labeled_items(&pane, ["A*", "B", "C"], cx);
2266// pane.update(cx, |pane, cx| {
2267// pane.add_item(
2268// Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2269// false,
2270// false,
2271// None,
2272// cx,
2273// );
2274// });
2275// set_labeled_items(&pane, ["A", "D*", "B", "C"], cx);
2276
2277// // b. Add with active item at the end of the item list
2278// set_labeled_items(&pane, ["A", "B", "C*"], cx);
2279// pane.update(cx, |pane, cx| {
2280// pane.add_item(
2281// Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2282// false,
2283// false,
2284// None,
2285// cx,
2286// );
2287// });
2288// assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2289// }
2290
2291// #[gpui::test]
2292// async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
2293// cx.foreground().forbid_parking();
2294// init_test(cx);
2295// let fs = FakeFs::new(cx.background());
2296
2297// let project = Project::test(fs, None, cx).await;
2298// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2299// let workspace = window.root(cx);
2300// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2301
2302// // 1. Add with a destination index
2303// // 1a. Add before the active item
2304// let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2305// pane.update(cx, |pane, cx| {
2306// pane.add_item(d, false, false, Some(0), cx);
2307// });
2308// assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2309
2310// // 1b. Add after the active item
2311// let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2312// pane.update(cx, |pane, cx| {
2313// pane.add_item(d, false, false, Some(2), cx);
2314// });
2315// assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2316
2317// // 1c. Add at the end of the item list (including off the length)
2318// let [a, _, _, _] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2319// pane.update(cx, |pane, cx| {
2320// pane.add_item(a, false, false, Some(5), cx);
2321// });
2322// assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2323
2324// // 1d. Add same item to active index
2325// let [_, b, _] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
2326// pane.update(cx, |pane, cx| {
2327// pane.add_item(b, false, false, Some(1), cx);
2328// });
2329// assert_item_labels(&pane, ["A", "B*", "C"], cx);
2330
2331// // 1e. Add item to index after same item in last position
2332// let [_, _, c] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
2333// pane.update(cx, |pane, cx| {
2334// pane.add_item(c, false, false, Some(2), cx);
2335// });
2336// assert_item_labels(&pane, ["A", "B", "C*"], cx);
2337
2338// // 2. Add without a destination index
2339// // 2a. Add with active item at the start of the item list
2340// let [_, _, _, d] = set_labeled_items(&pane, ["A*", "B", "C", "D"], cx);
2341// pane.update(cx, |pane, cx| {
2342// pane.add_item(d, false, false, None, cx);
2343// });
2344// assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
2345
2346// // 2b. Add with active item at the end of the item list
2347// let [a, _, _, _] = set_labeled_items(&pane, ["A", "B", "C", "D*"], cx);
2348// pane.update(cx, |pane, cx| {
2349// pane.add_item(a, false, false, None, cx);
2350// });
2351// assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2352
2353// // 2c. Add active item to active item at end of list
2354// let [_, _, c] = set_labeled_items(&pane, ["A", "B", "C*"], cx);
2355// pane.update(cx, |pane, cx| {
2356// pane.add_item(c, false, false, None, cx);
2357// });
2358// assert_item_labels(&pane, ["A", "B", "C*"], cx);
2359
2360// // 2d. Add active item to active item at start of list
2361// let [a, _, _] = set_labeled_items(&pane, ["A*", "B", "C"], cx);
2362// pane.update(cx, |pane, cx| {
2363// pane.add_item(a, false, false, None, cx);
2364// });
2365// assert_item_labels(&pane, ["A*", "B", "C"], cx);
2366// }
2367
2368// #[gpui::test]
2369// async fn test_add_item_with_same_project_entries(cx: &mut TestAppContext) {
2370// cx.foreground().forbid_parking();
2371// init_test(cx);
2372// let fs = FakeFs::new(cx.background());
2373
2374// let project = Project::test(fs, None, cx).await;
2375// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2376// let workspace = window.root(cx);
2377// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2378
2379// // singleton view
2380// pane.update(cx, |pane, cx| {
2381// let item = TestItem::new()
2382// .with_singleton(true)
2383// .with_label("buffer 1")
2384// .with_project_items(&[TestProjectItem::new(1, "one.txt", cx)]);
2385
2386// pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2387// });
2388// assert_item_labels(&pane, ["buffer 1*"], cx);
2389
2390// // new singleton view with the same project entry
2391// pane.update(cx, |pane, cx| {
2392// let item = TestItem::new()
2393// .with_singleton(true)
2394// .with_label("buffer 1")
2395// .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2396
2397// pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2398// });
2399// assert_item_labels(&pane, ["buffer 1*"], cx);
2400
2401// // new singleton view with different project entry
2402// pane.update(cx, |pane, cx| {
2403// let item = TestItem::new()
2404// .with_singleton(true)
2405// .with_label("buffer 2")
2406// .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)]);
2407// pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2408// });
2409// assert_item_labels(&pane, ["buffer 1", "buffer 2*"], cx);
2410
2411// // new multibuffer view with the same project entry
2412// pane.update(cx, |pane, cx| {
2413// let item = TestItem::new()
2414// .with_singleton(false)
2415// .with_label("multibuffer 1")
2416// .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2417
2418// pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2419// });
2420// assert_item_labels(&pane, ["buffer 1", "buffer 2", "multibuffer 1*"], cx);
2421
2422// // another multibuffer view with the same project entry
2423// pane.update(cx, |pane, cx| {
2424// let item = TestItem::new()
2425// .with_singleton(false)
2426// .with_label("multibuffer 1b")
2427// .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2428
2429// pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2430// });
2431// assert_item_labels(
2432// &pane,
2433// ["buffer 1", "buffer 2", "multibuffer 1", "multibuffer 1b*"],
2434// cx,
2435// );
2436// }
2437
2438// #[gpui::test]
2439// async fn test_remove_item_ordering(cx: &mut TestAppContext) {
2440// init_test(cx);
2441// let fs = FakeFs::new(cx.background());
2442
2443// let project = Project::test(fs, None, cx).await;
2444// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2445// let workspace = window.root(cx);
2446// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2447
2448// add_labeled_item(&pane, "A", false, cx);
2449// add_labeled_item(&pane, "B", false, cx);
2450// add_labeled_item(&pane, "C", false, cx);
2451// add_labeled_item(&pane, "D", false, cx);
2452// assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2453
2454// pane.update(cx, |pane, cx| pane.activate_item(1, false, false, cx));
2455// add_labeled_item(&pane, "1", false, cx);
2456// assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
2457
2458// pane.update(cx, |pane, cx| {
2459// pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2460// })
2461// .unwrap()
2462// .await
2463// .unwrap();
2464// assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
2465
2466// pane.update(cx, |pane, cx| pane.activate_item(3, false, false, cx));
2467// assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2468
2469// pane.update(cx, |pane, cx| {
2470// pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2471// })
2472// .unwrap()
2473// .await
2474// .unwrap();
2475// assert_item_labels(&pane, ["A", "B*", "C"], 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", "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*"], cx);
2492// }
2493
2494// #[gpui::test]
2495// async fn test_close_inactive_items(cx: &mut TestAppContext) {
2496// init_test(cx);
2497// let fs = FakeFs::new(cx.background());
2498
2499// let project = Project::test(fs, None, cx).await;
2500// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2501// let workspace = window.root(cx);
2502// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2503
2504// set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2505
2506// pane.update(cx, |pane, cx| {
2507// pane.close_inactive_items(&CloseInactiveItems, cx)
2508// })
2509// .unwrap()
2510// .await
2511// .unwrap();
2512// assert_item_labels(&pane, ["C*"], cx);
2513// }
2514
2515// #[gpui::test]
2516// async fn test_close_clean_items(cx: &mut TestAppContext) {
2517// init_test(cx);
2518// let fs = FakeFs::new(cx.background());
2519
2520// let project = Project::test(fs, None, cx).await;
2521// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2522// let workspace = window.root(cx);
2523// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2524
2525// add_labeled_item(&pane, "A", true, cx);
2526// add_labeled_item(&pane, "B", false, cx);
2527// add_labeled_item(&pane, "C", true, cx);
2528// add_labeled_item(&pane, "D", false, cx);
2529// add_labeled_item(&pane, "E", false, cx);
2530// assert_item_labels(&pane, ["A^", "B", "C^", "D", "E*"], cx);
2531
2532// pane.update(cx, |pane, cx| pane.close_clean_items(&CloseCleanItems, cx))
2533// .unwrap()
2534// .await
2535// .unwrap();
2536// assert_item_labels(&pane, ["A^", "C*^"], cx);
2537// }
2538
2539// #[gpui::test]
2540// async fn test_close_items_to_the_left(cx: &mut TestAppContext) {
2541// init_test(cx);
2542// let fs = FakeFs::new(cx.background());
2543
2544// let project = Project::test(fs, None, cx).await;
2545// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2546// let workspace = window.root(cx);
2547// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2548
2549// set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2550
2551// pane.update(cx, |pane, cx| {
2552// pane.close_items_to_the_left(&CloseItemsToTheLeft, cx)
2553// })
2554// .unwrap()
2555// .await
2556// .unwrap();
2557// assert_item_labels(&pane, ["C*", "D", "E"], cx);
2558// }
2559
2560// #[gpui::test]
2561// async fn test_close_items_to_the_right(cx: &mut TestAppContext) {
2562// init_test(cx);
2563// let fs = FakeFs::new(cx.background());
2564
2565// let project = Project::test(fs, None, cx).await;
2566// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2567// let workspace = window.root(cx);
2568// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2569
2570// set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2571
2572// pane.update(cx, |pane, cx| {
2573// pane.close_items_to_the_right(&CloseItemsToTheRight, cx)
2574// })
2575// .unwrap()
2576// .await
2577// .unwrap();
2578// assert_item_labels(&pane, ["A", "B", "C*"], cx);
2579// }
2580
2581// #[gpui::test]
2582// async fn test_close_all_items(cx: &mut TestAppContext) {
2583// init_test(cx);
2584// let fs = FakeFs::new(cx.background());
2585
2586// let project = Project::test(fs, None, cx).await;
2587// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2588// let workspace = window.root(cx);
2589// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2590
2591// add_labeled_item(&pane, "A", false, cx);
2592// add_labeled_item(&pane, "B", false, cx);
2593// add_labeled_item(&pane, "C", false, cx);
2594// assert_item_labels(&pane, ["A", "B", "C*"], cx);
2595
2596// pane.update(cx, |pane, cx| {
2597// pane.close_all_items(&CloseAllItems { save_intent: None }, cx)
2598// })
2599// .unwrap()
2600// .await
2601// .unwrap();
2602// assert_item_labels(&pane, [], cx);
2603
2604// add_labeled_item(&pane, "A", true, cx);
2605// add_labeled_item(&pane, "B", true, cx);
2606// add_labeled_item(&pane, "C", true, cx);
2607// assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
2608
2609// let save = pane
2610// .update(cx, |pane, cx| {
2611// pane.close_all_items(&CloseAllItems { save_intent: None }, cx)
2612// })
2613// .unwrap();
2614
2615// cx.foreground().run_until_parked();
2616// window.simulate_prompt_answer(2, cx);
2617// save.await.unwrap();
2618// assert_item_labels(&pane, [], cx);
2619// }
2620
2621// fn init_test(cx: &mut TestAppContext) {
2622// cx.update(|cx| {
2623// cx.set_global(SettingsStore::test(cx));
2624// theme::init((), cx);
2625// crate::init_settings(cx);
2626// Project::init_settings(cx);
2627// });
2628// }
2629
2630// fn add_labeled_item(
2631// pane: &ViewHandle<Pane>,
2632// label: &str,
2633// is_dirty: bool,
2634// cx: &mut TestAppContext,
2635// ) -> Box<ViewHandle<TestItem>> {
2636// pane.update(cx, |pane, cx| {
2637// let labeled_item =
2638// Box::new(cx.add_view(|_| TestItem::new().with_label(label).with_dirty(is_dirty)));
2639// pane.add_item(labeled_item.clone(), false, false, None, cx);
2640// labeled_item
2641// })
2642// }
2643
2644// fn set_labeled_items<const COUNT: usize>(
2645// pane: &ViewHandle<Pane>,
2646// labels: [&str; COUNT],
2647// cx: &mut TestAppContext,
2648// ) -> [Box<ViewHandle<TestItem>>; COUNT] {
2649// pane.update(cx, |pane, cx| {
2650// pane.items.clear();
2651// let mut active_item_index = 0;
2652
2653// let mut index = 0;
2654// let items = labels.map(|mut label| {
2655// if label.ends_with("*") {
2656// label = label.trim_end_matches("*");
2657// active_item_index = index;
2658// }
2659
2660// let labeled_item = Box::new(cx.add_view(|_| TestItem::new().with_label(label)));
2661// pane.add_item(labeled_item.clone(), false, false, None, cx);
2662// index += 1;
2663// labeled_item
2664// });
2665
2666// pane.activate_item(active_item_index, false, false, cx);
2667
2668// items
2669// })
2670// }
2671
2672// // Assert the item label, with the active item label suffixed with a '*'
2673// fn assert_item_labels<const COUNT: usize>(
2674// pane: &ViewHandle<Pane>,
2675// expected_states: [&str; COUNT],
2676// cx: &mut TestAppContext,
2677// ) {
2678// pane.read_with(cx, |pane, cx| {
2679// let actual_states = pane
2680// .items
2681// .iter()
2682// .enumerate()
2683// .map(|(ix, item)| {
2684// let mut state = item
2685// .as_any()
2686// .downcast_ref::<TestItem>()
2687// .unwrap()
2688// .read(cx)
2689// .label
2690// .clone();
2691// if ix == pane.active_item_index {
2692// state.push('*');
2693// }
2694// if item.is_dirty(cx) {
2695// state.push('^');
2696// }
2697// state
2698// })
2699// .collect::<Vec<_>>();
2700
2701// assert_eq!(
2702// actual_states, expected_states,
2703// "pane items do not match expectation"
2704// );
2705// })
2706// }
2707// }
2708
2709impl Render for DraggedTab {
2710 type Element = <Tab as RenderOnce>::Rendered;
2711
2712 fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
2713 let ui_font = ThemeSettings::get_global(cx).ui_font.family.clone();
2714 let item = &self.pane.read(cx).items[self.ix];
2715 let label = item.tab_content(Some(self.detail), false, cx);
2716 Tab::new("")
2717 .selected(self.is_active)
2718 .child(label)
2719 .render(cx)
2720 .font(ui_font)
2721 }
2722}