twrite-gpui 0.10.3

GPUI rendering, canvas text-shaping, and editor component for twrite
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
use gpui::prelude::*;
use gpui::{Context, Div, MouseButton, MouseDownEvent, Pixels, Point, Stateful, Window, div, px};
use twrite_core::{
    ContextMenuCaps, ContextMenuContext, ContextMenuItem, HookContext, HookOutcome, Selection,
    collect_context_items,
};

use super::Editor;

impl Editor {
    /// Opens the expandable right-click menu at the click position.
    ///
    /// Selection policy (VS Code style): a click inside the active
    /// selection keeps it; otherwise the cursor moves to the click and
    /// any selection collapses. Items merge built-in edit rows with
    /// hook-contributed rows (see [`collect_context_items`]).
    pub(crate) fn handle_right_click(
        &mut self,
        event: &MouseDownEvent,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        if !self.config.context_menu {
            return;
        }
        self.focus_handle.focus(window);
        self.reset_blink_cursor(cx);

        let offset = self.offset_for_position(event.position, window);
        let keep_selection = self
            .selection
            .is_some_and(|sel| !sel.byte_range().is_empty() && sel.byte_range().contains(&offset));
        if !keep_selection {
            self.buffer.set_cursor_offset(offset);
            self.selection = None;
            for hook in &mut self.hooks {
                hook.on_selection_change(&self.buffer, self.selection.as_ref());
            }
        }

        let point = self.buffer.offset_to_point(offset);
        let line_start = self
            .buffer
            .point_to_offset(twrite_core::Point::new(point.row, 0));
        let clicked_col = offset.saturating_sub(line_start);

        let clipboard_has_text = cx
            .read_from_clipboard()
            .and_then(|item| item.text())
            .is_some_and(|text| !text.is_empty());
        let caps =
            ContextMenuCaps::from_buffer(&self.buffer, self.selection.as_ref(), clipboard_has_text);

        let mut hook_rows = Vec::with_capacity(self.hooks.len());
        for hook in self.hooks.iter() {
            let menu_ctx = ContextMenuContext {
                buffer: &self.buffer,
                selection: self.selection.as_ref(),
                cursor_offset: self.buffer.cursor_offset(),
                clicked_row: point.row,
                clicked_col,
                caps,
            };
            hook_rows.push(hook.context_menu_items(&menu_ctx));
        }
        let items = collect_context_items(self.config.show_default_menu_items, caps, hook_rows);
        if items.is_empty() {
            self.dismiss_context_menu(cx);
            return;
        }

        self.context_menu.open(items);
        self.context_menu_anchor = Some(event.position);
        self.context_menu_selected = None;
        self.flush_effects();
        cx.notify();
    }

    /// Runs a menu row activation: hooks first, then built-in edit actions.
    pub(crate) fn dispatch_context_menu_action(
        &mut self,
        id: &str,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.reset_blink_cursor(cx);
        let enabled = self
            .context_menu
            .items()
            .iter()
            .find(|item| item.id == id)
            .is_some_and(|item| item.enabled);
        if !enabled {
            return;
        }

        let initial_version = self.buffer.version();
        let mut consumed = false;
        let mut hook_idx = 0;
        while hook_idx < self.hooks.len() {
            let mut ctx = HookContext::new(
                &mut self.buffer,
                &mut self.selection,
                &mut self.cursor_style,
                &mut self.prompt,
                &mut self.pending_effects,
            );
            if self.hooks[hook_idx].on_context_menu_action(&mut ctx, id) == HookOutcome::Consumed {
                consumed = true;
                break;
            }
            hook_idx += 1;
        }

        let mut edited = false;
        if !consumed {
            edited = self.run_builtin_menu_action(id, cx);
        } else if self.buffer.version() != initial_version {
            edited = true;
        }

        if edited {
            for hook in &mut self.hooks {
                hook.after_edit(&mut self.buffer);
            }
        }
        for hook in &mut self.hooks {
            hook.on_selection_change(&self.buffer, self.selection.as_ref());
        }

        self.context_menu.close();
        self.context_menu_anchor = None;
        self.context_menu_selected = None;
        self.scroll_to_cursor(Some(window));
        self.flush_effects();
        self.sync_search_state();
        cx.notify();
    }

