sk-tree 0.4.0

Skathi's retained node tree and the renderer's host functions
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
//! `copy`, `cut` and `paste` ClipboardEvents. A cancelled `keydown` cancels the clipboard event too,
//! as in a browser. A focused text field fires them from the widget's actions; anywhere else the
//! root's key listener fires them at the focused node (or `document.body`), and an uncancelled
//! `copy` copies the document selection.
//!
//! `clipboardData` is a real `DataTransfer`: read-only text/files/`image.png` for `paste` (gpui reads
//! no HTML, RTF or custom formats), and for a cancelled `copy`/`cut` only `text/plain` can be written.

use gpui::{
    App, ClipboardEntry, ClipboardItem, ImageFormat, InteractiveElement, KeyDownEvent, Keystroke,
    Window,
};
use sk_runtime::redjs::api::Value;
use sk_runtime::redjs::webapi::uievents::{self, DragDataMode};
use sk_runtime::JsRuntime;

use crate::render::warn_compat;
use crate::tree::{self, Tree};
use crate::windows;
use crate::EventPayload;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Verb {
    Copy,
    Cut,
    Paste,
}

impl Verb {
    pub(crate) fn code(self) -> u32 {
        match self {
            Verb::Copy => tree::EV_COPY,
            Verb::Cut => tree::EV_CUT,
            Verb::Paste => tree::EV_PASTE,
        }
    }

    pub(crate) fn of_command(c: sk_elements::ClipboardCommand) -> Verb {
        match c {
            sk_elements::ClipboardCommand::Copy => Verb::Copy,
            sk_elements::ClipboardCommand::Cut => Verb::Cut,
            sk_elements::ClipboardCommand::Paste => Verb::Paste,
        }
    }

    /// Keystrokes that ARE a clipboard command outside a text field: the primary modifier with C / X / V,
    /// and on Windows and Linux Ctrl+Insert, Shift+Delete and Shift+Insert. Any other modifier makes it
    /// a different shortcut.
    pub(crate) fn of_keystroke(k: &Keystroke) -> Option<Verb> {
        let m = &k.modifiers;
        let mac = cfg!(target_os = "macos");
        let primary = if mac { m.platform } else { m.control };
        let other = if mac { m.control } else { m.platform };
        let only_primary = primary && !other && !m.shift && !m.alt && !m.function;
        let only_ctrl = m.control && !m.platform && !m.shift && !m.alt && !m.function;
        let only_shift = m.shift && !m.control && !m.platform && !m.alt && !m.function;
        match k.key.as_str() {
            "c" if only_primary => Some(Verb::Copy),
            "x" if only_primary => Some(Verb::Cut),
            "v" if only_primary => Some(Verb::Paste),
            "insert" if !mac && only_ctrl => Some(Verb::Copy),
            "delete" if !mac && only_shift => Some(Verb::Cut),
            "insert" if !mac && only_shift => Some(Verb::Paste),
            _ => None,
        }
    }
}

pub(crate) fn listened(t: &Tree, target: u32, verb: Verb) -> bool {
    let bit = 1u64 << verb.code();
    let mut cur = target;
    while let Some(n) = t.node(cur) {
        if n.listeners & bit != 0 {
            return true;
        }
        if n.parent == 0 {
            return false;
        }
        cur = n.parent;
    }
    false
}

pub(crate) fn fire(target: u32, verb: Verb, window: &mut Window, cx: &mut App) -> bool {
    if !tree::read_tree(|t| listened(t, target, verb)) {
        return true;
    }
    let clip = if verb == Verb::Paste {
        cx.read_from_clipboard()
    } else {
        None
    };
    let mut write = None;
    let proceed = crate::render::js_wave_app(window, cx, || {
        let (proceed, w) = exchange(target, verb, clip.as_ref());
        write = w;
        proceed
    });
    if let Some(item) = write {
        cx.write_to_clipboard(item);
    }
    proceed
}

pub(crate) fn exchange(
    target: u32,
    verb: Verb,
    clip: Option<&ClipboardItem>,
) -> (bool, Option<ClipboardItem>) {
    let data = JsRuntime::try_with(|rt| new_data(rt, verb, clip)).flatten();
    if verb == Verb::Paste {
        warn_compat(
            "clipboard-paste-types",
            "a `paste` event's clipboardData holds what this host reads off the system clipboard: \
             text/plain, the files of a file copy, and a bitmap as image.png. HTML (text/html), rich \
             text and custom formats are not read, so getData(\"text/html\") is \"\" where a browser \
             would return the copied markup",
        );
    }
    let proceed = crate::dispatch_event_with(target, verb.code(), &EventPayload::default(), data);
    let write = data.and_then(|dt| JsRuntime::with(|rt| finish(rt, dt, verb, proceed)));
    (proceed, write)
}

