cursor_position.rs

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