cursor_position.rs

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