fn new_data(rt: &JsRuntime, verb: Verb, clip: Option<&ClipboardItem>) -> Option<Value> {
    let ctx = rt.ctx();
    let ctor = ctx.global_get("DataTransfer").ok().filter(Value::is_cell)?;
    let dt = ctx.construct(ctor, &[]).ok()?;
    ctx.protect(dt);
    if verb == Verb::Paste {
        if let Some(item) = clip {
            fill(rt, dt, item);
        }
        // SAFETY: `dt` is a live DataTransfer of this runtime, on its thread.
        unsafe { uievents::set_drag_data_mode(rt.raw(), dt.0, DragDataMode::ReadOnly) };
    }
    Some(dt)
}

/// Calls `obj[name](...args)`, ignoring a throw (the item is then missing, as in a browser).
fn call(rt: &JsRuntime, obj: Value, name: &str, args: &[Value]) -> Option<Value> {
    let ctx = rt.ctx();
    let f = ctx.get(obj, &ctx.atom(name)).ok()?;
    ctx.call(f, obj, args).ok()
}

fn fill(rt: &JsRuntime, dt: Value, item: &ClipboardItem) {
    let ctx = rt.ctx();
    for entry in item.entries() {
        if let ClipboardEntry::String(s) = entry {
            call(
                rt,
                dt,
                "setData",
                &[ctx.string("text/plain"), ctx.string(&s.text)],
            );
            break;
        }
    }
    let Ok(items) = ctx.get(dt, &ctx.atom("items")) else {
        return;
    };
    for entry in item.entries() {
        match entry {
            ClipboardEntry::Image(image) => {
                let Some(png) = as_png(&image.format, &image.bytes) else {
                    warn_compat(
                        "clipboard-paste-image",
                        &format!(
                            "a pasted {:?} image could not be offered as image.png and is not in \
                             clipboardData.files",
                            image.format
                        ),
                    );
                    continue;
                };
                if let Some(file) = png_file(rt, &png) {
                    call(rt, items, "add", &[file]);
                }
            }
            ClipboardEntry::ExternalPaths(paths) => {
                for path in paths.paths() {
                    // SAFETY: the runtime's own context, on its thread.
                    match unsafe { sk_runtime::redjs::webapi::file::file_from_path(rt.raw(), path, "") } {
                        Ok(file) => {
                            call(rt, items, "add", &[Value(file)]);
                        }
                        Err(_) => warn_compat(
                            "clipboard-paste-folder",
                            "a copied folder (or a path that can no longer be read) is left out of a \
                             paste's clipboardData.files; the files beside it are there",
                        ),
                    }
                }
            }
            ClipboardEntry::String(_) => {}
        }
    }
}

/// `new File([bytes], "image.png", { type: "image/png" })`: what Chromium names a pasted bitmap.
fn png_file(rt: &JsRuntime, png: &[u8]) -> Option<Value> {
    let ctx = rt.ctx();
    let ctor = ctx.global_get("File").ok().filter(Value::is_cell)?;
    // SAFETY: the runtime's own context, on its thread.
    let bytes = Value(unsafe { sk_runtime::redjs::webapi::util::make_u8(rt.raw(), png) });
    let parts = ctx.array(1).ok()?;
    ctx.set_index(parts, 0, bytes).ok()?;
    let opts = ctx.object();
    ctx.set(opts, &ctx.atom("type"), ctx.string("image/png"))
        .ok()?;
    ctx.construct(ctor, &[parts, ctx.string("image.png"), opts])
        .ok()
}

/// A clipboard image as PNG bytes: PNG as is, any other raster re-encoded (Windows hands a screenshot
/// over as a DIB). `None` for SVG or anything undecodable.
pub(crate) fn as_png(format: &ImageFormat, bytes: &[u8]) -> Option<Vec<u8>> {
    let from = match format {
        ImageFormat::Png => return Some(bytes.to_vec()),
        ImageFormat::Jpeg => image::ImageFormat::Jpeg,
        ImageFormat::Webp => image::ImageFormat::WebP,
        ImageFormat::Gif => image::ImageFormat::Gif,
        ImageFormat::Bmp => image::ImageFormat::Bmp,
        ImageFormat::Tiff => image::ImageFormat::Tiff,
        ImageFormat::Ico => image::ImageFormat::Ico,
        _ => return None,
    };
    let decoded = image::load_from_memory_with_format(bytes, from).ok()?;
    let mut out = Vec::new();
    decoded
        .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png)
        .ok()?;
    Some(out)
}

fn finish(rt: &JsRuntime, dt: Value, verb: Verb, proceed: bool) -> Option<ClipboardItem> {
    let write = if verb != Verb::Paste && !proceed {
        written(rt, dt)
    } else {
        None
    };
    // SAFETY: `dt` is a live DataTransfer of this runtime, on its thread.
    unsafe { uievents::set_drag_data_mode(rt.raw(), dt.0, DragDataMode::Disabled) };
    rt.ctx().unprotect(dt);
    write
}

