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