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