cursor_position.rs

  1use editor::{Editor, EditorEvent, MBTextSummary, MultiBufferSnapshot};
  2use gpui::{App, Entity, FocusHandle, Focusable, Styled, Subscription, Task, WeakEntity};
  3use settings::{RegisterSetting, Settings};
  4use std::{fmt::Write, num::NonZeroU32, time::Duration};
  5use text::{Point, Selection};
  6use ui::{
  7    Button, ButtonCommon, Clickable, Context, FluentBuilder, IntoElement, LabelSize, ParentElement,
  8    Render, Tooltip, Window, div,
  9};
 10use util::paths::FILE_ROW_COLUMN_DELIMITER;
 11use workspace::{StatusBarSettings, StatusItemView, Workspace, item::ItemHandle};
 12
 13#[derive(Copy, Clone, Debug, Default, PartialOrd, PartialEq)]
 14pub(crate) struct SelectionStats {
 15    pub lines: usize,
 16    pub characters: usize,
 17    pub selections: usize,
 18}
 19
 20pub struct CursorPosition {
 21    position: Option<UserCaretPosition>,
 22    selected_count: SelectionStats,
 23    context: Option<FocusHandle>,
 24    workspace: WeakEntity<Workspace>,
 25    update_position: Task<()>,
 26    _observe_active_editor: Option<Subscription>,
 27}
 28
 29/// A position in the editor, where user's caret is located at.
 30/// Lines are never zero as there is always at least one line in the editor.
 31/// Characters may start with zero as the caret may be at the beginning of a line, but all editors start counting characters from 1,
 32/// where "1" will mean "before the first character".
 33#[derive(Copy, Clone, Debug, PartialEq, Eq)]
 34pub struct UserCaretPosition {
 35    pub line: NonZeroU32,
 36    pub character: NonZeroU32,
 37}
 38
 39impl UserCaretPosition {
 40    pub(crate) fn at_selection_end(
 41        selection: &Selection<Point>,
 42        snapshot: &MultiBufferSnapshot,
 43    ) -> Self {
 44        let selection_end = selection.head();
 45        let (line, character) =
 46            if let Some((buffer_snapshot, point)) = snapshot.point_to_buffer_point(selection_end) {
 47                let line_start = Point::new(point.row, 0);
 48
 49                let chars_to_last_position = buffer_snapshot
 50                    .text_summary_for_range::<text::TextSummary, _>(line_start..point)
 51                    .chars as u32;
 52                (line_start.row, chars_to_last_position)
 53            } else {
 54                let line_start = Point::new(selection_end.row, 0);
 55
 56                let chars_to_last_position = snapshot
 57                    .text_summary_for_range::<MBTextSummary, _>(line_start..selection_end)
 58                    .chars as u32;
 59                (selection_end.row, chars_to_last_position)
 60            };
 61
 62        Self {
 63            line: NonZeroU32::new(line + 1).expect("added 1"),
 64            character: NonZeroU32::new(character + 1).expect("added 1"),
 65        }
 66    }
 67}
 68
 69impl CursorPosition {
 70    pub fn new(workspace: &Workspace) -> Self {
 71        Self {
 72            position: None,
 73            context: None,
 74            selected_count: Default::default(),
 75            workspace: workspace.weak_handle(),
 76            update_position: Task::ready(()),
 77            _observe_active_editor: None,
 78        }
 79    }
 80
 81    fn update_position(
 82        &mut self,
 83        editor: &Entity<Editor>,
 84        debounce: Option<Duration>,
 85        window: &mut Window,
 86        cx: &mut Context<Self>,
 87    ) {
 88        let editor = editor.downgrade();
 89        self.update_position = cx.spawn_in(window, async move |cursor_position, cx| {
 90            let is_singleton = editor
 91                .update(cx, |editor, cx| editor.buffer().read(cx).is_singleton())
 92                .ok()
 93                .unwrap_or(true);
 94
 95            if !is_singleton && let Some(debounce) = debounce {
 96                cx.background_executor().timer(debounce).await;
 97            }
 98
 99            editor
100                .update(cx, |editor, cx| {
101                    cursor_position.update(cx, |cursor_position, cx| {
102                        cursor_position.selected_count = SelectionStats::default();
103                        cursor_position.selected_count.selections = editor.selections.count();
104                        match editor.mode() {
105                            editor::EditorMode::AutoHeight { .. }
106                            | editor::EditorMode::SingleLine
107                            | editor::EditorMode::Minimap { .. } => {
108                                cursor_position.position = None;
109                                cursor_position.context = None;
110                            }
111                            editor::EditorMode::Full { .. } => {
112                                let mut last_selection = None::<Selection<Point>>;
113                                let snapshot = editor.display_snapshot(cx);
114                                if snapshot.buffer_snapshot().excerpts().count() > 0 {
115                                    for selection in editor.selections.all_adjusted(&snapshot) {
116                                        let selection_summary = snapshot
117                                            .buffer_snapshot()
118                                            .text_summary_for_range::<MBTextSummary, _>(
119                                            selection.start..selection.end,
120                                        );
121                                        cursor_position.selected_count.characters +=
122                                            selection_summary.chars;
123                                        if selection.end != selection.start {
124                                            cursor_position.selected_count.lines +=
125                                                (selection.end.row - selection.start.row) as usize;
126                                            if selection.end.column != 0 {
127                                                cursor_position.selected_count.lines += 1;
128                                            }
129                                        }
130                                        if last_selection.as_ref().is_none_or(|last_selection| {
131                                            selection.id > last_selection.id
132                                        }) {
133                                            last_selection = Some(selection);
134                                        }
135                                    }
136                                }
137                                cursor_position.position = last_selection.map(|s| {
138                                    UserCaretPosition::at_selection_end(
139                                        &s,
140                                        snapshot.buffer_snapshot(),
141                                    )
142                                });
143                                cursor_position.context = Some(editor.focus_handle(cx));
144                            }
145                        }
146
147                        cx.notify();
148                    })
149                })
150                .ok()
151                .transpose()
152                .ok()
153                .flatten();
154        });
155    }
156
157    fn write_position(&self, text: &mut String, cx: &App) {
158        if self.selected_count
159            <= (SelectionStats {
160                selections: 1,
161                ..Default::default()
162            })
163        {
164            // Do not write out anything if we have just one empty selection.
165            return;
166        }
167        let SelectionStats {
168            lines,
169            characters,
170            selections,
171        } = self.selected_count;
172        let format = LineIndicatorFormat::get(None, cx);
173        let is_short_format = format == &LineIndicatorFormat::Short;
174        let lines = (lines > 1).then_some((lines, "line"));
175        let selections = (selections > 1).then_some((selections, "selection"));
176        let characters = (characters > 0).then_some((characters, "character"));
177        if (None, None, None) == (characters, selections, lines) {
178            // Nothing to display.
179            return;
180        }
181        write!(text, " (").unwrap();
182        let mut wrote_once = false;
183        for (count, name) in [selections, lines, characters].into_iter().flatten() {
184            if wrote_once {
185                write!(text, ", ").unwrap();
186            }
187            let name = if is_short_format { &name[..1] } else { name };
188            let plural_suffix = if count > 1 && !is_short_format {
189                "s"
190            } else {
191                ""
192            };
193            write!(text, "{count} {name}{plural_suffix}").unwrap();
194            wrote_once = true;
195        }
196        text.push(')');
197    }
198
199    #[cfg(test)]
200    pub(crate) fn selection_stats(&self) -> &SelectionStats {
201        &self.selected_count
202    }
203
204    #[cfg(test)]
205    pub(crate) fn position(&self) -> Option<UserCaretPosition> {
206        self.position
207    }
208}
209
210impl Render for CursorPosition {
211    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
212        if !StatusBarSettings::get_global(cx).cursor_position_button {
213            return div().hidden();
214        }
215
216        div().when_some(self.position, |el, position| {
217            let mut text = format!(
218                "{}{FILE_ROW_COLUMN_DELIMITER}{}",
219                position.line, position.character,
220            );
221            self.write_position(&mut text, cx);
222
223            let context = self.context.clone();
224
225            el.child(
226                Button::new("go-to-line-column", text)
227                    .label_size(LabelSize::Small)
228                    .on_click(cx.listener(|this, _, window, cx| {
229                        if let Some(workspace) = this.workspace.upgrade() {
230                            workspace.update(cx, |workspace, cx| {
231                                if let Some(editor) = workspace
232                                    .active_item(cx)
233                                    .and_then(|item| item.act_as::<Editor>(cx))
234                                    && let Some(buffer) = editor.read(cx).active_buffer(cx)
235                                {
236                                    workspace.toggle_modal(window, cx, |window, cx| {
237                                        crate::GoToLine::new(editor, buffer, window, cx)
238                                    })
239                                }
240                            });
241                        }
242                    }))
243                    .tooltip(move |_window, cx| match context.as_ref() {
244                        Some(context) => Tooltip::for_action_in(
245                            "Go to Line/Column",
246                            &editor::actions::ToggleGoToLine,
247                            context,
248                            cx,
249                        ),
250                        None => Tooltip::for_action(
251                            "Go to Line/Column",
252                            &editor::actions::ToggleGoToLine,
253                            cx,
254                        ),
255                    }),
256            )
257        })
258    }
259}
260
261const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
262
263impl StatusItemView for CursorPosition {
264    fn set_active_pane_item(
265        &mut self,
266        active_pane_item: Option<&dyn ItemHandle>,
267        window: &mut Window,
268        cx: &mut Context<Self>,
269    ) {
270        if let Some(editor) = active_pane_item.and_then(|item| item.act_as::<Editor>(cx)) {
271            self._observe_active_editor = Some(cx.subscribe_in(
272                &editor,
273                window,
274                |cursor_position, editor, event, window, cx| match event {
275                    EditorEvent::SelectionsChanged { .. } => Self::update_position(
276                        cursor_position,
277                        editor,
278                        Some(UPDATE_DEBOUNCE),
279                        window,
280                        cx,
281                    ),
282                    _ => {}
283                },
284            ));
285            self.update_position(&editor, None, window, cx);
286        } else {
287            self.position = None;
288            self._observe_active_editor = None;
289        }
290
291        cx.notify();
292    }
293}
294
295#[derive(Clone, Copy, PartialEq, Eq, RegisterSetting)]
296pub enum LineIndicatorFormat {
297    Short,
298    Long,
299}
300
301impl From<settings::LineIndicatorFormat> for LineIndicatorFormat {
302    fn from(format: settings::LineIndicatorFormat) -> Self {
303        match format {
304            settings::LineIndicatorFormat::Short => LineIndicatorFormat::Short,
305            settings::LineIndicatorFormat::Long => LineIndicatorFormat::Long,
306        }
307    }
308}
309
310impl Settings for LineIndicatorFormat {
311    fn from_settings(content: &settings::SettingsContent) -> Self {
312        content.line_indicator_format.unwrap().into()
313    }
314}