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| {
138 Tooltip::for_action(
139 "Go to Line/Column",
140 &editor::actions::ToggleGoToLine,
141 cx,
142 )
143 }),
144 )
145 })
146 }
147}
148
149impl StatusItemView for CursorPosition {
150 fn set_active_pane_item(
151 &mut self,
152 active_pane_item: Option<&dyn ItemHandle>,
153 cx: &mut ViewContext<Self>,
154 ) {
155 if let Some(editor) = active_pane_item.and_then(|item| item.act_as::<Editor>(cx)) {
156 self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
157 self.update_position(editor, cx);
158 } else {
159 self.position = None;
160 self._observe_active_editor = None;
161 }
162
163 cx.notify();
164 }
165}
166
167#[derive(Clone, Copy, Default, PartialEq, JsonSchema, Deserialize, Serialize)]
168#[serde(rename_all = "snake_case")]
169pub(crate) enum LineIndicatorFormat {
170 Short,
171 #[default]
172 Long,
173}
174
175/// Whether or not to automatically check for updates.
176///
177/// Values: short, long
178/// Default: short
179#[derive(Clone, Copy, Default, JsonSchema, Deserialize, Serialize)]
180#[serde(transparent)]
181pub(crate) struct LineIndicatorFormatContent(LineIndicatorFormat);
182
183impl Settings for LineIndicatorFormat {
184 const KEY: Option<&'static str> = Some("line_indicator_format");
185
186 type FileContent = Option<LineIndicatorFormatContent>;
187
188 fn load(
189 sources: SettingsSources<Self::FileContent>,
190 _: &mut AppContext,
191 ) -> anyhow::Result<Self> {
192 let format = [sources.release_channel, sources.user]
193 .into_iter()
194 .find_map(|value| value.copied().flatten())
195 .unwrap_or(sources.default.ok_or_else(Self::missing_default)?);
196
197 Ok(format.0)
198 }
199}