1use editor::{Editor, ToPoint};
2use gpui::{AppContext, Subscription, View, WeakView};
3use schemars::JsonSchema;
4use serde::{Deserialize, Serialize};
5use settings::{Settings, SettingsSources};
6use std::fmt::Write;
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, Default, PartialOrd, PartialEq)]
16struct SelectionStats {
17 lines: usize,
18 characters: usize,
19 selections: usize,
20}
21
22pub struct CursorPosition {
23 position: Option<Point>,
24 selected_count: SelectionStats,
25 workspace: WeakView<Workspace>,
26 _observe_active_editor: Option<Subscription>,
27}
28
29impl CursorPosition {
30 pub fn new(workspace: &Workspace) -> Self {
31 Self {
32 position: None,
33 selected_count: Default::default(),
34 workspace: workspace.weak_handle(),
35 _observe_active_editor: None,
36 }
37 }
38
39 fn update_position(&mut self, editor: View<Editor>, cx: &mut ViewContext<Self>) {
40 let editor = editor.read(cx);
41 let buffer = editor.buffer().read(cx).snapshot(cx);
42
43 self.selected_count = Default::default();
44 self.selected_count.selections = editor.selections.count();
45 let mut last_selection: Option<Selection<usize>> = None;
46 for selection in editor.selections.all::<usize>(cx) {
47 self.selected_count.characters += selection.end - selection.start;
48 if last_selection
49 .as_ref()
50 .map_or(true, |last_selection| selection.id > last_selection.id)
51 {
52 last_selection = Some(selection);
53 }
54 }
55 for selection in editor.selections.all::<Point>(cx) {
56 if selection.end != selection.start {
57 self.selected_count.lines += (selection.end.row - selection.start.row) as usize;
58 if selection.end.column != 0 {
59 self.selected_count.lines += 1;
60 }
61 }
62 }
63 self.position = last_selection.map(|s| s.head().to_point(&buffer));
64
65 cx.notify();
66 }
67
68 fn write_position(&self, text: &mut String, cx: &AppContext) {
69 if self.selected_count
70 <= (SelectionStats {
71 selections: 1,
72 ..Default::default()
73 })
74 {
75 // Do not write out anything if we have just one empty selection.
76 return;
77 }
78 let SelectionStats {
79 lines,
80 characters,
81 selections,
82 } = self.selected_count;
83 let format = LineIndicatorFormat::get(None, cx);
84 let is_short_format = format == &LineIndicatorFormat::Short;
85 let lines = (lines > 1).then_some((lines, "line"));
86 let selections = (selections > 1).then_some((selections, "selection"));
87 let characters = (characters > 0).then_some((characters, "character"));
88 if (None, None, None) == (characters, selections, lines) {
89 // Nothing to display.
90 return;
91 }
92 write!(text, " (").unwrap();
93 let mut wrote_once = false;
94 for (count, name) in [selections, lines, characters].into_iter().flatten() {
95 if wrote_once {
96 write!(text, ", ").unwrap();
97 }
98 let name = if is_short_format { &name[..1] } else { &name };
99 let plural_suffix = if count > 1 && !is_short_format {
100 "s"
101 } else {
102 ""
103 };
104 write!(text, "{count} {name}{plural_suffix}").unwrap();
105 wrote_once = true;
106 }
107 text.push(')');
108 }
109}
110
111impl Render for CursorPosition {
112 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
113 div().when_some(self.position, |el, position| {
114 let mut text = format!(
115 "{}{FILE_ROW_COLUMN_DELIMITER}{}",
116 position.row + 1,
117 position.column + 1
118 );
119 self.write_position(&mut text, cx);
120
121 el.child(
122 Button::new("go-to-line-column", text)
123 .label_size(LabelSize::Small)
124 .on_click(cx.listener(|this, _, cx| {
125 if let Some(workspace) = this.workspace.upgrade() {
126 workspace.update(cx, |workspace, cx| {
127 if let Some(editor) = workspace
128 .active_item(cx)
129 .and_then(|item| item.act_as::<Editor>(cx))
130 {
131 workspace
132 .toggle_modal(cx, |cx| crate::GoToLine::new(editor, cx))
133 }
134 });
135 }
136 }))
137 .tooltip(|cx| Tooltip::for_action("Go to Line/Column", &crate::Toggle, cx)),
138 )
139 })
140 }
141}
142
143impl StatusItemView for CursorPosition {
144 fn set_active_pane_item(
145 &mut self,
146 active_pane_item: Option<&dyn ItemHandle>,
147 cx: &mut ViewContext<Self>,
148 ) {
149 if let Some(editor) = active_pane_item.and_then(|item| item.act_as::<Editor>(cx)) {
150 self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
151 self.update_position(editor, cx);
152 } else {
153 self.position = None;
154 self._observe_active_editor = None;
155 }
156
157 cx.notify();
158 }
159}
160
161#[derive(Clone, Copy, Default, PartialEq, JsonSchema, Deserialize, Serialize)]
162#[serde(rename_all = "snake_case")]
163pub(crate) enum LineIndicatorFormat {
164 Short,
165 #[default]
166 Long,
167}
168
169/// Whether or not to automatically check for updates.
170///
171/// Values: short, long
172/// Default: short
173#[derive(Clone, Copy, Default, JsonSchema, Deserialize, Serialize)]
174#[serde(transparent)]
175pub(crate) struct LineIndicatorFormatContent(LineIndicatorFormat);
176
177impl Settings for LineIndicatorFormat {
178 const KEY: Option<&'static str> = Some("line_indicator_format");
179
180 type FileContent = Option<LineIndicatorFormatContent>;
181
182 fn load(
183 sources: SettingsSources<Self::FileContent>,
184 _: &mut AppContext,
185 ) -> anyhow::Result<Self> {
186 let format = [sources.release_channel, sources.user]
187 .into_iter()
188 .find_map(|value| value.copied().flatten())
189 .unwrap_or(sources.default.ok_or_else(Self::missing_default)?);
190
191 Ok(format.0)
192 }
193}