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>,
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 =
101 last_selection.map(|s| s.head().to_point(&buffer));
102 cursor_position.context = Some(editor.focus_handle(cx));
103 }
104 }
105
106 cx.notify();
107 })
108 })
109 .ok()
110 .transpose()
111 .ok()
112 .flatten();
113 });
114 }
115
116 fn write_position(&self, text: &mut String, cx: &AppContext) {
117 if self.selected_count
118 <= (SelectionStats {
119 selections: 1,
120 ..Default::default()
121 })
122 {
123 // Do not write out anything if we have just one empty selection.
124 return;
125 }
126 let SelectionStats {
127 lines,
128 characters,
129 selections,
130 } = self.selected_count;
131 let format = LineIndicatorFormat::get(None, cx);
132 let is_short_format = format == &LineIndicatorFormat::Short;
133 let lines = (lines > 1).then_some((lines, "line"));
134 let selections = (selections > 1).then_some((selections, "selection"));
135 let characters = (characters > 0).then_some((characters, "character"));
136 if (None, None, None) == (characters, selections, lines) {
137 // Nothing to display.
138 return;
139 }
140 write!(text, " (").unwrap();
141 let mut wrote_once = false;
142 for (count, name) in [selections, lines, characters].into_iter().flatten() {
143 if wrote_once {
144 write!(text, ", ").unwrap();
145 }
146 let name = if is_short_format { &name[..1] } else { name };
147 let plural_suffix = if count > 1 && !is_short_format {
148 "s"
149 } else {
150 ""
151 };
152 write!(text, "{count} {name}{plural_suffix}").unwrap();
153 wrote_once = true;
154 }
155 text.push(')');
156 }
157
158 #[cfg(test)]
159 pub(crate) fn selection_stats(&self) -> &SelectionStats {
160 &self.selected_count
161 }
162}
163
164impl Render for CursorPosition {
165 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
166 div().when_some(self.position, |el, position| {
167 let mut text = format!(
168 "{}{FILE_ROW_COLUMN_DELIMITER}{}",
169 position.row + 1,
170 position.column + 1
171 );
172 self.write_position(&mut text, cx);
173
174 let context = self.context.clone();
175
176 el.child(
177 Button::new("go-to-line-column", text)
178 .label_size(LabelSize::Small)
179 .on_click(cx.listener(|this, _, cx| {
180 if let Some(workspace) = this.workspace.upgrade() {
181 workspace.update(cx, |workspace, cx| {
182 if let Some(editor) = workspace
183 .active_item(cx)
184 .and_then(|item| item.act_as::<Editor>(cx))
185 {
186 workspace
187 .toggle_modal(cx, |cx| crate::GoToLine::new(editor, cx))
188 }
189 });
190 }
191 }))
192 .tooltip(move |cx| match context.as_ref() {
193 Some(context) => Tooltip::for_action_in(
194 "Go to Line/Column",
195 &editor::actions::ToggleGoToLine,
196 context,
197 cx,
198 ),
199 None => Tooltip::for_action(
200 "Go to Line/Column",
201 &editor::actions::ToggleGoToLine,
202 cx,
203 ),
204 }),
205 )
206 })
207 }
208}
209
210const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
211
212impl StatusItemView for CursorPosition {
213 fn set_active_pane_item(
214 &mut self,
215 active_pane_item: Option<&dyn ItemHandle>,
216 cx: &mut ViewContext<Self>,
217 ) {
218 if let Some(editor) = active_pane_item.and_then(|item| item.act_as::<Editor>(cx)) {
219 self._observe_active_editor =
220 Some(cx.observe(&editor, |cursor_position, editor, cx| {
221 Self::update_position(cursor_position, editor, Some(UPDATE_DEBOUNCE), cx)
222 }));
223 self.update_position(editor, None, cx);
224 } else {
225 self.position = None;
226 self._observe_active_editor = None;
227 }
228
229 cx.notify();
230 }
231}
232
233#[derive(Clone, Copy, Default, PartialEq, JsonSchema, Deserialize, Serialize)]
234#[serde(rename_all = "snake_case")]
235pub(crate) enum LineIndicatorFormat {
236 Short,
237 #[default]
238 Long,
239}
240
241/// Whether or not to automatically check for updates.
242///
243/// Values: short, long
244/// Default: short
245#[derive(Clone, Copy, Default, JsonSchema, Deserialize, Serialize)]
246#[serde(transparent)]
247pub(crate) struct LineIndicatorFormatContent(LineIndicatorFormat);
248
249impl Settings for LineIndicatorFormat {
250 const KEY: Option<&'static str> = Some("line_indicator_format");
251
252 type FileContent = Option<LineIndicatorFormatContent>;
253
254 fn load(
255 sources: SettingsSources<Self::FileContent>,
256 _: &mut AppContext,
257 ) -> anyhow::Result<Self> {
258 let format = [sources.release_channel, sources.user]
259 .into_iter()
260 .find_map(|value| value.copied().flatten())
261 .unwrap_or(sources.default.ok_or_else(Self::missing_default)?);
262
263 Ok(format.0)
264 }
265}