Skip to repository content

tenant.openagents/omega

No repository description is available.

OpenAgents Git authority 2026-07-28T04:00:22.631Z Public web read
NIP-34 coordinate30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omega
MaintainersHidden in public view
References2 branches · 1 tag
Read-only clonegit clone https://openagents.com/git/tenant.openagents/omega.git
Browse files

cursor_position.rs

329 lines · 12.9 KB · rust
1use editor::{Editor, EditorEvent, MBTextSummary, MultiBufferSnapshot};
2use gpui::{App, Entity, FocusHandle, Focusable, Styled, Subscription, Task, WeakEntity};
3use settings::{RegisterSetting, Settings};
4use std::{fmt::Write, num::NonZeroU32, time::Duration};
5use text::{Point, Selection};
6use ui::{
7    Button, ButtonCommon, Clickable, Context, FluentBuilder, IntoElement, LabelSize, ParentElement,
8    Render, Tooltip, Window, div,
9};
10use util::paths::FILE_ROW_COLUMN_DELIMITER;
11use workspace::{HideStatusItem, StatusBarSettings, StatusItemView, Workspace, item::ItemHandle};
12
13#[derive(Copy, Clone, Debug, Default, PartialOrd, PartialEq)]
14pub(crate) struct SelectionStats {
15    pub lines: usize,
16    pub characters: usize,
17    pub selections: usize,
18}
19
20pub struct CursorPosition {
21    position: Option<UserCaretPosition>,
22    selected_count: SelectionStats,
23    context: Option<FocusHandle>,
24    workspace: WeakEntity<Workspace>,
25    update_position: Task<()>,
26    _observe_active_editor: Option<Subscription>,
27}
28
29/// A position in the editor, where user's caret is located at.
30/// Lines are never zero as there is always at least one line in the editor.
31/// Characters may start with zero as the caret may be at the beginning of a line, but all editors start counting characters from 1,
32/// where "1" will mean "before the first character".
33#[derive(Copy, Clone, Debug, PartialEq, Eq)]
34pub struct UserCaretPosition {
35    pub line: NonZeroU32,
36    pub character: NonZeroU32,
37}
38
39impl UserCaretPosition {
40    pub(crate) fn at_selection_end(
41        selection: &Selection<Point>,
42        snapshot: &MultiBufferSnapshot,
43    ) -> Self {
44        let selection_end = selection.head();
45        let (line, character) =
46            if let Some((buffer_snapshot, point)) = snapshot.point_to_buffer_point(selection_end) {
47                let line_start = Point::new(point.row, 0);
48
49                let chars_to_last_position = buffer_snapshot
50                    .text_summary_for_range::<text::TextSummary, _>(line_start..point)
51                    .chars as u32;
52                (line_start.row, chars_to_last_position)
53            } else {
54                let line_start = Point::new(selection_end.row, 0);
55
56                let chars_to_last_position = snapshot
57                    .text_summary_for_range::<MBTextSummary, _>(line_start..selection_end)
58                    .chars as u32;
59                (selection_end.row, chars_to_last_position)
60            };
61
62        Self {
63            line: NonZeroU32::new(line + 1).expect("added 1"),
64            character: NonZeroU32::new(character + 1).expect("added 1"),
65        }
66    }
67}
68
69impl CursorPosition {
70    pub fn new(workspace: &Workspace) -> Self {
71        Self {
72            position: None,
73            context: None,
74            selected_count: Default::default(),
75            workspace: workspace.weak_handle(),
76            update_position: Task::ready(()),
77            _observe_active_editor: None,
78        }
79    }
80
81    fn update_position(
82        &mut self,
83        editor: &Entity<Editor>,
84        debounce: Option<Duration>,
85        window: &mut Window,
86        cx: &mut Context<Self>,
87    ) {
88        let editor = editor.downgrade();
89        self.update_position = cx.spawn_in(window, async move |cursor_position, cx| {
90            let is_singleton = editor
91                .update(cx, |editor, cx| editor.buffer().read(cx).is_singleton())
92                .ok()
93                .unwrap_or(true);
94
95            if !is_singleton && let Some(debounce) = debounce {
96                cx.background_executor().timer(debounce).await;
97            }
98
99            editor
100                .update(cx, |editor, cx| {
101                    cursor_position.update(cx, |cursor_position, cx| {
102                        cursor_position.selected_count = SelectionStats::default();
103                        cursor_position.selected_count.selections = editor.selections.count();
104                        match editor.mode() {
105                            editor::EditorMode::AutoHeight { .. }
106                            | editor::EditorMode::SingleLine
107                            | editor::EditorMode::Minimap { .. } => {
108                                cursor_position.position = None;
109                                cursor_position.context = None;
110                            }
111                            editor::EditorMode::Full { .. } => {
112                                let mut last_selection = None::<Selection<Point>>;
113                                let snapshot = editor.display_snapshot(cx);
114                                if snapshot.buffer_snapshot().excerpts().count() > 0 {
115                                    for selection in editor.selections.all_adjusted(&snapshot) {
116                                        let selection_summary = snapshot
117                                            .buffer_snapshot()
118                                            .text_summary_for_range::<MBTextSummary, _>(
119                                            selection.start..selection.end,
120                                        );
121                                        cursor_position.selected_count.characters +=
122                                            selection_summary.chars;
123                                        if selection.end != selection.start {
124                                            cursor_position.selected_count.lines +=
125                                                (selection.end.row - selection.start.row) as usize;
126                                            if selection.end.column != 0 {
127                                                cursor_position.selected_count.lines += 1;
128                                            }
129                                        }
130                                        if last_selection.as_ref().is_none_or(|last_selection| {
131                                            selection.id > last_selection.id
132                                        }) {
133                                            last_selection = Some(selection);
134                                        }
135                                    }
136                                }
137                                cursor_position.position = last_selection.map(|s| {
138                                    UserCaretPosition::at_selection_end(
139                                        &s,
140                                        snapshot.buffer_snapshot(),
141                                    )
142                                });
143                                cursor_position.context = Some(editor.focus_handle(cx));
144                            }
145                        }
146
147                        cx.notify();
148                    })
149                })
150                .ok()
151                .transpose()
152                .ok()
153                .flatten();
154        });
155    }
156
157    fn write_position(&self, text: &mut String, cx: &App) {
158        if self.selected_count
159            <= (SelectionStats {
160                selections: 1,
161                ..Default::default()
162            })
163        {
164            // Do not write out anything if we have just one empty selection.
165            return;
166        }
167        let SelectionStats {
168            lines,
169            characters,
170            selections,
171        } = self.selected_count;
172        let format = LineIndicatorFormat::get(None, cx);
173        let is_short_format = format == &LineIndicatorFormat::Short;
174        let lines = (lines > 1).then_some((lines, "line"));
175        let selections = (selections > 1).then_some((selections, "selection"));
176        let characters = (characters > 0).then_some((characters, "character"));
177        if (None, None, None) == (characters, selections, lines) {
178            // Nothing to display.
179            return;
180        }
181        write!(text, " (").unwrap();
182        let mut wrote_once = false;
183        for (count, name) in [selections, lines, characters].into_iter().flatten() {
184            if wrote_once {
185                write!(text, ", ").unwrap();
186            }
187            let name = if is_short_format { &name[..1] } else { name };
188            let plural_suffix = if count > 1 && !is_short_format {
189                "s"
190            } else {
191                ""
192            };
193            write!(text, "{count} {name}{plural_suffix}").unwrap();
194            wrote_once = true;
195        }
196        text.push(')');
197    }
198
199    #[cfg(test)]
200    pub(crate) fn selection_stats(&self) -> &SelectionStats {
201        &self.selected_count
202    }
203
204    #[cfg(test)]
205    pub(crate) fn position(&self) -> Option<UserCaretPosition> {
206        self.position
207    }
208}
209
210impl Render for CursorPosition {
211    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
212        if !StatusBarSettings::get_global(cx).cursor_position_button {
213            return div().hidden();
214        }
215
216        div().when_some(self.position, |el, position| {
217            let mut text = format!(
218                "{}{FILE_ROW_COLUMN_DELIMITER}{}",
219                position.line, position.character,
220            );
221            self.write_position(&mut text, cx);
222
223            let context = self.context.clone();
224
225            el.child(
226                Button::new("go-to-line-column", text)
227                    .label_size(LabelSize::Small)
228                    .tab_index(0isize)
229                    .aria_label(format!(
230                        "Line {}, column {}",
231                        position.line, position.character
232                    ))
233                    .on_click(cx.listener(|this, _, window, cx| {
234                        if let Some(workspace) = this.workspace.upgrade() {
235                            workspace.update(cx, |workspace, cx| {
236                                if let Some(editor) = workspace
237                                    .active_item(cx)
238                                    .and_then(|item| item.act_as::<Editor>(cx))
239                                    && let Some(buffer) = editor.read(cx).active_buffer(cx)
240                                {
241                                    workspace.toggle_modal(window, cx, |window, cx| {
242                                        crate::GoToLine::new(editor, buffer, window, cx)
243                                    })
244                                }
245                            });
246                        }
247                    }))
248                    .tooltip(move |_window, cx| match context.as_ref() {
249                        Some(context) => Tooltip::for_action_in(
250                            "Go to Line/Column",
251                            &editor::actions::ToggleGoToLine,
252                            context,
253                            cx,
254                        ),
255                        None => Tooltip::for_action(
256                            "Go to Line/Column",
257                            &editor::actions::ToggleGoToLine,
258                            cx,
259                        ),
260                    }),
261            )
262        })
263    }
264}
265
266const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
267
268impl StatusItemView for CursorPosition {
269    fn set_active_pane_item(
270        &mut self,
271        active_pane_item: Option<&dyn ItemHandle>,
272        window: &mut Window,
273        cx: &mut Context<Self>,
274    ) {
275        if let Some(editor) = active_pane_item.and_then(|item| item.act_as::<Editor>(cx)) {
276            self._observe_active_editor = Some(cx.subscribe_in(
277                &editor,
278                window,
279                |cursor_position, editor, event, window, cx| match event {
280                    EditorEvent::SelectionsChanged { .. } => Self::update_position(
281                        cursor_position,
282                        editor,
283                        Some(UPDATE_DEBOUNCE),
284                        window,
285                        cx,
286                    ),
287                    _ => {}
288                },
289            ));
290            self.update_position(&editor, None, window, cx);
291        } else {
292            self.position = None;
293            self._observe_active_editor = None;
294        }
295
296        cx.notify();
297    }
298
299    fn hide_setting(&self, _: &App) -> Option<HideStatusItem> {
300        Some(HideStatusItem::new(|settings| {
301            settings
302                .status_bar
303                .get_or_insert_default()
304                .cursor_position_button = Some(false);
305        }))
306    }
307}
308
309#[derive(Clone, Copy, PartialEq, Eq, RegisterSetting)]
310pub enum LineIndicatorFormat {
311    Short,
312    Long,
313}
314
315impl From<settings::LineIndicatorFormat> for LineIndicatorFormat {
316    fn from(format: settings::LineIndicatorFormat) -> Self {
317        match format {
318            settings::LineIndicatorFormat::Short => LineIndicatorFormat::Short,
319            settings::LineIndicatorFormat::Long => LineIndicatorFormat::Long,
320        }
321    }
322}
323
324impl Settings for LineIndicatorFormat {
325    fn from_settings(content: &settings::SettingsContent) -> Self {
326        content.line_indicator_format.unwrap().into()
327    }
328}
329
Served at tenant.openagents/omega Member data and write actions are omitted.