cursor_position.rs

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