lib.rs

  1use anyhow::{anyhow, bail, Result};
  2use fs::repository::Branch;
  3use fuzzy::{StringMatch, StringMatchCandidate};
  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, HighlightedLabel, Label, LabelCommon,
 13    LabelSize, ListItem, ListItemSpacing, Selectable,
 14};
 15use util::ResultExt;
 16use workspace::{ModalView, Toast, Workspace};
 17
 18actions!(branches, [OpenRecent]);
 19
 20pub fn init(cx: &mut AppContext) {
 21    cx.observe_new_views(|workspace: &mut Workspace, _| {
 22        workspace.register_action(|workspace, action, cx| {
 23            BranchList::toggle_modal(workspace, action, cx).log_err();
 24        });
 25    })
 26    .detach();
 27}
 28
 29pub struct BranchList {
 30    pub picker: View<Picker<BranchListDelegate>>,
 31    rem_width: f32,
 32    _subscription: Subscription,
 33}
 34
 35impl BranchList {
 36    fn new(delegate: BranchListDelegate, rem_width: f32, cx: &mut ViewContext<Self>) -> Self {
 37        let picker = cx.new_view(|cx| Picker::uniform_list(delegate, cx));
 38        let _subscription = cx.subscribe(&picker, |_, _, _, cx| cx.emit(DismissEvent));
 39        Self {
 40            picker,
 41            rem_width,
 42            _subscription,
 43        }
 44    }
 45    fn toggle_modal(
 46        workspace: &mut Workspace,
 47        _: &OpenRecent,
 48        cx: &mut ViewContext<Workspace>,
 49    ) -> Result<()> {
 50        // Modal branch picker has a longer trailoff than a popover one.
 51        let delegate = BranchListDelegate::new(workspace, cx.view().clone(), 70, cx)?;
 52        workspace.toggle_modal(cx, |cx| BranchList::new(delegate, 34., cx));
 53
 54        Ok(())
 55    }
 56}
 57impl ModalView for BranchList {}
 58impl EventEmitter<DismissEvent> for BranchList {}
 59
 60impl FocusableView for BranchList {
 61    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
 62        self.picker.focus_handle(cx)
 63    }
 64}
 65
 66impl Render for BranchList {
 67    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
 68        v_flex()
 69            .w(rems(self.rem_width))
 70            .cursor_pointer()
 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 Some(worktree) = project.visible_worktrees(cx).next() else {
109            bail!("Cannot update branch list as there are no visible worktrees")
110        };
111
112        let mut cwd = worktree.read(cx).abs_path().to_path_buf();
113        cwd.push(".git");
114        let Some(repo) = project.fs().open_repo(&cwd) else {
115            bail!("Project does not have associated git repository.")
116        };
117        let all_branches = repo.lock().branches()?;
118        Ok(Self {
119            matches: vec![],
120            workspace: handle,
121            all_branches,
122            selected_index: 0,
123            last_query: Default::default(),
124            branch_name_trailoff_after,
125        })
126    }
127
128    fn display_error_toast(&self, message: String, cx: &mut WindowContext<'_>) {
129        const GIT_CHECKOUT_FAILURE_ID: usize = 2048;
130        self.workspace.update(cx, |model, ctx| {
131            model.show_toast(Toast::new(GIT_CHECKOUT_FAILURE_ID, message), ctx)
132        });
133    }
134}
135
136impl PickerDelegate for BranchListDelegate {
137    type ListItem = ListItem;
138
139    fn placeholder_text(&self, _cx: &mut WindowContext) -> Arc<str> {
140        "Select branch...".into()
141    }
142
143    fn match_count(&self) -> usize {
144        self.matches.len()
145    }
146
147    fn selected_index(&self) -> usize {
148        self.selected_index
149    }
150
151    fn set_selected_index(&mut self, ix: usize, _: &mut ViewContext<Picker<Self>>) {
152        self.selected_index = ix;
153    }
154
155    fn update_matches(&mut self, query: String, cx: &mut ViewContext<Picker<Self>>) -> Task<()> {
156        cx.spawn(move |picker, mut cx| async move {
157            let candidates = picker.update(&mut cx, |view, _| {
158                const RECENT_BRANCHES_COUNT: usize = 10;
159                let mut branches = view.delegate.all_branches.clone();
160                if query.is_empty() && 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.unix_timestamp.cmp(&lhs.unix_timestamp)
165                    });
166                    branches.truncate(RECENT_BRANCHES_COUNT);
167                    branches.sort_unstable_by(|lhs, rhs| lhs.name.cmp(&rhs.name));
168                }
169                branches
170                    .into_iter()
171                    .enumerate()
172                    .map(|(ix, command)| StringMatchCandidate {
173                        id: ix,
174                        char_bag: command.name.chars().collect(),
175                        string: command.name.into(),
176                    })
177                    .collect::<Vec<StringMatchCandidate>>()
178            });
179            let Some(candidates) = candidates.log_err() else {
180                return;
181            };
182            let matches = if query.is_empty() {
183                candidates
184                    .into_iter()
185                    .enumerate()
186                    .map(|(index, candidate)| StringMatch {
187                        candidate_id: index,
188                        string: candidate.string,
189                        positions: Vec::new(),
190                        score: 0.0,
191                    })
192                    .collect()
193            } else {
194                fuzzy::match_strings(
195                    &candidates,
196                    &query,
197                    true,
198                    10000,
199                    &Default::default(),
200                    cx.background_executor().clone(),
201                )
202                .await
203            };
204            picker
205                .update(&mut cx, |picker, _| {
206                    let delegate = &mut picker.delegate;
207                    delegate.matches = matches;
208                    if delegate.matches.is_empty() {
209                        delegate.selected_index = 0;
210                    } else {
211                        delegate.selected_index =
212                            core::cmp::min(delegate.selected_index, delegate.matches.len() - 1);
213                    }
214                    delegate.last_query = query;
215                })
216                .log_err();
217        })
218    }
219
220    fn confirm(&mut self, _: bool, cx: &mut ViewContext<Picker<Self>>) {
221        let current_pick = self.selected_index();
222        let Some(current_pick) = self
223            .matches
224            .get(current_pick)
225            .map(|pick| pick.string.clone())
226        else {
227            return;
228        };
229        cx.spawn(|picker, mut cx| async move {
230            picker
231                .update(&mut cx, |this, cx| {
232                    let project = this.delegate.workspace.read(cx).project().read(cx);
233                    let mut cwd = project
234                        .visible_worktrees(cx)
235                        .next()
236                        .ok_or_else(|| anyhow!("There are no visisible worktrees."))?
237                        .read(cx)
238                        .abs_path()
239                        .to_path_buf();
240                    cwd.push(".git");
241                    let status = project
242                        .fs()
243                        .open_repo(&cwd)
244                        .ok_or_else(|| {
245                            anyhow!(
246                                "Could not open repository at path `{}`",
247                                cwd.as_os_str().to_string_lossy()
248                            )
249                        })?
250                        .lock()
251                        .change_branch(&current_pick);
252                    if status.is_err() {
253                        this.delegate.display_error_toast(format!("Failed to checkout branch '{current_pick}', check for conflicts or unstashed files"), cx);
254                        status?;
255                    }
256                    cx.emit(DismissEvent);
257
258                    Ok::<(), anyhow::Error>(())
259                })
260                .log_err();
261        })
262        .detach();
263    }
264
265    fn dismissed(&mut self, cx: &mut ViewContext<Picker<Self>>) {
266        cx.emit(DismissEvent);
267    }
268
269    fn render_match(
270        &self,
271        ix: usize,
272        selected: bool,
273        _cx: &mut ViewContext<Picker<Self>>,
274    ) -> Option<Self::ListItem> {
275        let hit = &self.matches[ix];
276        let shortened_branch_name =
277            util::truncate_and_trailoff(&hit.string, self.branch_name_trailoff_after);
278        let highlights: Vec<_> = hit
279            .positions
280            .iter()
281            .filter(|index| index < &&self.branch_name_trailoff_after)
282            .copied()
283            .collect();
284        Some(
285            ListItem::new(SharedString::from(format!("vcs-menu-{ix}")))
286                .inset(true)
287                .spacing(ListItemSpacing::Sparse)
288                .selected(selected)
289                .start_slot(HighlightedLabel::new(shortened_branch_name, highlights)),
290        )
291    }
292    fn render_header(&self, _: &mut ViewContext<Picker<Self>>) -> Option<AnyElement> {
293        let label = if self.last_query.is_empty() {
294            h_flex()
295                .ml_3()
296                .child(Label::new("Recent branches").size(LabelSize::Small))
297        } else {
298            let match_label = self.matches.is_empty().not().then(|| {
299                let suffix = if self.matches.len() == 1 { "" } else { "es" };
300                Label::new(format!("{} match{}", self.matches.len(), suffix)).size(LabelSize::Small)
301            });
302            h_flex()
303                .px_3()
304                .h_full()
305                .justify_between()
306                .child(Label::new("Branches").size(LabelSize::Small))
307                .children(match_label)
308        };
309        Some(label.into_any())
310    }
311    fn render_footer(&self, cx: &mut ViewContext<Picker<Self>>) -> Option<AnyElement> {
312        if self.last_query.is_empty() {
313            return None;
314        }
315
316        Some(
317            h_flex().mr_3().pb_2().child(h_flex().w_full()).child(
318            Button::new("branch-picker-create-branch-button", "Create branch").on_click(
319                cx.listener(|_, _, cx| {
320                    cx.spawn(|picker, mut cx| async move {
321                                        picker.update(&mut cx, |this, cx| {
322                                            let project = this.delegate.workspace.read(cx).project().read(cx);
323                                            let current_pick = &this.delegate.last_query;
324                                            let mut cwd = project
325                                            .visible_worktrees(cx)
326                                            .next()
327                                            .ok_or_else(|| anyhow!("There are no visisible worktrees."))?
328                                            .read(cx)
329                                            .abs_path()
330                                            .to_path_buf();
331                                            cwd.push(".git");
332                                            let repo = project
333                                                .fs()
334                                                .open_repo(&cwd)
335                                                .ok_or_else(|| anyhow!("Could not open repository at path `{}`", cwd.as_os_str().to_string_lossy()))?;
336                                            let repo = repo
337                                                .lock();
338                                            let status = repo
339                                                .create_branch(&current_pick);
340                                            if status.is_err() {
341                                                this.delegate.display_error_toast(format!("Failed to create branch '{current_pick}', check for conflicts or unstashed files"), cx);
342                                                status?;
343                                            }
344                                            let status = repo.change_branch(&current_pick);
345                                            if status.is_err() {
346                                                this.delegate.display_error_toast(format!("Failed to check branch '{current_pick}', check for conflicts or unstashed files"), cx);
347                                                status?;
348                                            }
349                                            this.cancel(&Default::default(), cx);
350                                            Ok::<(), anyhow::Error>(())
351                                })
352
353                    }).detach_and_log_err(cx);
354                }),
355            ).style(ui::ButtonStyle::Filled)).into_any_element(),
356        )
357    }
358}