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