neovide 0.17.6

Neovide: No Nonsense Neovim Gui
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
use glamour::Intersection;
use itertools::Itertools;
use skia_safe::BlendMode;
use skia_safe::Canvas;
use skia_safe::ClipOp;
use skia_safe::Color;
use skia_safe::Paint;
use skia_safe::Path;
use skia_safe::PathOp;
use skia_safe::Point3;
use skia_safe::RRect;
use skia_safe::Rect;
use skia_safe::canvas::SaveLayerRec;
use skia_safe::image_filters::blur;
use skia_safe::utils::shadow_utils::ShadowFlags;
use skia_safe::utils::shadow_utils::draw_shadow;

use super::RenderedWindow;
use super::RendererSettings;
use super::WindowDrawDetails;
use super::is_rightmost_window_edge;
use crate::editor::WindowType;
use crate::units::GridScale;
use crate::units::PixelRect;
use crate::units::to_skia_rect;

struct LayerWindow<'w> {
    window: &'w mut RenderedWindow,
    group: usize,
}

/// A nonempty group of windows borrowed for one frame, in draw order. The
/// renderer owns the windows and rebuilds their groups before drawing. This
/// layer keeps no geometry across frames. [`Self::draw`] requires at least
/// one window because [`build_silhouette`] derives both its path and bounds
/// from the first rectangle.
pub struct FloatingLayer<'w> {
    pub windows: Vec<&'w mut RenderedWindow>,
}

impl FloatingLayer<'_> {
    /// The grid silhouette with the drawable edge backgrounds included.
    /// Expansion alone does not prove a window has a background to extend.
    /// The cached fills supply the added paths, and a window with no fills
    /// leaves the clip and bounds unchanged. The resulting clip and bounds
    /// are shared by the blur and compositing passes.
    fn build_draw_clip_and_bounds(
        &self,
        mut draw_clip: Path,
        mut draw_bound_rect: Rect,
        expanded_regions: &[PixelRect<f32>],
        grid_scale: GridScale,
    ) -> (Path, Rect) {
        for (window, region) in self.windows.iter().zip(expanded_regions.iter().copied()) {
            if let Some((path, bounds)) = window.edge_background_path_and_bounds(region, grid_scale)
            {
                include_path_bounds(&mut draw_clip, &mut draw_bound_rect, &path, bounds);
            }
        }

        (draw_clip, draw_bound_rect)
    }

    pub fn draw(
        &mut self,
        root_canvas: &Canvas,
        settings: &RendererSettings,
        default_background: Color,
        grid_scale: GridScale,
        content_region: Option<PixelRect<f32>>,
        bottom_fill_y: Option<f32>,
    ) -> Vec<WindowDrawDetails> {
        let pixel_regions =
            self.windows.iter().map(|window| window.pixel_region(grid_scale)).collect::<Vec<_>>();

        // Edge regions are calculated again for this frame. The grid
        // regions below still place the text and its clips. Using a taller
        // foreground region could expose the extra line that smooth
        // scrolling keeps beyond the viewport.
        let regions = self.expand_edges(&pixel_regions, grid_scale, content_region, bottom_fill_y);

        let (silhouette, bound_rect) = build_silhouette(&pixel_regions, settings, grid_scale);
        let (draw_clip, draw_bound_rect) =
            self.build_draw_clip_and_bounds(silhouette.clone(), bound_rect, &regions, grid_scale);
        let has_transparency = self.windows.iter().any(|window| window.has_transparency());

        self._draw_shadow(root_canvas, &silhouette, settings);

        root_canvas.save();
        root_canvas.clip_path(&draw_clip, None, Some(false));
        let need_blur = has_transparency || settings.floating_blur;
        if need_blur
            && let Some(blur) = blur(
                (settings.floating_blur_amount_x, settings.floating_blur_amount_y),
                None,
                None,
                None,
            )
        {
            let paint =
                Paint::default().set_anti_alias(false).set_blend_mode(BlendMode::Src).to_owned();
            let save_layer_rec =
                SaveLayerRec::default().backdrop(&blur).bounds(&draw_bound_rect).paint(&paint);
            root_canvas.save_layer(&save_layer_rec);
            root_canvas.restore();
        }

        let paint =
            Paint::default().set_anti_alias(false).set_blend_mode(BlendMode::SrcOver).to_owned();

        let save_layer_rec = SaveLayerRec::default().bounds(&draw_bound_rect).paint(&paint);

        root_canvas.save_layer(&save_layer_rec);
        let background_paint = Paint::default().set_color(default_background).to_owned();
        root_canvas.draw_path(&draw_clip, &background_paint);
        let mut ret = vec![];

        (0..self.windows.len()).for_each(|i| {
            let window = &mut self.windows[i];
            window.draw_background_surface(root_canvas, pixel_regions[i], grid_scale);
            window.draw_foreground_surface(root_canvas, pixel_regions[i], grid_scale);
            ret.push(WindowDrawDetails {
                id: window.id,
                region: regions[i],
                grid_size: window.grid_size,
                window_type: window.window_type,
            });
        });

        for (window, region) in self.windows.iter().zip(regions.iter().copied()) {
            window.draw_edge_background_surface(root_canvas, region, grid_scale);
        }

        root_canvas.restore();

        root_canvas.restore();

        ret
    }

    /// The background and hit regions for the current layer. `pixel_regions`
    /// must contain one grid rectangle per window, in the same order. Right
    /// edges can expand from the outer edge of this layer while bottom edges
    /// must meet `bottom_fill_y`, the main grid boundary supplied by the
    /// renderer. Being bottommost in this layer is not sufficient, as a
    /// lower layer can still occupy the rows below a popup.
    ///
    /// `content_region` already excludes explicit padding. `None` leaves
    /// the regions unchanged. A missing bottom boundary disables only
    /// bottom expansion, while right edges can still expand. Both the
    /// edge drawing and [`WindowDrawDetails`] use these results, so the
    /// boundary check also prevents extra bottom areas in mouse hit testing.
    fn expand_edges(
        &self,
        pixel_regions: &[PixelRect<f32>],
        grid_scale: GridScale,
        content_region: Option<PixelRect<f32>>,
        bottom_fill_y: Option<f32>,
    ) -> Vec<PixelRect<f32>> {
        let max_layer_x = max_region_max_x(pixel_regions);
        self.windows
            .iter()
            .zip(pixel_regions.iter().copied())
            .map(|(window, region)| {
                let rightmost_window = is_rightmost_window_edge(region.max.x, max_layer_x);
                let region = window.expanded_pixel_region(
                    region,
                    content_region,
                    grid_scale,
                    rightmost_window,
                );
                window.expanded_bottom_pixel_region(
                    region,
                    content_region,
                    grid_scale,
                    bottom_fill_y,
                )
            })
            .collect::<Vec<_>>()
    }

    fn _draw_shadow(&self, root_canvas: &Canvas, path: &Path, settings: &RendererSettings) {
        if !settings.floating_shadow {
            return;
        }
        // Assume that the message window is the only one in the layer
        if self
            .windows
            .first()
            .is_some_and(|w| matches!(w.window_type, WindowType::Message { scrolled: false }))
        {
            return;
        }

        root_canvas.save();
        // We clip using the Difference op to make sure that the shadow isn't rendered inside
        // the window itself.
        root_canvas.clip_path(path, Some(ClipOp::Difference), None);
        // The light angle is specified in degrees from the vertical, so we first convert them
        // to radians and then use sin/cos to get the y and z components of the light
        let light_angle_radians = settings.light_angle_degrees.to_radians();
        draw_shadow(
            root_canvas,
            path,
            // Specifies how far from the root canvas the shadow casting rect is. We just use
            // the z component here to set it a constant distance away.
            Point3::new(0., 0., settings.floating_z_height),
            // Because we use the DIRECTIONAL_LIGHT shadow flag, this specifies the angle that
            // the light is coming from.
            Point3::new(0., -light_angle_radians.sin(), light_angle_radians.cos()),
            // This is roughly equal to the apparent radius of the light .
            5.,
            Color::from_argb((0.03 * 255.) as u8, 0, 0, 0),
            Color::from_argb((0.35 * 255.) as u8, 0, 0, 0),
            // Directional Light flag is necessary to make the shadow render consistently
            // across various sizes of floating windows. It effects how the light direction is
            // processed.
            Some(ShadowFlags::DIRECTIONAL_LIGHT),
        );
        root_canvas.restore();
    }
}