    /// Executes a well-known edit id. Returns whether the buffer changed.
    /// Unknown ids are ignored (a hook was expected to consume them).
    fn run_builtin_menu_action(&mut self, id: &str, cx: &mut Context<Self>) -> bool {
        match id {
            twrite_core::UNDO_ID => {
                if self.buffer.can_undo() {
                    self.buffer.undo();
                    self.selection = None;
                    true
                } else {
                    false
                }
            }
            twrite_core::REDO_ID => {
                if self.buffer.can_redo() {
                    self.buffer.redo();
                    self.selection = None;
                    true
                } else {
                    false
                }
            }
            twrite_core::CUT_ID => self.cut(cx),
            twrite_core::COPY_ID => {
                self.copy(cx);
                false
            }
            twrite_core::PASTE_ID => self.paste(cx),
            twrite_core::DELETE_ID => {
                if self.delete_selection() {
                    self.selection = None;
                    true
                } else {
                    false
                }
            }
            twrite_core::SELECT_ALL_ID => {
                self.selection = Some(Selection::range(0, self.buffer.len_bytes()));
                false
            }
            _ => false,
        }
    }

    /// Closes the menu without running an action.
    pub(crate) fn dismiss_context_menu(&mut self, cx: &mut Context<Self>) {
        if self.context_menu.is_open() {
            self.context_menu.close();
            self.context_menu_anchor = None;
            self.context_menu_selected = None;
            cx.notify();
        }
    }

    /// Moves keyboard selection to the next / previous enabled row.
    pub(crate) fn move_context_menu_selection(&mut self, forward: bool, cx: &mut Context<Self>) {
        let items = self.context_menu.items();
        if items.is_empty() {
            return;
        }
        let len = items.len();
        let mut idx = self
            .context_menu_selected
            .unwrap_or(if forward { len - 1 } else { 0 });
        for _ in 0..len {
            idx = if forward {
                (idx + 1) % len
            } else {
                idx.checked_sub(1).unwrap_or(len - 1)
            };
            if items[idx].enabled {
                self.context_menu_selected = Some(idx);
                cx.notify();
                return;
            }
        }
    }

    /// Activates the keyboard-selected row, if any.
    pub(crate) fn activate_context_menu_selected(
        &mut self,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        if let Some(idx) = self.context_menu_selected
            && let Some(item) = self.context_menu.items().get(idx).cloned()
        {
            let id: &'static str = item.id;
            self.dispatch_context_menu_action(id, window, cx);
        }
    }

    /// Renders the open menu as an absolutely-positioned overlay.
    ///
    /// The anchor is clamped into `last_bounds` using the same fixed
    /// metrics the rows are drawn with, so the popup never overflows
    /// the viewport. The click anchor is window-space but the overlay
    /// positions relative to the editor root, so it is converted to
    /// editor-local coordinates first. Renders nothing when closed.
    pub(crate) fn render_context_menu(&self, cx: &mut Context<Self>) -> Div {
        if !self.context_menu.is_open() {
            return div();
        }
        const MENU_WIDTH: f32 = 230.0;
        const ROW_HEIGHT: f32 = 28.0;
        const DIVIDER_HEIGHT: f32 = 9.0;

        let items = self.context_menu.items();
        let mut height: f32 = 8.0;
        for item in items {
            height += ROW_HEIGHT;
            if item.divider_after {
                height += DIVIDER_HEIGHT;
            }
        }
        height += 8.0;

        let anchor = self
            .context_menu_anchor
            .unwrap_or(gpui::point(px(0.0), px(0.0)));
        let pos = menu_overlay_position(anchor, self.last_bounds, MENU_WIDTH, height);

        let mut list = div().flex().flex_col().py(px(4.0));
        for (idx, item) in items.iter().enumerate() {
            list = list.child(self.render_menu_row(
                item,
                idx,
                Some(idx) == self.context_menu_selected,
                cx,
            ));
            if item.divider_after {
                list = list.child(
                    div()
                        .mx(px(8.0))
                        .my(px(4.0))
                        .h(px(1.0))
                        .bg(self.theme.menu_border),
                );
            }
        }

        div()
            .absolute()
            .left(pos.x)
            .top(pos.y)
            .w(px(MENU_WIDTH))
            .rounded_md()
            .border_1()
            .border_color(self.theme.menu_border)
            .bg(self.theme.menu_bg)
            .shadow_lg()
            .on_mouse_down(MouseButton::Left, |_, _, cx| {
                cx.stop_propagation();
            })
            .child(list)
    }