fn written(rt: &JsRuntime, dt: Value) -> Option<ClipboardItem> {
    let ctx = rt.ctx();
    let types = ctx.get(dt, &ctx.atom("types")).ok()?;
    let n = ctx.array_length(types).unwrap_or(0);
    let mut list = Vec::with_capacity(n as usize);
    for i in 0..n {
        if let Some(s) = ctx
            .get_index(types, i)
            .ok()
            .and_then(|v| ctx.read_string(v).ok())
        {
            list.push(s);
        }
    }
    let dropped: Vec<&str> = list
        .iter()
        .map(String::as_str)
        .filter(|t| *t != "text/plain")
        .collect();
    if !dropped.is_empty() {
        warn_compat(
            "clipboard-write-types",
            &format!(
                "a cancelled copy/cut set {} on clipboardData; only text/plain reaches the system \
                 clipboard here (gpui writes text and images, not HTML or custom formats), so the \
                 rest is dropped",
                dropped.join(", ")
            ),
        );
    }
    if !list.iter().any(|t| t == "text/plain") {
        return None;
    }
    let text = call(rt, dt, "getData", &[ctx.string("text/plain")])?;
    Some(ClipboardItem::new_string(ctx.read_string(text).ok()?))
}

pub(crate) fn bind_root<E: InteractiveElement>(e: E, root: u32) -> E {
    e.capture_key_down(|_, window, _| windows::here(window, |w| w.key_prevented = false))
        .on_key_down(move |ev: &KeyDownEvent, window, cx| {
            let Some(verb) = Verb::of_keystroke(&ev.keystroke) else {
                return;
            };
            if windows::here(window, |w| std::mem::take(&mut w.key_prevented)) {
                return;
            }
            let focused = windows::focused_node(windows::key(window));
            let target = if focused != 0 && tree::read_tree(|t| t.node(focused).is_some()) {
                focused
            } else {
                root
            };
            if !fire(target, verb, window, cx) {
                return;
            }
            if verb == Verb::Copy {
                if let Some(text) = crate::selection::text_for_copy(focused) {
                    cx.write_to_clipboard(ClipboardItem::new_string(text));
                }
            }
        })
}

#[cfg(test)]
mod tests {
    use super::*;

    fn stroke(s: &str) -> Keystroke {
        // `parse` wants a `&'static str` since zed#65970; a test may leak.
        Keystroke::parse(s.to_owned().leak()).unwrap()
    }

    #[test]
    fn the_clipboard_keys_and_nothing_else() {
        let p = if cfg!(target_os = "macos") {
            "cmd"
        } else {
            "ctrl"
        };
        assert_eq!(
            Verb::of_keystroke(&stroke(&format!("{p}-c"))),
            Some(Verb::Copy)
        );
        assert_eq!(
            Verb::of_keystroke(&stroke(&format!("{p}-x"))),
            Some(Verb::Cut)
        );
        assert_eq!(
            Verb::of_keystroke(&stroke(&format!("{p}-v"))),
            Some(Verb::Paste)
        );
        for other in [
            "c",
            "v",
            "shift-c",
            &format!("shift-{p}-v"),
            &format!("alt-{p}-c"),
            "ctrl-shift-insert",
            "delete",
            "insert",
        ] {
            assert_eq!(Verb::of_keystroke(&stroke(other)), None, "{other}");
        }
        if !cfg!(target_os = "macos") {
            assert_eq!(Verb::of_keystroke(&stroke("ctrl-insert")), Some(Verb::Copy));
            assert_eq!(Verb::of_keystroke(&stroke("shift-delete")), Some(Verb::Cut));
            assert_eq!(
                Verb::of_keystroke(&stroke("shift-insert")),
                Some(Verb::Paste)
            );
        }
    }

    #[test]
    fn a_listener_anywhere_up_the_path_counts_and_the_root_stands_for_document() {
        let (root, mid, leaf, other) = tree::with_tree(|t| {
            let root = t.create_root();
            let div = t.intern("div");
            let kid = |t: &mut Tree, parent: u32| {
                let id = t.create_element(div);
                t.insert(id, parent, 0);
                id
            };
            let mid = kid(t, root);
            let leaf = kid(t, mid);
            let other = kid(t, root);
            (root, mid, leaf, other)
        });
        let listened_at = |id: u32, verb: Verb| tree::read_tree(|t| listened(t, id, verb));
        assert!(!listened_at(leaf, Verb::Paste));
        tree::with_tree(|t| t.set_listener(mid, tree::EV_PASTE, true));
        assert!(listened_at(leaf, Verb::Paste), "an ancestor's @paste");
        assert!(!listened_at(leaf, Verb::Copy), "per event");
        assert!(!listened_at(other, Verb::Paste), "not a sibling's");
        tree::with_tree(|t| t.set_listener(root, tree::EV_COPY, true));
        assert!(listened_at(other, Verb::Copy));
        assert!(listened_at(leaf, Verb::Copy));
    }

