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