cursor_position.rs

  1use editor::{Editor, ToPoint};
  2use gpui::{AppContext, Subscription, View, WeakView};
  3use schemars::JsonSchema;
  4use serde::{Deserialize, Serialize};
  5use settings::{Settings, SettingsSources};
  6use std::fmt::Write;
  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>,
 24    selected_count: SelectionStats,
 25    workspace: WeakView<Workspace>,
 26    _observe_active_editor: Option<Subscription>,
 27}
 28
 29impl CursorPosition {
 30    pub fn new(workspace: &Workspace) -> Self {
 31        Self {
 32            position: None,
 33            selected_count: Default::default(),
 34            workspace: workspace.weak_handle(),
 35            _observe_active_editor: None,
 36        }
 37    }
 38
 39    fn update_position(&mut self, editor: View<Editor>, cx: &mut ViewContext<Self>) {
 40        let editor = editor.read(cx);
 41        let buffer = editor.buffer().read(cx).snapshot(cx);
 42
 43        self.selected_count = Default::default();
 44        self.selected_count.selections = editor.selections.count();
 45        let mut last_selection: Option<Selection<usize>> = None;
 46        for selection in editor.selections.all::<usize>(cx) {
 47            self.selected_count.characters += buffer
 48                .text_for_range(selection.start..selection.end)
 49                .map(|t| t.chars().count())
 50                .sum::<usize>();
 51            if last_selection
 52                .as_ref()
 53                .map_or(true, |last_selection| selection.id > last_selection.id)
 54            {
 55                last_selection = Some(selection);
 56            }
 57        }
 58        for selection in editor.selections.all::<Point>(cx) {
 59            if selection.end != selection.start {
 60                self.selected_count.lines += (selection.end.row - selection.start.row) as usize;
 61                if selection.end.column != 0 {
 62                    self.selected_count.lines += 1;
 63                }
 64            }
 65        }
 66        self.position = last_selection.map(|s| s.head().to_point(&buffer));
 67
 68        cx.notify();
 69    }
 70
 71    fn write_position(&self, text: &mut String, cx: &AppContext) {
 72        if self.selected_count
 73            <= (SelectionStats {
 74                selections: 1,
 75                ..Default::default()
 76            })
 77        {
 78            // Do not write out anything if we have just one empty selection.
 79            return;
 80        }
 81        let SelectionStats {
 82            lines,
 83            characters,
 84            selections,
 85        } = self.selected_count;
 86        let format = LineIndicatorFormat::get(None, cx);
 87        let is_short_format = format == &LineIndicatorFormat::Short;
 88        let lines = (lines > 1).then_some((lines, "line"));
 89        let selections = (selections > 1).then_some((selections, "selection"));
 90        let characters = (characters > 0).then_some((characters, "character"));
 91        if (None, None, None) == (characters, selections, lines) {
 92            // Nothing to display.
 93            return;
 94        }
 95        write!(text, " (").unwrap();
 96        let mut wrote_once = false;
 97        for (count, name) in [selections, lines, characters].into_iter().flatten() {
 98            if wrote_once {
 99                write!(text, ", ").unwrap();
100            }
101            let name = if is_short_format { &name[..1] } else { &name };
102            let plural_suffix = if count > 1 && !is_short_format {
103                "s"
104            } else {
105                ""
106            };
107            write!(text, "{count} {name}{plural_suffix}").unwrap();
108            wrote_once = true;
109        }
110        text.push(')');
111    }
112
113    #[cfg(test)]
114    pub(crate) fn selection_stats(&self) -> &SelectionStats {
115        &self.selected_count
116    }
117}
118
119impl Render for CursorPosition {
120    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
121        div().when_some(self.position, |el, position| {
122            let mut text = format!(
123                "{}{FILE_ROW_COLUMN_DELIMITER}{}",
124                position.row + 1,
125                position.column + 1
126            );
127            self.write_position(&mut text, cx);
128
129            el.child(
130                Button::new("go-to-line-column", text)
131                    .label_size(LabelSize::Small)
132                    .on_click(cx.listener(|this, _, cx| {
133                        if let Some(workspace) = this.workspace.upgrade() {
134                            workspace.update(cx, |workspace, cx| {
135                                if let Some(editor) = workspace
136                                    .active_item(cx)
137                                    .and_then(|item| item.act_as::<Editor>(cx))
138                                {
139                                    workspace
140                                        .toggle_modal(cx, |cx| crate::GoToLine::new(editor, cx))
141                                }
142                            });
143                        }
144                    }))
145                    .tooltip(|cx| {
146                        Tooltip::for_action(
147                            "Go to Line/Column",
148                            &editor::actions::ToggleGoToLine,
149                            cx,
150                        )
151                    }),
152            )
153        })
154    }
155}
156
157impl StatusItemView for CursorPosition {
158    fn set_active_pane_item(
159        &mut self,
160        active_pane_item: Option<&dyn ItemHandle>,
161        cx: &mut ViewContext<Self>,
162    ) {
163        if let Some(editor) = active_pane_item.and_then(|item| item.act_as::<Editor>(cx)) {
164            self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
165            self.update_position(editor, cx);
166        } else {
167            self.position = None;
168            self._observe_active_editor = None;
169        }
170
171        cx.notify();
172    }
173}
174
175#[derive(Clone, Copy, Default, PartialEq, JsonSchema, Deserialize, Serialize)]
176#[serde(rename_all = "snake_case")]
177pub(crate) enum LineIndicatorFormat {
178    Short,
179    #[default]
180    Long,
181}
182
183/// Whether or not to automatically check for updates.
184///
185/// Values: short, long
186/// Default: short
187#[derive(Clone, Copy, Default, JsonSchema, Deserialize, Serialize)]
188#[serde(transparent)]
189pub(crate) struct LineIndicatorFormatContent(LineIndicatorFormat);
190
191impl Settings for LineIndicatorFormat {
192    const KEY: Option<&'static str> = Some("line_indicator_format");
193
194    type FileContent = Option<LineIndicatorFormatContent>;
195
196    fn load(
197        sources: SettingsSources<Self::FileContent>,
198        _: &mut AppContext,
199    ) -> anyhow::Result<Self> {
200        let format = [sources.release_channel, sources.user]
201            .into_iter()
202            .find_map(|value| value.copied().flatten())
203            .unwrap_or(sources.default.ok_or_else(Self::missing_default)?);
204
205        Ok(format.0)
206    }
207}