1use editor::{Editor, MultiBufferSnapshot};
2use gpui::{App, Entity, FocusHandle, Focusable, 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 editor.selections.all_adjusted(cx) {
117 let selection_summary = snapshot
118 .text_summary_for_range::<text::TextSummary, _>(
119 selection.start..selection.end,
120 );
121 cursor_position.selected_count.characters +=
122 selection_summary.chars;
123 if selection.end != selection.start {
124 cursor_position.selected_count.lines +=
125 (selection.end.row - selection.start.row) as usize;
126 if selection.end.column != 0 {
127 cursor_position.selected_count.lines += 1;
128 }
129 }
130 if last_selection.as_ref().is_none_or(|last_selection| {
131 selection.id > last_selection.id
132 }) {
133 last_selection = Some(selection);
134 }
135 }
136 }
137 cursor_position.position = last_selection
138 .map(|s| UserCaretPosition::at_selection_end(&s, &snapshot));
139 cursor_position.context = Some(editor.focus_handle(cx));
140 }
141 }
142
143 cx.notify();
144 })
145 })
146 .ok()
147 .transpose()
148 .ok()
149 .flatten();
150 });
151 }
152
153 fn write_position(&self, text: &mut String, cx: &App) {
154 if self.selected_count
155 <= (SelectionStats {
156 selections: 1,
157 ..Default::default()
158 })
159 {
160 // Do not write out anything if we have just one empty selection.
161 return;
162 }
163 let SelectionStats {
164 lines,
165 characters,
166 selections,
167 } = self.selected_count;
168 let format = LineIndicatorFormat::get(None, cx);
169 let is_short_format = format == &LineIndicatorFormat::Short;
170 let lines = (lines > 1).then_some((lines, "line"));
171 let selections = (selections > 1).then_some((selections, "selection"));
172 let characters = (characters > 0).then_some((characters, "character"));
173 if (None, None, None) == (characters, selections, lines) {
174 // Nothing to display.
175 return;
176 }
177 write!(text, " (").unwrap();
178 let mut wrote_once = false;
179 for (count, name) in [selections, lines, characters].into_iter().flatten() {
180 if wrote_once {
181 write!(text, ", ").unwrap();
182 }
183 let name = if is_short_format { &name[..1] } else { name };
184 let plural_suffix = if count > 1 && !is_short_format {
185 "s"
186 } else {
187 ""
188 };
189 write!(text, "{count} {name}{plural_suffix}").unwrap();
190 wrote_once = true;
191 }
192 text.push(')');
193 }
194
195 #[cfg(test)]
196 pub(crate) fn selection_stats(&self) -> &SelectionStats {
197 &self.selected_count
198 }
199
200 #[cfg(test)]
201 pub(crate) fn position(&self) -> Option<UserCaretPosition> {
202 self.position
203 }
204}
205
206impl Render for CursorPosition {
207 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
208 if !StatusBarSettings::get_global(cx).cursor_position_button {
209 return div();
210 }
211
212 div().when_some(self.position, |el, position| {
213 let mut text = format!(
214 "{}{FILE_ROW_COLUMN_DELIMITER}{}",
215 position.line, position.character,
216 );
217 self.write_position(&mut text, cx);
218
219 let context = self.context.clone();
220
221 el.child(
222 Button::new("go-to-line-column", text)
223 .label_size(LabelSize::Small)
224 .on_click(cx.listener(|this, _, window, cx| {
225 if let Some(workspace) = this.workspace.upgrade() {
226 workspace.update(cx, |workspace, cx| {
227 if let Some(editor) = workspace
228 .active_item(cx)
229 .and_then(|item| item.act_as::<Editor>(cx))
230 && let Some((_, buffer, _)) = editor.read(cx).active_excerpt(cx)
231 {
232 workspace.toggle_modal(window, cx, |window, cx| {
233 crate::GoToLine::new(editor, buffer, window, cx)
234 })
235 }
236 });
237 }
238 }))
239 .tooltip(move |window, cx| match context.as_ref() {
240 Some(context) => Tooltip::for_action_in(
241 "Go to Line/Column",
242 &editor::actions::ToggleGoToLine,
243 context,
244 window,
245 cx,
246 ),
247 None => Tooltip::for_action(
248 "Go to Line/Column",
249 &editor::actions::ToggleGoToLine,
250 window,
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}