1use anyhow::{Context, Result};
2use fuzzy::{StringMatch, StringMatchCandidate};
3use git::repository::Branch;
4use gpui::{
5 actions, rems, AnyElement, AppContext, DismissEvent, EventEmitter, FocusHandle, FocusableView,
6 InteractiveElement, IntoElement, ParentElement, Render, SharedString, Styled, Subscription,
7 Task, View, ViewContext, VisualContext, WindowContext,
8};
9use picker::{Picker, PickerDelegate};
10use std::{ops::Not, sync::Arc};
11use ui::{prelude::*, HighlightedLabel, ListItem, ListItemSpacing};
12use util::ResultExt;
13use workspace::notifications::NotificationId;
14use workspace::{ModalView, Toast, Workspace};
15
16actions!(branches, [OpenRecent]);
17
18pub fn init(cx: &mut AppContext) {
19 cx.observe_new_views(|workspace: &mut Workspace, _| {
20 workspace.register_action(|workspace, action, cx| {
21 BranchList::open(workspace, action, cx).log_err();
22 });
23 })
24 .detach();
25}
26
27pub struct BranchList {
28 pub picker: View<Picker<BranchListDelegate>>,
29 rem_width: f32,
30 _subscription: Subscription,
31}
32
33impl BranchList {
34 fn new(delegate: BranchListDelegate, rem_width: f32, cx: &mut ViewContext<Self>) -> Self {
35 let picker = cx.new_view(|cx| Picker::uniform_list(delegate, cx));
36 let _subscription = cx.subscribe(&picker, |_, _, _, cx| cx.emit(DismissEvent));
37 Self {
38 picker,
39 rem_width,
40 _subscription,
41 }
42 }
43 pub fn open(
44 workspace: &mut Workspace,
45 _: &OpenRecent,
46 cx: &mut ViewContext<Workspace>,
47 ) -> Result<()> {
48 // Modal branch picker has a longer trailoff than a popover one.
49 let delegate = BranchListDelegate::new(workspace, cx.view().clone(), 70, cx)?;
50 workspace.toggle_modal(cx, |cx| BranchList::new(delegate, 34., cx));
51
52 Ok(())
53 }
54}
55impl ModalView for BranchList {}
56impl EventEmitter<DismissEvent> for BranchList {}
57
58impl FocusableView for BranchList {
59 fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
60 self.picker.focus_handle(cx)
61 }
62}
63
64impl Render for BranchList {
65 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
66 v_flex()
67 .w(rems(self.rem_width))
68 .child(self.picker.clone())
69 .on_mouse_down_out(cx.listener(|this, _, cx| {
70 this.picker.update(cx, |this, cx| {
71 this.cancel(&Default::default(), cx);
72 })
73 }))
74 }
75}
76
77#[derive(Debug, Clone)]
78enum BranchEntry {
79 Branch(StringMatch),
80 NewBranch { name: String },
81}
82
83impl BranchEntry {
84 fn name(&self) -> &str {
85 match self {
86 Self::Branch(branch) => &branch.string,
87 Self::NewBranch { name } => &name,
88 }
89 }
90}
91
92pub struct BranchListDelegate {
93 matches: Vec<BranchEntry>,
94 all_branches: Vec<Branch>,
95 workspace: View<Workspace>,
96 selected_index: usize,
97 last_query: String,
98 /// Max length of branch name before we truncate it and add a trailing `...`.
99 branch_name_trailoff_after: usize,
100}
101
102impl BranchListDelegate {
103 fn new(
104 workspace: &Workspace,
105 handle: View<Workspace>,
106 branch_name_trailoff_after: usize,
107 cx: &AppContext,
108 ) -> Result<Self> {
109 let project = workspace.project().read(cx);
110 let repo = project
111 .get_first_worktree_root_repo(cx)
112 .context("failed to get root repository for first worktree")?;
113
114 let all_branches = repo.branches()?;
115 Ok(Self {
116 matches: vec![],
117 workspace: handle,
118 all_branches,
119 selected_index: 0,
120 last_query: Default::default(),
121 branch_name_trailoff_after,
122 })
123 }
124
125 fn display_error_toast(&self, message: String, cx: &mut WindowContext<'_>) {
126 self.workspace.update(cx, |model, ctx| {
127 struct GitCheckoutFailure;
128 let id = NotificationId::unique::<GitCheckoutFailure>();
129
130 model.show_toast(Toast::new(id, message), ctx)
131 });
132 }
133}
134
135impl PickerDelegate for BranchListDelegate {
136 type ListItem = ListItem;
137
138 fn placeholder_text(&self, _cx: &mut WindowContext) -> Arc<str> {
139 "Select branch...".into()
140 }
141
142 fn match_count(&self) -> usize {
143 self.matches.len()
144 }
145
146 fn selected_index(&self) -> usize {
147 self.selected_index
148 }
149
150 fn set_selected_index(&mut self, ix: usize, _: &mut ViewContext<Picker<Self>>) {
151 self.selected_index = ix;
152 }
153
154 fn update_matches(&mut self, query: String, cx: &mut ViewContext<Picker<Self>>) -> Task<()> {
155 cx.spawn(move |picker, mut cx| async move {
156 let candidates = picker.update(&mut cx, |view, _| {
157 const RECENT_BRANCHES_COUNT: usize = 10;
158 let mut branches = view.delegate.all_branches.clone();
159 if query.is_empty() {
160 if branches.len() > RECENT_BRANCHES_COUNT {
161 // Truncate list of recent branches
162 // Do a partial sort to show recent-ish branches first.
163 branches.select_nth_unstable_by(RECENT_BRANCHES_COUNT - 1, |lhs, rhs| {
164 rhs.is_head
165 .cmp(&lhs.is_head)
166 .then(rhs.unix_timestamp.cmp(&lhs.unix_timestamp))
167 });
168 branches.truncate(RECENT_BRANCHES_COUNT);
169 }
170 branches.sort_unstable_by(|lhs, rhs| {
171 rhs.is_head.cmp(&lhs.is_head).then(lhs.name.cmp(&rhs.name))
172 });
173 }
174 branches
175 .into_iter()
176 .enumerate()
177 .map(|(ix, command)| StringMatchCandidate {
178 id: ix,
179 char_bag: command.name.chars().collect(),
180 string: command.name.into(),
181 })
182 .collect::<Vec<StringMatchCandidate>>()
183 });
184 let Some(candidates) = candidates.log_err() else {
185 return;
186 };
187 let matches = if query.is_empty() {
188 candidates
189 .into_iter()
190 .enumerate()
191 .map(|(index, candidate)| StringMatch {
192 candidate_id: index,
193 string: candidate.string,
194 positions: Vec::new(),
195 score: 0.0,
196 })
197 .collect()
198 } else {
199 fuzzy::match_strings(
200 &candidates,
201 &query,
202 true,
203 10000,
204 &Default::default(),
205 cx.background_executor().clone(),
206 )
207 .await
208 };
209 picker
210 .update(&mut cx, |picker, _| {
211 let delegate = &mut picker.delegate;
212 delegate.matches = matches.into_iter().map(BranchEntry::Branch).collect();
213 if delegate.matches.is_empty() {
214 if !query.is_empty() {
215 delegate.matches.push(BranchEntry::NewBranch {
216 name: query.trim().replace(' ', "-"),
217 });
218 }
219
220 delegate.selected_index = 0;
221 } else {
222 delegate.selected_index =
223 core::cmp::min(delegate.selected_index, delegate.matches.len() - 1);
224 }
225 delegate.last_query = query;
226 })
227 .log_err();
228 })
229 }
230
231 fn confirm(&mut self, _: bool, cx: &mut ViewContext<Picker<Self>>) {
232 let Some(branch) = self.matches.get(self.selected_index()) else {
233 return;
234 };
235 cx.spawn({
236 let branch = branch.clone();
237 |picker, mut cx| async move {
238 picker
239 .update(&mut cx, |this, cx| {
240 let project = this.delegate.workspace.read(cx).project().read(cx);
241 let repo = project
242 .get_first_worktree_root_repo(cx)
243 .context("failed to get root repository for first worktree")?;
244
245 let branch_to_checkout = match branch {
246 BranchEntry::Branch(branch) => branch.string,
247 BranchEntry::NewBranch { name: branch_name } => {
248 let status = repo.create_branch(&branch_name);
249 if status.is_err() {
250 this.delegate.display_error_toast(format!("Failed to create branch '{branch_name}', check for conflicts or unstashed files"), cx);
251 status?;
252 }
253
254 branch_name
255 }
256 };
257
258 let status = repo.change_branch(&branch_to_checkout);
259 if status.is_err() {
260 this.delegate.display_error_toast(format!("Failed to checkout branch '{branch_to_checkout}', check for conflicts or unstashed files"), cx);
261 status?;
262 }
263
264 cx.emit(DismissEvent);
265
266 Ok::<(), anyhow::Error>(())
267 })
268 .log_err();
269 }
270 })
271 .detach();
272 }
273
274 fn dismissed(&mut self, cx: &mut ViewContext<Picker<Self>>) {
275 cx.emit(DismissEvent);
276 }
277
278 fn render_match(
279 &self,
280 ix: usize,
281 selected: bool,
282 _cx: &mut ViewContext<Picker<Self>>,
283 ) -> Option<Self::ListItem> {
284 let hit = &self.matches[ix];
285 let shortened_branch_name =
286 util::truncate_and_trailoff(&hit.name(), self.branch_name_trailoff_after);
287
288 Some(
289 ListItem::new(SharedString::from(format!("vcs-menu-{ix}")))
290 .inset(true)
291 .spacing(ListItemSpacing::Sparse)
292 .selected(selected)
293 .map(|parent| match hit {
294 BranchEntry::Branch(branch) => {
295 let highlights: Vec<_> = branch
296 .positions
297 .iter()
298 .filter(|index| index < &&self.branch_name_trailoff_after)
299 .copied()
300 .collect();
301
302 parent.child(HighlightedLabel::new(shortened_branch_name, highlights))
303 }
304 BranchEntry::NewBranch { name } => {
305 parent.child(Label::new(format!("Create branch '{name}'")))
306 }
307 }),
308 )
309 }
310
311 fn render_header(&self, _: &mut ViewContext<Picker<Self>>) -> Option<AnyElement> {
312 let label = if self.last_query.is_empty() {
313 Label::new("Recent Branches")
314 .size(LabelSize::Small)
315 .mt_1()
316 .ml_3()
317 .into_any_element()
318 } else {
319 let match_label = self.matches.is_empty().not().then(|| {
320 let suffix = if self.matches.len() == 1 { "" } else { "es" };
321 Label::new(format!("{} match{}", self.matches.len(), suffix))
322 .color(Color::Muted)
323 .size(LabelSize::Small)
324 });
325 h_flex()
326 .px_3()
327 .justify_between()
328 .child(Label::new("Branches").size(LabelSize::Small))
329 .children(match_label)
330 .into_any_element()
331 };
332 Some(v_flex().mt_1().child(label).into_any_element())
333 }
334}