fn get_window_group(windows: &mut Vec<LayerWindow>, index: usize) -> usize {
    if windows[index].group != index {
        windows[index].group = get_window_group(windows, windows[index].group);
    }
    windows[index].group
}

fn group_windows_with_regions(windows: &mut Vec<LayerWindow>, regions: &[PixelRect<f32>]) {
    // intersects does not consider touching regions as intersection, so extend the box by one
    // pixel before doing the test.
    let epsilon = 1.0;
    for i in 0..windows.len() {
        for j in i + 1..windows.len() {
            let group_i = get_window_group(windows, i);
            let group_j = get_window_group(windows, j);
            if group_i != group_j
                && regions[i].to_rect().inflate((epsilon, epsilon).into()).intersects(&regions[j])
            {
                let new_group = group_i.min(group_j);
                if group_i != group_j {
                    windows[group_i].group = new_group;
                    windows[group_j].group = new_group;
                }
            }
        }
    }
}

pub fn group_windows(
    windows: Vec<&mut RenderedWindow>,
    grid_scale: GridScale,
) -> Vec<Vec<&mut RenderedWindow>> {
    let mut windows = windows
        .into_iter()
        .enumerate()
        .map(|(index, window)| LayerWindow { window, group: index })
        .collect::<Vec<_>>();
    let regions =
        windows.iter().map(|window| window.window.pixel_region(grid_scale)).collect::<Vec<_>>();
    group_windows_with_regions(&mut windows, &regions);
    for i in 0..windows.len() {
        let _ = get_window_group(&mut windows, i);
    }
    windows.sort_by_key(|a| a.group);
    windows
        .into_iter()
        .chunk_by(|window| window.group)
        .into_iter()
        .map(|(_, v)| v.map(|w| w.window).collect::<Vec<_>>())
        .collect_vec()
}

