1#[cfg(test)]
2mod tab_switcher_tests;
3
4use collections::HashMap;
5use gpui::{
6 impl_actions, rems, Action, AppContext, DismissEvent, EventEmitter, FocusHandle, FocusableView,
7 Modifiers, ModifiersChangedEvent, ParentElement, Render, Styled, Task, View, ViewContext,
8 VisualContext, WeakView,
9};
10use picker::{Picker, PickerDelegate};
11use serde::Deserialize;
12use std::sync::Arc;
13use ui::{prelude::*, ListItem, ListItemSpacing};
14use util::ResultExt;
15use workspace::{
16 item::ItemHandle,
17 pane::{render_item_indicator, tab_details, Event as PaneEvent},
18 ModalView, Pane, Workspace,
19};
20
21const PANEL_WIDTH_REMS: f32 = 28.;
22
23#[derive(PartialEq, Clone, Deserialize, Default)]
24pub struct Toggle {
25 #[serde(default)]
26 pub select_last: bool,
27}
28
29impl_actions!(tab_switcher, [Toggle]);
30
31pub struct TabSwitcher {
32 picker: View<Picker<TabSwitcherDelegate>>,
33 init_modifiers: Option<Modifiers>,
34}
35
36impl ModalView for TabSwitcher {}
37
38pub fn init(cx: &mut AppContext) {
39 cx.observe_new_views(TabSwitcher::register).detach();
40}
41
42impl TabSwitcher {
43 fn register(workspace: &mut Workspace, _: &mut ViewContext<Workspace>) {
44 workspace.register_action(|workspace, action: &Toggle, cx| {
45 let Some(tab_switcher) = workspace.active_modal::<Self>(cx) else {
46 Self::open(action, workspace, cx);
47 return;
48 };
49
50 tab_switcher.update(cx, |tab_switcher, cx| {
51 tab_switcher
52 .picker
53 .update(cx, |picker, cx| picker.cycle_selection(cx))
54 });
55 });
56 }
57
58 fn open(action: &Toggle, workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
59 let weak_pane = workspace.active_pane().downgrade();
60 workspace.toggle_modal(cx, |cx| {
61 let delegate = TabSwitcherDelegate::new(action, cx.view().downgrade(), weak_pane, cx);
62 TabSwitcher::new(delegate, cx)
63 });
64 }
65
66 fn new(delegate: TabSwitcherDelegate, cx: &mut ViewContext<Self>) -> Self {
67 Self {
68 picker: cx.new_view(|cx| Picker::nonsearchable_uniform_list(delegate, cx)),
69 init_modifiers: cx.modifiers().modified().then_some(cx.modifiers()),
70 }
71 }
72
73 fn handle_modifiers_changed(
74 &mut self,
75 event: &ModifiersChangedEvent,
76 cx: &mut ViewContext<Self>,
77 ) {
78 let Some(init_modifiers) = self.init_modifiers else {
79 return;
80 };
81 if !event.modified() || !init_modifiers.is_subset_of(event) {
82 self.init_modifiers = None;
83 if self.picker.read(cx).delegate.matches.is_empty() {
84 cx.emit(DismissEvent)
85 } else {
86 cx.dispatch_action(menu::Confirm.boxed_clone());
87 }
88 }
89 }
90}
91
92impl EventEmitter<DismissEvent> for TabSwitcher {}
93
94impl FocusableView for TabSwitcher {
95 fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
96 self.picker.focus_handle(cx)
97 }
98}
99
100impl Render for TabSwitcher {
101 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
102 v_flex()
103 .key_context("TabSwitcher")
104 .w(rems(PANEL_WIDTH_REMS))
105 .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
106 .child(self.picker.clone())
107 }
108}
109
110struct TabMatch {
111 item_index: usize,
112 item: Box<dyn ItemHandle>,
113 detail: usize,
114}
115
116pub struct TabSwitcherDelegate {
117 select_last: bool,
118 tab_switcher: WeakView<TabSwitcher>,
119 selected_index: usize,
120 pane: WeakView<Pane>,
121 matches: Vec<TabMatch>,
122}
123
124impl TabSwitcherDelegate {
125 fn new(
126 action: &Toggle,
127 tab_switcher: WeakView<TabSwitcher>,
128 pane: WeakView<Pane>,
129 cx: &mut ViewContext<TabSwitcher>,
130 ) -> Self {
131 Self::subscribe_to_updates(&pane, cx);
132 Self {
133 select_last: action.select_last,
134 tab_switcher,
135 selected_index: 0,
136 pane,
137 matches: Vec::new(),
138 }
139 }
140
141 fn subscribe_to_updates(pane: &WeakView<Pane>, cx: &mut ViewContext<TabSwitcher>) {
142 let Some(pane) = pane.upgrade() else {
143 return;
144 };
145 cx.subscribe(&pane, |tab_switcher, _, event, cx| {
146 match event {
147 PaneEvent::AddItem { .. } | PaneEvent::RemoveItem { .. } | PaneEvent::Remove => {
148 tab_switcher
149 .picker
150 .update(cx, |picker, cx| picker.refresh(cx))
151 }
152 _ => {}
153 };
154 })
155 .detach();
156 }
157
158 fn update_matches(&mut self, cx: &mut WindowContext) {
159 self.matches.clear();
160 let Some(pane) = self.pane.upgrade() else {
161 return;
162 };
163
164 let pane = pane.read(cx);
165 let mut history_indices = HashMap::default();
166 pane.activation_history().iter().rev().enumerate().for_each(
167 |(history_index, entity_id)| {
168 history_indices.insert(entity_id, history_index);
169 },
170 );
171
172 let items: Vec<Box<dyn ItemHandle>> = pane.items().map(|item| item.boxed_clone()).collect();
173 items
174 .iter()
175 .enumerate()
176 .zip(tab_details(&items, cx))
177 .map(|((item_index, item), detail)| TabMatch {
178 item_index,
179 item: item.boxed_clone(),
180 detail,
181 })
182 .for_each(|tab_match| self.matches.push(tab_match));
183
184 let non_history_base = history_indices.len();
185 self.matches.sort_by(move |a, b| {
186 let a_score = *history_indices
187 .get(&a.item.item_id())
188 .unwrap_or(&(a.item_index + non_history_base));
189 let b_score = *history_indices
190 .get(&b.item.item_id())
191 .unwrap_or(&(b.item_index + non_history_base));
192 a_score.cmp(&b_score)
193 });
194
195 if self.matches.len() > 1 {
196 if self.select_last {
197 self.selected_index = self.matches.len() - 1;
198 } else {
199 self.selected_index = 1;
200 }
201 }
202 }
203}
204
205impl PickerDelegate for TabSwitcherDelegate {
206 type ListItem = ListItem;
207
208 fn placeholder_text(&self, _cx: &mut WindowContext) -> Arc<str> {
209 "".into()
210 }
211
212 fn match_count(&self) -> usize {
213 self.matches.len()
214 }
215
216 fn selected_index(&self) -> usize {
217 self.selected_index
218 }
219
220 fn set_selected_index(&mut self, ix: usize, cx: &mut ViewContext<Picker<Self>>) {
221 self.selected_index = ix;
222 cx.notify();
223 }
224
225 fn separators_after_indices(&self) -> Vec<usize> {
226 Vec::new()
227 }
228
229 fn update_matches(
230 &mut self,
231 _raw_query: String,
232 cx: &mut ViewContext<Picker<Self>>,
233 ) -> Task<()> {
234 self.update_matches(cx);
235 Task::ready(())
236 }
237
238 fn confirm(&mut self, _secondary: bool, cx: &mut ViewContext<Picker<TabSwitcherDelegate>>) {
239 let Some(pane) = self.pane.upgrade() else {
240 return;
241 };
242 let Some(selected_match) = self.matches.get(self.selected_index()) else {
243 return;
244 };
245 pane.update(cx, |pane, cx| {
246 pane.activate_item(selected_match.item_index, true, true, cx);
247 });
248 }
249
250 fn dismissed(&mut self, cx: &mut ViewContext<Picker<TabSwitcherDelegate>>) {
251 self.tab_switcher
252 .update(cx, |_, cx| cx.emit(DismissEvent))
253 .log_err();
254 }
255
256 fn render_match(
257 &self,
258 ix: usize,
259 selected: bool,
260 cx: &mut ViewContext<Picker<Self>>,
261 ) -> Option<Self::ListItem> {
262 let tab_match = self
263 .matches
264 .get(ix)
265 .expect("Invalid matches state: no element for index {ix}");
266
267 let label = tab_match.item.tab_content(Some(tab_match.detail), true, cx);
268 let indicator = render_item_indicator(tab_match.item.boxed_clone(), cx);
269
270 Some(
271 ListItem::new(ix)
272 .spacing(ListItemSpacing::Sparse)
273 .inset(true)
274 .selected(selected)
275 .child(h_flex().w_full().child(label))
276 .children(indicator),
277 )
278 }
279}