1use editor::{Editor, MultiBufferSnapshot};
2use gpui::{App, Entity, FocusHandle, Focusable, Styled, Subscription, Task, WeakEntity};
3use settings::Settings;
4use std::{fmt::Write, num::NonZeroU32, time::Duration};
5use text::{Point, Selection};
6use ui::{
7 Button, ButtonCommon, Clickable, Context, FluentBuilder, IntoElement, LabelSize, ParentElement,
8 Render, Tooltip, Window, div,
9};
10use util::paths::FILE_ROW_COLUMN_DELIMITER;
11use workspace::{StatusBarSettings, StatusItemView, Workspace, item::ItemHandle};
12
13#[derive(Copy, Clone, Debug, Default, PartialOrd, PartialEq)]
14pub(crate) struct SelectionStats {
15 pub lines: usize,
16 pub characters: usize,
17 pub selections: usize,
18}
19
20pub struct CursorPosition {
21 position: Option<UserCaretPosition>,
22 selected_count: SelectionStats,
23 context: Option<FocusHandle>,
24 workspace: WeakEntity<Workspace>,
25 update_position: Task<()>,
26 _observe_active_editor: Option<Subscription>,
27}
28
29/// A position in the editor, where user's caret is located at.
30/// Lines are never zero as there is always at least one line in the editor.
31/// Characters may start with zero as the caret may be at the beginning of a line, but all editors start counting characters from 1,
32/// where "1" will mean "before the first character".
33#[derive(Copy, Clone, Debug, PartialEq, Eq)]
34pub struct UserCaretPosition {
35 pub line: NonZeroU32,
36 pub character: NonZeroU32,
37}
38
39impl UserCaretPosition {
40 pub(crate) fn at_selection_end(
41 selection: &Selection<Point>,
42 snapshot: &MultiBufferSnapshot,
43 ) -> Self {
44 let selection_end = selection.head();
45 let (line, character) = if let Some((buffer_snapshot, point, _)) =
46 snapshot.point_to_buffer_point(selection_end)
47 {
48 let line_start = Point::new(point.row, 0);
49
50 let chars_to_last_position = buffer_snapshot
51 .text_summary_for_range::<text::TextSummary, _>(line_start..point)
52 .chars as u32;
53 (line_start.row, chars_to_last_position)
54 } else {
55 let line_start = Point::new(selection_end.row, 0);
56
57 let chars_to_last_position = snapshot
58 .text_summary_for_range::<text::TextSummary, _>(line_start..selection_end)
59 .chars as u32;
60 (selection_end.row, chars_to_last_position)
61 };
62
63 Self {
64 line: NonZeroU32::new(line + 1).expect("added 1"),
65 character: NonZeroU32::new(character + 1).expect("added 1"),
66 }
67 }
68}
69
70impl CursorPosition {
71 pub fn new(workspace: &Workspace) -> Self {
72 Self {
73 position: None,
74 context: None,
75 selected_count: Default::default(),
76 workspace: workspace.weak_handle(),
77 update_position: Task::ready(()),
78 _observe_active_editor: None,
79 }
80 }
81
82 fn update_position(
83 &mut self,
84 editor: Entity<Editor>,
85 debounce: Option<Duration>,
86 window: &mut Window,
87 cx: &mut Context<Self>,
88 ) {
89 let editor = editor.downgrade();
90 self.update_position = cx.spawn_in(window, async move |cursor_position, cx| {
91 let is_singleton = editor
92 .update(cx, |editor, cx| editor.buffer().read(cx).is_singleton())
93 .ok()
94 .unwrap_or(true);
95
96 if !is_singleton && let Some(debounce) = debounce {
97 cx.background_executor().timer(debounce).await;
98 }
99
100 editor
101 .update(cx, |editor, cx| {
102 cursor_position.update(cx, |cursor_position, cx| {
103 cursor_position.selected_count = SelectionStats::default();
104 cursor_position.selected_count.selections = editor.selections.count();
105 match editor.mode() {
106 editor::EditorMode::AutoHeight { .. }
107 | editor::EditorMode::SingleLine
108 | editor::EditorMode::Minimap { .. } => {
109 cursor_position.position = None;
110 cursor_position.context = None;
111 }
112 editor::EditorMode::Full { .. } => {
113 let mut last_selection = None::<Selection<Point>>;
114 let snapshot = editor.buffer().read(cx).snapshot(cx);
115 if snapshot.excerpts().count() > 0 {
116 for selection in
117 editor.selections.all_adjusted_with_snapshot(&snapshot)
118 {
119 let selection_summary = snapshot
120 .text_summary_for_range::<text::TextSummary, _>(
121 selection.start..selection.end,
122 );
123 cursor_position.selected_count.characters +=
124 selection_summary.chars;
125 if selection.end != selection.start {
126 cursor_position.selected_count.lines +=
127 (selection.end.row - selection.start.row) as usize;
128 if selection.end.column != 0 {
129 cursor_position.selected_count.lines += 1;
130 }
131 }
132 if last_selection.as_ref().is_none_or(|last_selection| {
133 selection.id > last_selection.id
134 }) {
135 last_selection = Some(selection);
136 }
137 }
138 }
139 cursor_position.position = last_selection
140 .map(|s| UserCaretPosition::at_selection_end(&s, &snapshot));
141 cursor_position.context = Some(editor.focus_handle(cx));
142 }
143 }
144
145 cx.notify();
146 })
147 })
148 .ok()
149 .transpose()
150 .ok()
151 .flatten();
152 });
153 }
154
155 fn write_position(&self, text: &mut String, cx: &App) {
156 if self.selected_count
157 <= (SelectionStats {
158 selections: 1,
159 ..Default::default()
160 })
161 {
162 // Do not write out anything if we have just one empty selection.
163 return;
164 }
165 let SelectionStats {
166 lines,
167 characters,
168 selections,
169 } = self.selected_count;
170 let format = LineIndicatorFormat::get(None, cx);
171 let is_short_format = format == &LineIndicatorFormat::Short;
172 let lines = (lines > 1).then_some((lines, "line"));
173 let selections = (selections > 1).then_some((selections, "selection"));
174 let characters = (characters > 0).then_some((characters, "character"));
175 if (None, None, None) == (characters, selections, lines) {
176 // Nothing to display.
177 return;
178 }
179 write!(text, " (").unwrap();
180 let mut wrote_once = false;
181 for (count, name) in [selections, lines, characters].into_iter().flatten() {
182 if wrote_once {
183 write!(text, ", ").unwrap();
184 }
185 let name = if is_short_format { &name[..1] } else { name };
186 let plural_suffix = if count > 1 && !is_short_format {
187 "s"
188 } else {
189 ""
190 };
191 write!(text, "{count} {name}{plural_suffix}").unwrap();
192 wrote_once = true;
193 }
194 text.push(')');
195 }
196
197 #[cfg(test)]
198 pub(crate) fn selection_stats(&self) -> &SelectionStats {
199 &self.selected_count
200 }
201
202 #[cfg(test)]
203 pub(crate) fn position(&self) -> Option<UserCaretPosition> {
204 self.position
205 }
206}
207
208impl Render for CursorPosition {
209 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
210 if !StatusBarSettings::get_global(cx).cursor_position_button {
211 return div().hidden();
212 }
213
214 div().when_some(self.position, |el, position| {
215 let mut text = format!(
216 "{}{FILE_ROW_COLUMN_DELIMITER}{}",
217 position.line, position.character,
218 );
219 self.write_position(&mut text, cx);
220
221 let context = self.context.clone();
222
223 el.child(
224 Button::new("go-to-line-column", text)
225 .label_size(LabelSize::Small)
226 .on_click(cx.listener(|this, _, window, cx| {
227 if let Some(workspace) = this.workspace.upgrade() {
228 workspace.update(cx, |workspace, cx| {
229 if let Some(editor) = workspace
230 .active_item(cx)
231 .and_then(|item| item.act_as::<Editor>(cx))
232 && let Some((_, buffer, _)) = editor.read(cx).active_excerpt(cx)
233 {
234 workspace.toggle_modal(window, cx, |window, cx| {
235 crate::GoToLine::new(editor, buffer, window, cx)
236 })
237 }
238 });
239 }
240 }))
241 .tooltip(move |_window, cx| match context.as_ref() {
242 Some(context) => Tooltip::for_action_in(
243 "Go to Line/Column",
244 &editor::actions::ToggleGoToLine,
245 context,
246 cx,
247 ),
248 None => Tooltip::for_action(
249 "Go to Line/Column",
250 &editor::actions::ToggleGoToLine,
251 cx,
252 ),
253 }),
254 )
255 })
256 }
257}
258
259const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
260
261impl StatusItemView for CursorPosition {
262 fn set_active_pane_item(
263 &mut self,
264 active_pane_item: Option<&dyn ItemHandle>,
265 window: &mut Window,
266 cx: &mut Context<Self>,
267 ) {
268 if let Some(editor) = active_pane_item.and_then(|item| item.act_as::<Editor>(cx)) {
269 self._observe_active_editor =
270 Some(
271 cx.observe_in(&editor, window, |cursor_position, editor, window, cx| {
272 Self::update_position(
273 cursor_position,
274 editor,
275 Some(UPDATE_DEBOUNCE),
276 window,
277 cx,
278 )
279 }),
280 );
281 self.update_position(editor, None, window, cx);
282 } else {
283 self.position = None;
284 self._observe_active_editor = None;
285 }
286
287 cx.notify();
288 }
289}
290
291#[derive(Clone, Copy, PartialEq, Eq)]
292pub enum LineIndicatorFormat {
293 Short,
294 Long,
295}
296
297impl From<settings::LineIndicatorFormat> for LineIndicatorFormat {
298 fn from(format: settings::LineIndicatorFormat) -> Self {
299 match format {
300 settings::LineIndicatorFormat::Short => LineIndicatorFormat::Short,
301 settings::LineIndicatorFormat::Long => LineIndicatorFormat::Long,
302 }
303 }
304}
305
306impl Settings for LineIndicatorFormat {
307 fn from_settings(content: &settings::SettingsContent) -> Self {
308 content.line_indicator_format.unwrap().into()
309 }
310}