/// A background path included in the layer clip and draw bounds. If Skia
/// cannot form the union, the existing clip stays in place. The bounds
/// still include the supplied rectangle and may extend beyond the clip.
fn include_path_bounds(
    draw_clip: &mut Path,
    draw_bound_rect: &mut Rect,
    path: &Path,
    bounds: Rect,
) {
    if let Some(unioned) = draw_clip.op(path, PathOp::Union) {
        *draw_clip = unioned;
    }

    *draw_bound_rect = Rect::join2(*draw_bound_rect, bounds);
}

fn build_silhouette(
    regions: &[PixelRect<f32>],
    settings: &RendererSettings,
    grid_scale: GridScale,
) -> (Path, Rect) {
    let silhouette = regions
        .iter()
        .map(|r| rect_to_round_rect_path(to_skia_rect(r), settings, grid_scale))
        .reduce(|a, b| a.op(&b, PathOp::Union).unwrap())
        .unwrap();

    let bounding_rect = regions.iter().map(to_skia_rect).reduce(Rect::join2).unwrap();

    (silhouette, bounding_rect)
}

fn max_region_max_x(regions: &[PixelRect<f32>]) -> f32 {
    regions.iter().fold(f32::NEG_INFINITY, |max_x, region| max_x.max(region.max.x))
}

fn rect_to_round_rect_path(rect: Rect, settings: &RendererSettings, grid_scale: GridScale) -> Path {
    let scaled_radius =
        if settings.floating_corner_radius > 0.0 && settings.floating_corner_radius <= 1.0 {
            settings.floating_corner_radius * grid_scale.height()
        } else {
            0.0
        };
    Path::rrect(RRect::new_rect_xy(rect, scaled_radius, scaled_radius), None)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::editor::WindowType;
    use crate::renderer::WindowDrawCommand;
    use crate::units::GridPos;
    use crate::units::GridScale;
    use crate::units::PixelPos;
    use crate::units::PixelRect;
    use crate::units::PixelSize;

    fn grid_scale() -> GridScale { GridScale::new(PixelSize::new(8.0, 16.0)) }

    fn positioned_window(id: u64, grid_top: f64, grid_left: f64) -> RenderedWindow {
        let mut window = RenderedWindow::new(id);
        window.handle_window_draw_command(WindowDrawCommand::Position {
            grid_position: (grid_left, grid_top),
            grid_size: (20, 1),
            anchor_info: None,
            window_type: WindowType::Editor,
        });
        window.grid_current_position = GridPos::new(grid_left as f32, grid_top as f32);
        window
    }

    #[test]
    fn floating_layer_expands_bottom_and_right_edges_when_bottom_fill_is_enabled() {
        let grid_scale = grid_scale();
        let mut upper_window = positioned_window(2, 3.0, 0.0);
        let mut bottom_window = positioned_window(3, 4.0, 0.0);
        let layer = FloatingLayer { windows: vec![&mut upper_window, &mut bottom_window] };
        let pixel_regions =
            layer.windows.iter().map(|window| window.pixel_region(grid_scale)).collect::<Vec<_>>();
        let upper_region = pixel_regions[0];
        let bottom_region = pixel_regions[1];
        let content_region = PixelRect::new(
            PixelPos::new(0.0, 0.0),
            PixelPos::new(bottom_region.max.x + 3.0, bottom_region.max.y + 7.0),
        );

        let expanded_regions = layer.expand_edges(
            &pixel_regions,
            grid_scale,
            Some(content_region),
            Some(bottom_region.max.y),
        );

        assert_eq!(
            expanded_regions,
            vec![
                PixelRect::new(
                    upper_region.min,
                    PixelPos::new(content_region.max.x, upper_region.max.y),
                ),
                PixelRect::new(bottom_region.min, content_region.max),
            ]
        );
    }

    #[test]
    fn floating_layer_expands_only_right_edge_when_bottom_fill_is_disabled() {
        let grid_scale = grid_scale();
        let mut upper_window = positioned_window(2, 3.0, 0.0);
        let mut bottom_window = positioned_window(3, 4.0, 0.0);
        let layer = FloatingLayer { windows: vec![&mut upper_window, &mut bottom_window] };
        let pixel_regions =
            layer.windows.iter().map(|window| window.pixel_region(grid_scale)).collect::<Vec<_>>();
        let upper_region = pixel_regions[0];
        let bottom_region = pixel_regions[1];
        let content_region = PixelRect::new(
            PixelPos::new(0.0, 0.0),
            PixelPos::new(bottom_region.max.x + 3.0, bottom_region.max.y + 7.0),
        );

        let expanded_regions =
            layer.expand_edges(&pixel_regions, grid_scale, Some(content_region), None);

        assert_eq!(
            expanded_regions,
            vec![
                PixelRect::new(
                    upper_region.min,
                    PixelPos::new(content_region.max.x, upper_region.max.y),
                ),
                PixelRect::new(
                    bottom_region.min,
                    PixelPos::new(content_region.max.x, bottom_region.max.y),
                ),
            ]
        );
    }
}