    fn render_menu_row(
        &self,
        item: &ContextMenuItem,
        idx: usize,
        highlighted: bool,
        cx: &mut Context<Self>,
    ) -> Stateful<Div> {
        let id: &'static str = item.id;
        let enabled = item.enabled;
        let (fg, hint_color) = if enabled {
            (self.theme.menu_fg, self.theme.menu_hint)
        } else {
            (self.theme.menu_hint, self.theme.menu_hint)
        };
        let mut row = div()
            .id(("context-menu-item", idx))
            .flex()
            .flex_row()
            .items_center()
            .justify_between()
            .h(px(28.0))
            .px(px(12.0))
            .gap(px(16.0))
            .text_sm()
            .text_color(fg);

        if enabled {
            row = row.cursor_pointer();
            if highlighted {
                row = row.bg(self.theme.menu_hover);
            } else {
                row = row.hover(|s| s.bg(self.theme.menu_hover));
            }
        }

        // The label flexes and truncates with an ellipsis so long text
        // (e.g. "UPPERCASE selection" plus a hint) never overflows the
        // fixed-width popup. Structured hints render as one kbd chip per
        // part (modifiers in canonical order, then the key); the chip row
        // keeps its size via flex_shrink_0 so the label truncates first.
        let label = div().flex_1().truncate().child(item.label.clone());
        if let Some(hint) = &item.hint {
            let mut chips = div()
                .flex()
                .flex_row()
                .items_center()
                .gap(px(3.0))
                .flex_shrink_0();
            for part in hint.parts() {
                chips = chips.child(
                    div()
                        .px(px(4.0))
                        .rounded_sm()
                        .border_1()
                        .border_color(hint_color)
                        .text_size(px(10.0))
                        .text_color(hint_color)
                        .child(part),
                );
            }
            row = row.child(label).child(chips);
        } else {
            row = row.child(label);
        }

        if !enabled {
            return row;
        }
        row.on_mouse_down(
            MouseButton::Left,
            cx.listener(move |this, _event: &MouseDownEvent, window, cx| {
                this.dispatch_context_menu_action(id, window, cx);
                cx.stop_propagation();
            }),
        )
    }
}

/// Clamps a raw anchor into bounds using menu metrics (pure, testable).
pub(crate) fn clamp_menu_anchor(
    anchor: Point<Pixels>,
    bounds: gpui::Bounds<Pixels>,
    menu_width: f32,
    menu_height: f32,
) -> Point<Pixels> {
    gpui::point(
        anchor
            .x
            .min(bounds.right() - px(menu_width + 8.0))
            .max(bounds.left()),
        anchor
            .y
            .min(bounds.bottom() - px(menu_height + 8.0))
            .max(bounds.top()),
    )
}

/// Converts a window-space click anchor into editor-root-local overlay
/// coordinates (pure, testable).
///
/// The anchor is clamped into the canvas bounds in window space first,
/// then shifted by the editor origin. The editor root carries no
/// padding or border and its first child is the canvas wrapper, so the
/// root origin coincides with the canvas bounds origin. Without this
/// shift the popup drifts by the editor's window offset in nested
/// layouts (sidebar, toolbar, padding) and can land off-screen.
pub(crate) fn menu_overlay_position(
    anchor: Point<Pixels>,
    bounds: Option<gpui::Bounds<Pixels>>,
    menu_width: f32,
    menu_height: f32,
) -> Point<Pixels> {
    match bounds {
        Some(b) => {
            let clamped = clamp_menu_anchor(anchor, b, menu_width, menu_height);
            gpui::point(clamped.x - b.origin.x, clamped.y - b.origin.y)
        }
        None => anchor,
    }
}

#[cfg(test)]
mod tests {
    use super::{clamp_menu_anchor, menu_overlay_position};
    use gpui::{Bounds, point, px, size};

    #[test]
    fn anchor_clamps_into_bounds() {
        let bounds = Bounds::new(point(px(0.0), px(0.0)), size(px(800.0), px(600.0)));
        let clamped = clamp_menu_anchor(point(px(790.0), px(590.0)), bounds, 230.0, 200.0);
        assert_eq!(clamped, point(px(562.0), px(392.0)));
        let inside = clamp_menu_anchor(point(px(100.0), px(100.0)), bounds, 230.0, 200.0);
        assert_eq!(inside, point(px(100.0), px(100.0)));
    }

    #[test]
    fn overlay_position_shifts_window_anchor_into_editor_space() {
        // Nested editor: canvas starts at window (300, 70).
        let bounds = Bounds::new(point(px(300.0), px(70.0)), size(px(500.0), px(400.0)));
        let pos = menu_overlay_position(point(px(400.0), px(200.0)), Some(bounds), 230.0, 100.0);
        assert_eq!(pos, point(px(100.0), px(130.0)));
    }

    #[test]
    fn overlay_position_clamps_before_shifting() {
        // Click near the canvas bottom-right: clamp pulls the anchor
        // inside first, then the editor origin is subtracted.
        let bounds = Bounds::new(point(px(300.0), px(70.0)), size(px(500.0), px(400.0)));
        let pos = menu_overlay_position(point(px(790.0), px(460.0)), Some(bounds), 230.0, 100.0);
        // Clamped to (562, 362) in window space, then shifted to editor space.
        assert_eq!(pos, point(px(262.0), px(292.0)));
    }

    #[test]
    fn overlay_position_without_bounds_passes_anchor_through() {
        let pos = menu_overlay_position(point(px(400.0), px(200.0)), None, 230.0, 100.0);
        assert_eq!(pos, point(px(400.0), px(200.0)));
    }
}