lib.rs

  1use anyhow::{anyhow, bail, Result};
  2use fuzzy::{StringMatch, StringMatchCandidate};
  3use gpui::{
  4    actions,
  5    elements::*,
  6    platform::{CursorStyle, MouseButton},
  7    AppContext, MouseState, Task, ViewContext, ViewHandle,
  8};
  9use picker::{Picker, PickerDelegate, PickerEvent};
 10use std::{ops::Not, sync::Arc};
 11use util::ResultExt;
 12use workspace::{Toast, Workspace};
 13
 14actions!(branches, [OpenRecent]);
 15
 16pub fn init(cx: &mut AppContext) {
 17    Picker::<BranchListDelegate>::init(cx);
 18    cx.add_async_action(toggle);
 19}
 20pub type BranchList = Picker<BranchListDelegate>;
 21
 22pub fn build_branch_list(
 23    workspace: ViewHandle<Workspace>,
 24    cx: &mut ViewContext<BranchList>,
 25) -> BranchList {
 26    Picker::new(
 27        BranchListDelegate {
 28            matches: vec![],
 29            workspace,
 30            selected_index: 0,
 31            last_query: String::default(),
 32            branch_name_trailoff_after: 29,
 33        },
 34        cx,
 35    )
 36    .with_theme(|theme| theme.picker.clone())
 37}
 38
 39fn toggle(
 40    _: &mut Workspace,
 41    _: &OpenRecent,
 42    cx: &mut ViewContext<Workspace>,
 43) -> Option<Task<Result<()>>> {
 44    Some(cx.spawn(|workspace, mut cx| async move {
 45        workspace.update(&mut cx, |workspace, cx| {
 46            workspace.toggle_modal(cx, |_, cx| {
 47                let workspace = cx.handle();
 48                cx.add_view(|cx| {
 49                    Picker::new(
 50                        BranchListDelegate {
 51                            matches: vec![],
 52                            workspace,
 53                            selected_index: 0,
 54                            last_query: String::default(),
 55                            /// Modal branch picker has a longer trailoff than a popover one.
 56                            branch_name_trailoff_after: 70,
 57                        },
 58                        cx,
 59                    )
 60                    .with_theme(|theme| theme.picker.clone())
 61                    .with_max_size(800., 1200.)
 62                })
 63            });
 64        })?;
 65        Ok(())
 66    }))
 67}
 68
 69pub struct BranchListDelegate {
 70    matches: Vec<StringMatch>,
 71    workspace: ViewHandle<Workspace>,
 72    selected_index: usize,
 73    last_query: String,
 74    /// Max length of branch name before we truncate it and add a trailing `...`.
 75    branch_name_trailoff_after: usize,
 76}
 77
 78impl BranchListDelegate {
 79    fn display_error_toast(&self, message: String, cx: &mut ViewContext<BranchList>) {
 80        const GIT_CHECKOUT_FAILURE_ID: usize = 2048;
 81        self.workspace.update(cx, |model, ctx| {
 82            model.show_toast(Toast::new(GIT_CHECKOUT_FAILURE_ID, message), ctx)
 83        });
 84    }
 85}
 86impl PickerDelegate for BranchListDelegate {
 87    fn placeholder_text(&self) -> Arc<str> {
 88        "Select branch...".into()
 89    }
 90
 91    fn match_count(&self) -> usize {
 92        self.matches.len()
 93    }
 94
 95    fn selected_index(&self) -> usize {
 96        self.selected_index
 97    }
 98
 99    fn set_selected_index(&mut self, ix: usize, _: &mut ViewContext<Picker<Self>>) {
100        self.selected_index = ix;
101    }
102
103    fn update_matches(&mut self, query: String, cx: &mut ViewContext<Picker<Self>>) -> Task<()> {
104        cx.spawn(move |picker, mut cx| async move {
105            let Some(candidates) = picker
106                .read_with(&mut cx, |view, cx| {
107                    let delegate = view.delegate();
108                    let project = delegate.workspace.read(cx).project().read(&cx);
109                    let mut cwd =
110                    project
111                        .visible_worktrees(cx)
112                        .next()
113                        .unwrap()
114                        .read(cx)
115                        .abs_path()
116                        .to_path_buf();
117                    cwd.push(".git");
118                    let Some(repo) = project.fs().open_repo(&cwd) else {bail!("Project does not have associated git repository.")};
119                    let mut branches = repo
120                        .lock()
121                        .branches()?;
122                    const RECENT_BRANCHES_COUNT: usize = 10;
123                    if query.is_empty() && branches.len() > RECENT_BRANCHES_COUNT {
124                        // Truncate list of recent branches
125                        // Do a partial sort to show recent-ish branches first.
126                        branches.select_nth_unstable_by(RECENT_BRANCHES_COUNT - 1, |lhs, rhs| {
127                            rhs.unix_timestamp.cmp(&lhs.unix_timestamp)
128                        });
129                        branches.truncate(RECENT_BRANCHES_COUNT);
130                        branches.sort_unstable_by(|lhs, rhs| lhs.name.cmp(&rhs.name));
131                    }
132                    Ok(branches
133                        .iter()
134                        .cloned()
135                        .enumerate()
136                        .map(|(ix, command)| StringMatchCandidate {
137                            id: ix,
138                            char_bag: command.name.chars().collect(),
139                            string: command.name.into(),
140                        })
141                        .collect::<Vec<_>>())
142                })
143                .log_err() else { return; };
144            let Some(candidates) = candidates.log_err() else {return;};
145            let matches = if query.is_empty() {
146                candidates
147                    .into_iter()
148                    .enumerate()
149                    .map(|(index, candidate)| StringMatch {
150                        candidate_id: index,
151                        string: candidate.string,
152                        positions: Vec::new(),
153                        score: 0.0,
154                    })
155                    .collect()
156            } else {
157                fuzzy::match_strings(
158                    &candidates,
159                    &query,
160                    true,
161                    10000,
162                    &Default::default(),
163                    cx.background(),
164                )
165                .await
166            };
167            picker
168                .update(&mut cx, |picker, _| {
169                    let delegate = picker.delegate_mut();
170                    delegate.matches = matches;
171                    if delegate.matches.is_empty() {
172                        delegate.selected_index = 0;
173                    } else {
174                        delegate.selected_index =
175                            core::cmp::min(delegate.selected_index, delegate.matches.len() - 1);
176                    }
177                    delegate.last_query = query;
178                })
179                .log_err();
180        })
181    }
182
183    fn confirm(&mut self, cx: &mut ViewContext<Picker<Self>>) {
184        let current_pick = self.selected_index();
185        let Some(current_pick) = self.matches.get(current_pick).map(|pick| pick.string.clone()) else {
186            return;
187        };
188        cx.spawn(|picker, mut cx| async move {
189            picker
190                .update(&mut cx, |this, cx| {
191                    let project = this.delegate().workspace.read(cx).project().read(cx);
192                    let mut cwd = project
193                        .visible_worktrees(cx)
194                        .next()
195                        .ok_or_else(|| anyhow!("There are no visisible worktrees."))?
196                        .read(cx)
197                        .abs_path()
198                        .to_path_buf();
199                    cwd.push(".git");
200                    let status = project
201                        .fs()
202                        .open_repo(&cwd)
203                        .ok_or_else(|| {
204                            anyhow!(
205                                "Could not open repository at path `{}`",
206                                cwd.as_os_str().to_string_lossy()
207                            )
208                        })?
209                        .lock()
210                        .change_branch(&current_pick);
211                    if status.is_err() {
212                        this.delegate().display_error_toast(format!("Failed to checkout branch '{current_pick}', check for conflicts or unstashed files"), cx);
213                        status?;
214                    }
215                    cx.emit(PickerEvent::Dismiss);
216
217                    Ok::<(), anyhow::Error>(())
218                })
219                .log_err();
220        })
221        .detach();
222    }
223
224    fn dismissed(&mut self, cx: &mut ViewContext<Picker<Self>>) {
225        cx.emit(PickerEvent::Dismiss);
226    }
227
228    fn render_match(
229        &self,
230        ix: usize,
231        mouse_state: &mut MouseState,
232        selected: bool,
233        cx: &gpui::AppContext,
234    ) -> AnyElement<Picker<Self>> {
235        let theme = &theme::current(cx);
236        let hit = &self.matches[ix];
237        let shortened_branch_name =
238            util::truncate_and_trailoff(&hit.string, self.branch_name_trailoff_after);
239        let highlights = hit
240            .positions
241            .iter()
242            .copied()
243            .filter(|index| index < &self.branch_name_trailoff_after)
244            .collect();
245        let style = theme.picker.item.in_state(selected).style_for(mouse_state);
246        Flex::row()
247            .with_child(
248                Label::new(shortened_branch_name.clone(), style.label.clone())
249                    .with_highlights(highlights)
250                    .contained()
251                    .aligned()
252                    .left(),
253            )
254            .contained()
255            .with_style(style.container)
256            .constrained()
257            .with_height(theme.contact_finder.row_height)
258            .into_any()
259    }
260    fn render_header(
261        &self,
262        cx: &mut ViewContext<Picker<Self>>,
263    ) -> Option<AnyElement<Picker<Self>>> {
264        let theme = &theme::current(cx);
265        let style = theme.picker.header.clone();
266        let label = if self.last_query.is_empty() {
267            Flex::row()
268                .with_child(Label::new("Recent branches", style.label.clone()))
269                .contained()
270                .with_style(style.container)
271        } else {
272            Flex::row()
273                .with_child(Label::new("Branches", style.label.clone()))
274                .with_children(self.matches.is_empty().not().then(|| {
275                    let suffix = if self.matches.len() == 1 { "" } else { "es" };
276                    Label::new(
277                        format!("{} match{}", self.matches.len(), suffix),
278                        style.label,
279                    )
280                    .flex_float()
281                }))
282                .contained()
283                .with_style(style.container)
284        };
285        Some(label.into_any())
286    }
287    fn render_footer(
288        &self,
289        cx: &mut ViewContext<Picker<Self>>,
290    ) -> Option<AnyElement<Picker<Self>>> {
291        if !self.last_query.is_empty() {
292            let theme = &theme::current(cx);
293            let style = theme.picker.footer.clone();
294            enum BranchCreateButton {}
295            Some(
296                Flex::row().with_child(MouseEventHandler::<BranchCreateButton, _>::new(0, cx, |state, _| {
297                    let style = style.style_for(state);
298                    Label::new("Create branch", style.label.clone())
299                        .contained()
300                        .with_style(style.container)
301                })
302                .with_cursor_style(CursorStyle::PointingHand)
303                .on_down(MouseButton::Left, |_, _, cx| {
304                    cx.spawn(|picker, mut cx| async move {
305                        picker.update(&mut cx, |this, cx| {
306                            let project = this.delegate().workspace.read(cx).project().read(cx);
307                            let current_pick = &this.delegate().last_query;
308                            let mut cwd = project
309                            .visible_worktrees(cx)
310                            .next()
311                            .ok_or_else(|| anyhow!("There are no visisible worktrees."))?
312                            .read(cx)
313                            .abs_path()
314                            .to_path_buf();
315                            cwd.push(".git");
316                            let repo = project
317                                .fs()
318                                .open_repo(&cwd)
319                                .ok_or_else(|| anyhow!("Could not open repository at path `{}`", cwd.as_os_str().to_string_lossy()))?;
320                            let repo = repo
321                                .lock();
322                            let status = repo
323                                .create_branch(&current_pick);
324                            if status.is_err() {
325                                this.delegate().display_error_toast(format!("Failed to create branch '{current_pick}', check for conflicts or unstashed files"), cx);
326                                status?;
327                            }
328                            let status = repo.change_branch(&current_pick);
329                            if status.is_err() {
330                                this.delegate().display_error_toast(format!("Failed to chec branch '{current_pick}', check for conflicts or unstashed files"), cx);
331                                status?;
332                            }
333                            cx.emit(PickerEvent::Dismiss);
334                            Ok::<(), anyhow::Error>(())
335                })
336                    }).detach();
337                })).aligned().right()
338                .into_any(),
339            )
340        } else {
341            None
342        }
343    }
344}