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