    #[test]
    fn a_bitmap_is_offered_as_png() {
        let mut img = image::RgbaImage::new(2, 1);
        img.put_pixel(0, 0, image::Rgba([255, 0, 0, 255]));
        img.put_pixel(1, 0, image::Rgba([0, 0, 255, 255]));
        let mut bmp = Vec::new();
        image::DynamicImage::ImageRgba8(img)
            .write_to(&mut std::io::Cursor::new(&mut bmp), image::ImageFormat::Bmp)
            .unwrap();
        let png = as_png(&ImageFormat::Bmp, &bmp).expect("converted");
        assert_eq!(&png[..8], b"\x89PNG\r\n\x1a\n");
        let back = image::load_from_memory_with_format(&png, image::ImageFormat::Png)
            .unwrap()
            .to_rgba8();
        assert_eq!(back.get_pixel(0, 0).0, [255, 0, 0, 255]);
        assert_eq!(back.get_pixel(1, 0).0, [0, 0, 255, 255]);
        assert_eq!(
            as_png(&ImageFormat::Png, b"as is").as_deref(),
            Some(&b"as is"[..])
        );
        assert_eq!(as_png(&ImageFormat::Svg, b"<svg/>"), None);
        assert_eq!(as_png(&ImageFormat::Bmp, b"not a bmp"), None);
    }

    fn eval(src: &str) -> String {
        JsRuntime::with(|rt| {
            let v = rt
                .ctx()
                .eval(src)
                .unwrap_or_else(|e| panic!("{src}: {e:?}"));
            rt.ctx().to_rust_string(v).unwrap()
        })
    }

    #[test]
    fn clipboard_data_crosses_in_the_right_mode_and_comes_back() {
        sk_runtime::testing::on_js_thread(move || {
            let node = tree::with_tree(|t| t.create_root());
            let f = JsRuntime::with(|rt| {
                let f = rt
                    .ctx()
                    .eval(
                        "globalThis.seen = []; (function (node, code, a, b, c, d, key, data) {
                           globalThis.kept = data;
                           const r = { code, isDT: data instanceof DataTransfer, types: [...data.types],
                                       text: data.getData('text/plain'), files: data.files.length,
                                       name: data.files.length ? data.files[0].name : '',
                                       type: data.files.length ? data.files[0].type : '' };
                           try { data.setData('text/plain', 'from js'); r.wrote = data.getData('text/plain'); }
                           catch (e) { r.wrote = 'threw'; }
                           if (code !== 39) data.setData('text/html', '<b>x</b>');
                           seen.push(r);
                           return globalThis.cancel !== true;
                         })",
                    )
                    .unwrap();
                rt.ctx().protect(f);
                f.0
            });
            tree::set_dispatcher(f);
            let last = || eval("JSON.stringify(seen[seen.length - 1])");

            let mut png = Vec::new();
            image::DynamicImage::ImageRgba8(image::RgbaImage::new(1, 1))
                .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
                .unwrap();
            let item = ClipboardItem {
                entries: vec![
                    ClipboardEntry::Image(gpui::Image::from_bytes(ImageFormat::Png, png)),
                    ClipboardEntry::String(gpui::ClipboardString::new("hello".into())),
                ],
            };
            let (proceed, write) = exchange(node, Verb::Paste, Some(&item));
            assert!(proceed);
            assert!(write.is_none(), "a paste writes nothing");
            assert_eq!(
                last(),
                r#"{"code":39,"isDT":true,"types":["text/plain","Files"],"text":"hello","files":1,"name":"image.png","type":"image/png","wrote":"hello"}"#,
                "read-only: setData is a no-op"
            );
            assert_eq!(
                eval("kept.getData('text/plain') + '|' + kept.files.length"),
                "|0",
                "disabled after the event"
            );

            let (proceed, write) = exchange(node, Verb::Copy, None);
            assert!(proceed);
            assert!(write.is_none());
            assert_eq!(
                last(),
                r#"{"code":40,"isDT":true,"types":[],"text":"","files":0,"name":"","type":"","wrote":"from js"}"#
            );

            eval("globalThis.cancel = true; ''");
            let (proceed, write) = exchange(node, Verb::Cut, None);
            assert!(!proceed);
            assert_eq!(write.and_then(|w| w.text()).as_deref(), Some("from js"));
            assert_eq!(
                eval("kept.types.length + ''"),
                "0",
                "disabled after the event"
            );
        });
    }
}