lib.rs

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