1
//! Clipboard content types for copy/paste operations
2
//!
3
//! Contains `ClipboardContent` and `StyledTextRun`, used by clipboard and
4
//! changeset modules.
5
//!
6
//! **Rich-text status: wired end to end.** A paste populates `styled_runs`
7
//! whenever the source offered a styled flavor — the platform transports in
8
//! `dll/src/desktop/shell2/*/clipboard.rs` hand every flavor the source
9
//! published to `rich-clipboard`, whose decode policy prefers RTF, then HTML,
10
//! then plain text, and `shell2/common/clipboard.rs` converts the result into
11
//! this type. A copy goes the other way: [`ClipboardExtract`] pulls per-run
12
//! formatting off each source `StyledRun` as the selection is walked, and the
13
//! transports fan that out as RTF *and* HTML *and* plain text at once — so a
14
//! copy out of azul pastes into Word or `LibreOffice` formatted.
15
//!
16
//! Two platforms are less capable, and both say so in their own docs: X11's
17
//! selection owner can serve only one target (`x11/clipboard.rs`), so it
18
//! publishes plain text; and a Wayland session with no compositor selection
19
//! falls back through `XWayland` to that same single-target path.
20
//!
21
//! `to_html()` below predates all of this and is not on the clipboard path:
22
//! `rich-clipboard`'s `RichText::to_html_fragment` is what actually gets
23
//! published, because it also emits the matching RTF and the `CF_HTML`
24
//! wrapper Windows needs. This stays as public FFI API.
25

            
26
use azul_css::{impl_option, impl_option_inner, AzString, OptionString};
27

            
28
// Clipboard Content Extraction
29

            
30
/// Styled text run for rich clipboard content
31
#[derive(Debug, Clone, PartialEq)]
32
#[repr(C)]
33
pub struct StyledTextRun {
34
    /// The actual text content
35
    pub text: AzString,
36
    /// Font family name
37
    pub font_family: OptionString,
38
    /// Font size in pixels
39
    pub font_size_px: f32,
40
    /// Text color
41
    pub color: azul_css::props::basic::ColorU,
42
    /// Whether text is bold
43
    pub is_bold: bool,
44
    /// Whether text is italic
45
    pub is_italic: bool,
46
}
47

            
48
azul_css::impl_option!(
49
    StyledTextRun,
50
    OptionStyledTextRun,
51
    copy = false,
52
    [Debug, Clone, PartialEq]
53
);
54
azul_css::impl_vec!(
55
    StyledTextRun,
56
    StyledTextRunVec,
57
    StyledTextRunVecDestructor,
58
    StyledTextRunVecDestructorType,
59
    StyledTextRunVecSlice,
60
    OptionStyledTextRun
61
);
62
azul_css::impl_vec_debug!(StyledTextRun, StyledTextRunVec);
63
azul_css::impl_vec_clone!(StyledTextRun, StyledTextRunVec, StyledTextRunVecDestructor);
64
azul_css::impl_vec_partialeq!(StyledTextRun, StyledTextRunVec);
65

            
66
/// Clipboard content with both plain text and styled (HTML) representation
67
#[derive(Debug, Clone, PartialEq)]
68
#[repr(C)]
69
pub struct ClipboardContent {
70
    /// Plain text representation (UTF-8)
71
    pub plain_text: AzString,
72
    /// Rich text runs with styling information
73
    pub styled_runs: StyledTextRunVec,
74
}
75

            
76
impl_option!(
77
    ClipboardContent,
78
    OptionClipboardContent,
79
    copy = false,
80
    [Debug, Clone, PartialEq]
81
);
82

            
83
/// Builds a [`ClipboardContent`] from the styled runs a selection walks over.
84
///
85
/// Not FFI — this is the copy path's scratch buffer, and it exists so the three
86
/// selection shapes (single-run, multi-run, cross-block) all produce their
87
/// plain text and their styling from one place instead of the plain text
88
/// twice.
89
///
90
/// The two invariants it maintains are the ones the OS transports depend on:
91
/// `plain_text` is exactly the concatenation of the runs' text (a receiver must
92
/// not get different characters depending on which flavor it picks), and
93
/// adjacent runs with identical formatting are merged.
94
///
95
/// Merging is not cosmetic. A style run is cut at every DOM text node and every
96
/// styling change, so a paragraph typed in one font can arrive as dozens of
97
/// runs; emitting each one as its own `<span>` or `\b0\b` pair would produce
98
/// RTF and HTML several times the size of the text for no visible difference.
99
#[derive(Debug, Default)]
100
pub struct ClipboardExtract {
101
    /// Grown in place. Runs borrow nothing from it — they keep their own text —
102
    /// but the two are appended to together, which is what keeps them equal.
103
    plain: String,
104
    runs: Vec<PendingRun>,
105
}
106

            
107
/// A run still being accumulated.
108
///
109
/// Held as a plain `String` rather than the FFI `AzString` so that merging is
110
/// an append. Building an `AzString` per merge would re-copy everything
111
/// accumulated so far, which on a uniformly-styled select-all — where *every*
112
/// run merges into one — is quadratic in the document.
113
#[derive(Debug)]
114
struct PendingRun {
115
    text: String,
116
    style: RunStyle,
117
}
118

            
119
/// The formatting fields of a [`StyledTextRun`], without the text.
120
///
121
/// Comparing these is what decides a merge. `f32` equality is the derived one:
122
/// a NaN size simply never merges, which costs a few extra runs in a case that
123
/// cannot arise from the cascade anyway.
124
#[derive(Debug, Clone, PartialEq)]
125
struct RunStyle {
126
    font_family: Option<String>,
127
    font_size_px: f32,
128
    color: azul_css::props::basic::ColorU,
129
    is_bold: bool,
130
    is_italic: bool,
131
}
132

            
133
impl ClipboardExtract {
134
    /// Append `text`, formatted by `style`.
135
2060
    pub fn push(&mut self, text: &str, style: &crate::text3::cache::StyleProperties) {
136
2060
        if text.is_empty() {
137
1
            return;
138
2059
        }
139
2059
        self.plain.push_str(text);
140

            
141
2059
        let selector = style.font_stack.first_selector();
142
2059
        let run_style = RunStyle {
143
            // A direct `FontRef` (an embedded icon font) has no family name to
144
            // give a receiving application, and `FontStack::first_family`'s
145
            // `"<embedded-font>"` placeholder is a debugging string, not a
146
            // font anyone can resolve. `None` means "inherit", which is the
147
            // honest answer.
148
2059
            font_family: selector.map(|s| s.family.clone()),
149
2059
            font_size_px: style.font_size_px,
150
2059
            color: style.color,
151
            // CSS `font-weight: bold` is 700; everything at or above it reads
152
            // as bold to a format that only has a boolean. `FcWeight` is
153
            // ordered by its CSS numeric value, so this is that comparison.
154
2059
            is_bold: selector.is_some_and(|s| s.weight >= rust_fontconfig::FcWeight::Bold),
155
            // Oblique is a slanted rendering of an upright face; every
156
            // clipboard format this feeds collapses it into italic.
157
2059
            is_italic: selector.is_some_and(|s| {
158
2057
                matches!(
159
2058
                    s.style,
160
                    crate::text3::cache::FontStyle::Italic
161
                        | crate::text3::cache::FontStyle::Oblique
162
                )
163
2058
            }),
164
        };
165

            
166
2059
        match self.runs.last_mut() {
167
2026
            Some(last) if last.style == run_style => last.text.push_str(text),
168
36
            _ => self.runs.push(PendingRun {
169
36
                text: String::from(text),
170
36
                style: run_style,
171
36
            }),
172
        }
173
2060
    }
174

            
175
    /// Append text under whatever formatting is already in effect.
176
    ///
177
    /// For the paragraph joiner between blocks of a cross-block selection: a
178
    /// `\n` of its own would be an unformatted run wedged between two formatted
179
    /// ones, which RTF and HTML both have to spell out.
180
2023
    pub fn push_inheriting(&mut self, text: &str) {
181
2023
        if text.is_empty() {
182
1
            return;
183
2022
        }
184
2022
        self.plain.push_str(text);
185
2022
        match self.runs.last_mut() {
186
2022
            Some(last) => last.text.push_str(text),
187
            // Nothing to inherit from: the selection started with the joiner.
188
            None => self.runs.push(PendingRun {
189
                text: String::from(text),
190
                style: RunStyle {
191
                    font_family: None,
192
                    font_size_px: 0.0,
193
                    color: azul_css::props::basic::ColorU {
194
                        r: 0,
195
                        g: 0,
196
                        b: 0,
197
                        a: 255,
198
                    },
199
                    is_bold: false,
200
                    is_italic: false,
201
                },
202
            }),
203
        }
204
2023
    }
205

            
206
    /// The collected content, or `None` if the selection held no text.
207
    ///
208
    /// This is where the FFI strings are built — once per run, not once per
209
    /// merge.
210
    #[must_use]
211
35
    pub fn finish(self) -> Option<ClipboardContent> {
212
35
        if self.plain.is_empty() {
213
2
            return None;
214
33
        }
215
33
        let runs: Vec<StyledTextRun> = self
216
33
            .runs
217
33
            .into_iter()
218
33
            .map(|r| StyledTextRun {
219
36
                text: r.text.into(),
220
36
                font_family: r.style.font_family.map(AzString::from).into(),
221
36
                font_size_px: r.style.font_size_px,
222
36
                color: r.style.color,
223
36
                is_bold: r.style.is_bold,
224
36
                is_italic: r.style.is_italic,
225
36
            })
226
33
            .collect();
227
33
        Some(ClipboardContent {
228
33
            plain_text: self.plain.into(),
229
33
            styled_runs: runs.into(),
230
33
        })
231
35
    }
232
}
233

            
234
impl ClipboardContent {
235
    /// Convert styled runs to HTML for rich clipboard formats.
236
    ///
237
    /// Public FFI API, and **not** what the clipboard publishes — that is
238
    /// `rich-clipboard`'s `RichText::to_html_fragment`, which also emits the
239
    /// matching RTF and the `CF_HTML` wrapper Windows needs (see module docs).
240
    /// Kept for callers that want a quick HTML rendering of a
241
    /// `ClipboardContent` without the rest of that stack.
242
    #[must_use]
243
53
    pub fn to_html(&self) -> String {
244
        use core::fmt::Write as _;
245
53
        let mut html = String::from("<div>");
246

            
247
2053
        for run in self.styled_runs.as_slice() {
248
2053
            html.push_str("<span style=\"");
249

            
250
2053
            if let Some(font_family) = run.font_family.as_ref() {
251
2008
                let _ = write!(html, "font-family: {}; ", font_family.as_str());
252
2008
            }
253
2053
            let _ = write!(html, "font-size: {}px; ", run.font_size_px);
254
2053
            let _ = write!(
255
2053
                html,
256
2053
                "color: rgba({}, {}, {}, {}); ",
257
                run.color.r,
258
                run.color.g,
259
                run.color.b,
260
2053
                f32::from(run.color.a) / 255.0
261
            );
262
2053
            if run.is_bold {
263
1
                html.push_str("font-weight: bold; ");
264
2052
            }
265
2053
            if run.is_italic {
266
1
                html.push_str("font-style: italic; ");
267
2052
            }
268

            
269
2053
            html.push_str("\">");
270
            // Escape HTML entities
271
2053
            let escaped = run
272
2053
                .text
273
2053
                .as_str()
274
2053
                .replace('&', "&amp;")
275
2053
                .replace('<', "&lt;")
276
2053
                .replace('>', "&gt;");
277
2053
            html.push_str(&escaped);
278
2053
            html.push_str("</span>");
279
        }
280

            
281
53
        html.push_str("</div>");
282
53
        html
283
53
    }
284
}
285

            
286
#[cfg(test)]
287
mod autotest_generated {
288
    use azul_css::{props::basic::ColorU, AzString, OptionString};
289

            
290
    use super::*;
291

            
292
    // =========================================================================
293
    // Fixtures
294
    //
295
    // `ClipboardContent::to_html` is a pure string builder, so the adversarial
296
    // surface is (a) the escaping pass over `text` (ordering, double-escaping,
297
    // characters it does *not* cover), (b) `f32` Display of `font_size_px`
298
    // (NaN / inf / -0.0 / MAX), (c) the u8 -> f32 alpha division at the
299
    // channel boundaries, and (d) structural invariants that must hold for
300
    // every input (balanced tags, one span per run, determinism).
301
    // =========================================================================
302

            
303
    const OPAQUE_BLACK: ColorU = ColorU {
304
        r: 0,
305
        g: 0,
306
        b: 0,
307
        a: 255,
308
    };
309

            
310
    /// A styled run, parameterized on every field the formatter reads.
311
    fn run(text: &str, font_size_px: f32, family: Option<&str>) -> StyledTextRun {
312
        StyledTextRun {
313
            text: AzString::from(text),
314
            font_family: family.map_or(OptionString::None, |f| {
315
                OptionString::Some(AzString::from(f))
316
            }),
317
            font_size_px,
318
            color: OPAQUE_BLACK,
319
            is_bold: false,
320
            is_italic: false,
321
        }
322
    }
323

            
324
    fn content(runs: Vec<StyledTextRun>) -> ClipboardContent {
325
        ClipboardContent {
326
            plain_text: AzString::from(""),
327
            styled_runs: runs.into(),
328
        }
329
    }
330

            
331
    /// Inverse of the escaping pass in `to_html` (entities undone in reverse
332
    /// order, so `&amp;` is restored last).
333
    fn unescape(s: &str) -> String {
334
        s.replace("&lt;", "<")
335
            .replace("&gt;", ">")
336
            .replace("&amp;", "&")
337
    }
338

            
339
    // ---------------------------------------------------------------------
340
    // basic_access: expected value after a known construction
341
    // ---------------------------------------------------------------------
342

            
343
    #[test]
344
    fn to_html_single_run_produces_exact_markup() {
345
        let c = content(vec![run("hi", 12.0, Some("Arial"))]);
346
        assert_eq!(
347
            c.to_html(),
348
            "<div><span style=\"font-family: Arial; font-size: 12px; color: rgba(0, 0, 0, 1); \
349
             \">hi</span></div>"
350
        );
351
    }
352

            
353
    #[test]
354
    fn to_html_omits_font_family_when_none() {
355
        let html = content(vec![run("x", 1.0, None)]).to_html();
356
        assert!(!html.contains("font-family"), "{html}");
357
        assert!(html.contains("font-size: 1px; "), "{html}");
358
    }
359

            
360
    #[test]
361
    fn to_html_emits_bold_and_italic_only_when_set() {
362
        let mut r = run("x", 10.0, None);
363
        assert!(!content(vec![r.clone()]).to_html().contains("font-weight"));
364
        assert!(!content(vec![r.clone()]).to_html().contains("font-style"));
365

            
366
        r.is_bold = true;
367
        r.is_italic = true;
368
        let html = content(vec![r]).to_html();
369
        assert!(html.contains("font-weight: bold; "), "{html}");
370
        assert!(html.contains("font-style: italic; "), "{html}");
371
    }
372

            
373
    #[test]
374
    fn to_html_concatenates_runs_in_order() {
375
        let html = content(vec![
376
            run("a", 1.0, None),
377
            run("b", 2.0, None),
378
            run("c", 3.0, None),
379
        ])
380
        .to_html();
381
        let a = html.find(">a<").expect("run a missing");
382
        let b = html.find(">b<").expect("run b missing");
383
        let c = html.find(">c<").expect("run c missing");
384
        assert!(a < b && b < c, "runs reordered: {html}");
385
    }
386

            
387
    // ---------------------------------------------------------------------
388
    // edge_access: default / empty / extreme instances must not panic
389
    // ---------------------------------------------------------------------
390

            
391
    #[test]
392
    fn to_html_empty_runs_is_empty_div() {
393
        assert_eq!(content(Vec::new()).to_html(), "<div></div>");
394
    }
395

            
396
    #[test]
397
    fn to_html_empty_run_text_yields_empty_span_body() {
398
        let html = content(vec![run("", 0.0, Some(""))]).to_html();
399
        assert!(html.ends_with("\"></span></div>"), "{html}");
400
        assert!(html.contains("font-family: ; "), "{html}");
401
    }
402

            
403
    #[test]
404
    fn to_html_ignores_plain_text_field() {
405
        // `to_html` only reads `styled_runs`; a populated `plain_text` (the
406
        // only field the live producers fill) must not leak into the markup.
407
        let c = ClipboardContent {
408
            plain_text: AzString::from("SHOULD-NOT-APPEAR"),
409
            styled_runs: Vec::<StyledTextRun>::new().into(),
410
        };
411
        assert_eq!(c.to_html(), "<div></div>");
412
    }
413

            
414
    // ---------------------------------------------------------------------
415
    // escaping / round-trip: escape(text) must be losslessly reversible
416
    // ---------------------------------------------------------------------
417

            
418
    #[test]
419
    fn to_html_escapes_angle_brackets_and_ampersand() {
420
        let html = content(vec![run("<script>a && b</script>", 10.0, None)]).to_html();
421
        assert!(
422
            html.contains("&lt;script&gt;a &amp;&amp; b&lt;/script&gt;"),
423
            "{html}"
424
        );
425
        assert!(!html.contains("<script>"), "raw tag survived: {html}");
426
    }
427

            
428
    #[test]
429
    fn to_html_does_not_double_escape_existing_entities() {
430
        // `&` is replaced first, so an input entity is escaped exactly once.
431
        let html = content(vec![run("&lt;&amp;", 10.0, None)]).to_html();
432
        assert!(html.contains(">&amp;lt;&amp;amp;<"), "{html}");
433
    }
434

            
435
    #[test]
436
    fn to_html_text_round_trips_through_unescape() {
437
        for text in [
438
            "",
439
            "plain",
440
            "&",
441
            "<",
442
            ">",
443
            "&amp;",
444
            "&lt;<>&gt;",
445
            "a<b>c&d",
446
            "&&&&<<<<>>>>",
447
        ] {
448
            let html = content(vec![run(text, 10.0, None)]).to_html();
449
            let body = html
450
                .rsplit_once("</span>")
451
                .and_then(|(head, _)| head.rsplit_once("\">").map(|(_, b)| b.to_string()))
452
                .expect("span body not found");
453
            assert_eq!(unescape(&body), text, "round-trip failed for {text:?}");
454
        }
455
    }
456

            
457
    #[test]
458
    fn to_html_escaped_text_introduces_no_raw_markup_chars() {
459
        // With no font-family, every `<`/`>` in the output must come from the
460
        // four structural tags: <div>, <span ...>, </span>, </div>.
461
        let html = content(vec![run("<<<>>>&&&", 10.0, None)]).to_html();
462
        assert_eq!(html.matches('<').count(), 4, "{html}");
463
        assert_eq!(html.matches('>').count(), 4, "{html}");
464
    }
465

            
466
    #[test]
467
    fn to_html_font_family_is_interpolated_raw_into_the_style_attribute() {
468
        // Characterization test (NOT an endorsement): unlike `text`, the font
469
        // family is written into the `style="..."` attribute with no escaping
470
        // or quoting, so a quote in the family name terminates the attribute.
471
        // Live producers never populate `styled_runs`, so this is currently
472
        // unreachable — but any future producer must sanitize the family name.
473
        let html = content(vec![run("t", 10.0, Some("\"><img onerror=x>"))]).to_html();
474
        assert!(
475
            html.contains("font-family: \"><img onerror=x>; "),
476
            "escaping behaviour changed, re-check the injection note: {html}"
477
        );
478
    }
479

            
480
    // ---------------------------------------------------------------------
481
    // numeric: font_size_px is a raw f32 Display
482
    // ---------------------------------------------------------------------
483

            
484
    #[test]
485
    fn to_html_non_finite_font_size_does_not_panic() {
486
        for (size, rendered) in [
487
            (f32::NAN, "font-size: NaNpx; "),
488
            (f32::INFINITY, "font-size: infpx; "),
489
            (f32::NEG_INFINITY, "font-size: -infpx; "),
490
        ] {
491
            let html = content(vec![run("x", size, None)]).to_html();
492
            assert!(html.contains(rendered), "{size} -> {html}");
493
            assert!(html.ends_with("</div>"), "{html}");
494
        }
495
    }
496

            
497
    #[test]
498
    fn to_html_extreme_finite_font_sizes_do_not_panic() {
499
        for size in [
500
            0.0,
501
            -0.0,
502
            -1.0,
503
            f32::MIN,
504
            f32::MAX,
505
            f32::MIN_POSITIVE,
506
            f32::EPSILON,
507
        ] {
508
            let html = content(vec![run("x", size, None)]).to_html();
509
            assert!(html.starts_with("<div><span"), "{size} -> {html}");
510
            assert!(html.ends_with("x</span></div>"), "{size} -> {html}");
511
            assert!(html.contains("font-size: "), "{size} -> {html}");
512
        }
513
    }
514

            
515
    #[test]
516
    fn to_html_alpha_is_normalized_to_0_1_at_channel_boundaries() {
517
        let alpha_of = |a: u8| {
518
            let mut r = run("x", 10.0, None);
519
            r.color = ColorU {
520
                r: 0,
521
                g: 0,
522
                b: 0,
523
                a,
524
            };
525
            content(vec![r]).to_html()
526
        };
527
        assert!(alpha_of(255).contains("rgba(0, 0, 0, 1); "));
528
        assert!(alpha_of(0).contains("rgba(0, 0, 0, 0); "));
529
        // 1/255 keeps full f32 precision — it is not truncated to 0.
530
        let expected = format!("rgba(0, 0, 0, {}); ", 1.0_f32 / 255.0);
531
        assert!(alpha_of(1).contains(&expected), "{}", alpha_of(1));
532
    }
533

            
534
    #[test]
535
    fn to_html_color_channels_are_verbatim_u8() {
536
        let mut r = run("x", 10.0, None);
537
        r.color = ColorU {
538
            r: 255,
539
            g: 0,
540
            b: 128,
541
            a: 255,
542
        };
543
        assert!(content(vec![r])
544
            .to_html()
545
            .contains("color: rgba(255, 0, 128, 1); "));
546
    }
547

            
548
    // ---------------------------------------------------------------------
549
    // unicode / hostile payloads
550
    // ---------------------------------------------------------------------
551

            
552
    #[test]
553
    fn to_html_preserves_unicode_and_control_characters() {
554
        for text in [
555
            "😀👨‍👩‍👧‍👦",              // emoji + ZWJ sequence
556
            "مرحبا بالعالم",     // RTL
557
            "e\u{0301}\u{0327}", // combining marks
558
            "a\u{0}b",           // interior NUL
559
            "line\nbreak\ttab",
560
            "\u{200B}\u{FEFF}", // zero-width space + BOM
561
            "\u{202E}reversed", // RTL override
562
        ] {
563
            let html = content(vec![run(text, 10.0, None)]).to_html();
564
            assert!(html.contains(text), "lost {text:?} in {html:?}");
565
            assert!(html.ends_with("</span></div>"), "{html:?}");
566
        }
567
    }
568

            
569
    #[test]
570
    fn to_html_large_text_does_not_panic() {
571
        let text = "&".repeat(100_000);
572
        let html = content(vec![run(&text, 10.0, None)]).to_html();
573
        // every `&` expands to the 5-byte `&amp;`
574
        assert_eq!(html.matches("&amp;").count(), 100_000);
575
        assert!(html.ends_with("</span></div>"));
576
    }
577

            
578
    #[test]
579
    fn to_html_many_runs_emits_one_span_each() {
580
        let runs: Vec<_> = (0..2_000u16)
581
            .map(|i| run("t", f32::from(i), Some("Arial")))
582
            .collect();
583
        let html = content(runs).to_html();
584
        assert_eq!(html.matches("<span style=\"").count(), 2_000);
585
        assert_eq!(html.matches("</span>").count(), 2_000);
586
    }
587

            
588
    // ---------------------------------------------------------------------
589
    // invariants: structure, purity, clone-equivalence
590
    // ---------------------------------------------------------------------
591

            
592
    #[test]
593
    fn to_html_always_wraps_output_in_a_single_div() {
594
        let cases = vec![
595
            content(Vec::new()),
596
            content(vec![run("", f32::NAN, None)]),
597
            content(vec![run("<>&", -0.0, Some("a\"b"))]),
598
            content(vec![run("😀", f32::MAX, Some(""))]),
599
        ];
600
        for c in cases {
601
            let html = c.to_html();
602
            assert!(html.starts_with("<div>"), "{html}");
603
            assert!(html.ends_with("</div>"), "{html}");
604
            assert_eq!(html.matches("<div>").count(), 1, "{html}");
605
            assert_eq!(html.matches("</div>").count(), 1, "{html}");
606
            assert_eq!(
607
                html.matches("<span style=\"").count(),
608
                html.matches("</span>").count(),
609
                "unbalanced spans: {html}"
610
            );
611
        }
612
    }
613

            
614
    #[test]
615
    fn to_html_is_pure_and_deterministic() {
616
        let c = content(vec![run("<a>", 12.5, Some("Arial")), run("&", 0.0, None)]);
617
        let before = c.clone();
618
        let first = c.to_html();
619
        let second = c.to_html();
620
        assert_eq!(first, second, "to_html is not deterministic");
621
        assert_eq!(c, before, "to_html mutated the receiver");
622
        assert_eq!(c.clone().to_html(), first, "clone renders differently");
623
    }
624
}
625

            
626
#[cfg(test)]
627
mod extract_tests {
628
    use std::sync::Arc;
629

            
630
    use azul_css::props::basic::ColorU;
631
    use rust_fontconfig::FcWeight;
632

            
633
    use super::*;
634
    use crate::text3::cache::{FontSelector, FontStack, FontStyle, StyleProperties};
635

            
636
20
    fn style(family: &str, weight: FcWeight, italic: bool, size_px: f32) -> StyleProperties {
637
        StyleProperties {
638
20
            font_stack: FontStack::Stack(vec![FontSelector {
639
20
                family: family.to_string(),
640
20
                weight,
641
20
                style: if italic {
642
                    FontStyle::Italic
643
                } else {
644
20
                    FontStyle::Normal
645
                },
646
20
                unicode_ranges: Vec::new(),
647
            }]),
648
20
            font_size_px: size_px,
649
20
            ..StyleProperties::default()
650
        }
651
20
    }
652

            
653
11
    fn plain_style() -> StyleProperties {
654
11
        style("Helvetica", FcWeight::Normal, false, 16.0)
655
11
    }
656

            
657
    /// The whole point of the copy path: formatting from the source runs has to
658
    /// reach `styled_runs`, because that is what the OS transports turn into
659
    /// RTF and HTML. It used to be hardcoded empty.
660
    ///
661
    /// NEGATIVE CONTROL: make `push` always write `StyledTextRun::default()`-ish
662
    /// values — the bold/size/family assertions below go red.
663
    #[test]
664
1
    fn formatting_reaches_the_styled_runs() {
665
1
        let mut acc = ClipboardExtract::default();
666
1
        acc.push("normal ", &plain_style());
667
1
        acc.push("bold", &style("Georgia", FcWeight::Bold, false, 24.0));
668

            
669
1
        let content = acc.finish().expect("a non-empty selection yields content");
670
1
        assert_eq!(content.plain_text.as_str(), "normal bold");
671

            
672
1
        let runs = content.styled_runs.as_slice();
673
1
        assert_eq!(runs.len(), 2);
674
1
        assert_eq!(runs[0].text.as_str(), "normal ");
675
1
        assert!(!runs[0].is_bold);
676
1
        assert_eq!(
677
1
            runs[0].font_family.as_ref().map(|f| f.as_str()),
678
            Some("Helvetica")
679
        );
680
1
        assert_eq!(runs[1].text.as_str(), "bold");
681
1
        assert!(runs[1].is_bold);
682
1
        assert_eq!(runs[1].font_size_px, 24.0);
683
1
        assert_eq!(
684
1
            runs[1].font_family.as_ref().map(|f| f.as_str()),
685
            Some("Georgia")
686
        );
687
1
    }
688

            
689
    /// `plain_text` must be exactly the concatenation of the runs. A receiver
690
    /// picking the plain flavor and one picking RTF must not end up with
691
    /// different characters — the seam's encoder drops the rich flavor outright
692
    /// when these disagree, so a mismatch silently costs all the formatting.
693
    ///
694
    /// NEGATIVE CONTROL: push to `self.plain` without pushing a run (or the
695
    /// reverse) in either `push` or `push_inheriting`.
696
    #[test]
697
1
    fn plain_text_is_exactly_the_concatenated_runs() {
698
1
        let mut acc = ClipboardExtract::default();
699
1
        acc.push("one", &plain_style());
700
1
        acc.push_inheriting("\n");
701
1
        acc.push("two", &style("Georgia", FcWeight::Bold, false, 16.0));
702
1
        acc.push_inheriting("\n");
703
1
        acc.push("three", &plain_style());
704

            
705
1
        let content = acc.finish().expect("content");
706
1
        let joined: String = content
707
1
            .styled_runs
708
1
            .as_slice()
709
1
            .iter()
710
3
            .map(|r| r.text.as_str())
711
1
            .collect();
712
1
        assert_eq!(content.plain_text.as_str(), joined);
713
1
        assert_eq!(content.plain_text.as_str(), "one\ntwo\nthree");
714
1
    }
715

            
716
    /// A style run is cut at every DOM text node and every styling change, so
717
    /// identically-formatted neighbours must merge — otherwise a paragraph in
718
    /// one font emits dozens of `<span>`s and `\b0\b` pairs for no visible
719
    /// difference.
720
    ///
721
    /// NEGATIVE CONTROL: drop the `same_formatting` arm from `push`.
722
    #[test]
723
1
    fn identically_formatted_neighbours_merge() {
724
1
        let mut acc = ClipboardExtract::default();
725
4
        for word in ["a", "b", "c", "d"] {
726
4
            acc.push(word, &plain_style());
727
4
        }
728
1
        let content = acc.finish().expect("content");
729
1
        assert_eq!(
730
1
            content.styled_runs.as_slice().len(),
731
            1,
732
            "four identically-styled pushes must collapse to one run"
733
        );
734
1
        assert_eq!(content.styled_runs.as_slice()[0].text.as_str(), "abcd");
735
1
        assert_eq!(content.plain_text.as_str(), "abcd");
736
1
    }
737

            
738
    /// The paragraph joiner in a cross-block copy inherits the formatting it
739
    /// follows, so it does not split a styled run in three.
740
    ///
741
    /// NEGATIVE CONTROL: make `push_inheriting` push a default-styled run.
742
    #[test]
743
1
    fn the_paragraph_joiner_does_not_split_a_run() {
744
1
        let mut acc = ClipboardExtract::default();
745
1
        let bold = style("Georgia", FcWeight::Bold, false, 16.0);
746
1
        acc.push("first", &bold);
747
1
        acc.push_inheriting("\n");
748
1
        acc.push("second", &bold);
749

            
750
1
        let content = acc.finish().expect("content");
751
1
        let runs = content.styled_runs.as_slice();
752
1
        assert_eq!(runs.len(), 1, "one style spans the whole thing");
753
1
        assert_eq!(runs[0].text.as_str(), "first\nsecond");
754
1
        assert!(runs[0].is_bold);
755
1
    }
756

            
757
    /// Weight is a scale and the clipboard formats have a boolean. CSS's
758
    /// `bold` is 700, so that is the cut.
759
    #[test]
760
1
    fn weight_maps_to_bold_at_seven_hundred() {
761
6
        for (weight, expect_bold) in [
762
1
            (FcWeight::Light, false),
763
1
            (FcWeight::Normal, false),
764
1
            (FcWeight::Medium, false),
765
1
            (FcWeight::SemiBold, false),
766
1
            (FcWeight::Bold, true),
767
1
            (FcWeight::Black, true),
768
        ] {
769
6
            let mut acc = ClipboardExtract::default();
770
6
            acc.push("x", &style("Helvetica", weight, false, 16.0));
771
6
            let content = acc.finish().expect("content");
772
6
            assert_eq!(
773
6
                content.styled_runs.as_slice()[0].is_bold,
774
                expect_bold,
775
                "{weight:?} mapped to the wrong boldness"
776
            );
777
        }
778
1
    }
779

            
780
    /// Oblique is a slanted upright face; every format this feeds has only
781
    /// "italic", so it must not be silently dropped.
782
    #[test]
783
1
    fn oblique_is_carried_as_italic() {
784
1
        let mut acc = ClipboardExtract::default();
785
1
        let mut oblique = plain_style();
786
1
        oblique.font_stack = FontStack::Stack(vec![FontSelector {
787
1
            family: "Helvetica".to_string(),
788
1
            weight: FcWeight::Normal,
789
1
            style: FontStyle::Oblique,
790
1
            unicode_ranges: Vec::new(),
791
1
        }]);
792
1
        acc.push("slanted", &oblique);
793
1
        let content = acc.finish().expect("content");
794
1
        assert!(content.styled_runs.as_slice()[0].is_italic);
795
1
    }
796

            
797
    /// An embedded `FontRef` has no family name a receiving application could
798
    /// resolve, so it must inherit rather than be handed the internal
799
    /// `"<embedded-font>"` debugging placeholder as if it were a font.
800
    ///
801
    /// NEGATIVE CONTROL: use `FontStack::first_family()` in `push`.
802
    #[test]
803
1
    fn an_embedded_font_has_no_family_to_publish() {
804
1
        let mut acc = ClipboardExtract::default();
805
1
        let mut embedded = plain_style();
806
        // `FontStack::Ref` needs a real FontRef; `first_selector()` returning
807
        // None is the property under test, and `Stack(vec![])` reaches the
808
        // same branch without constructing one.
809
1
        embedded.font_stack = FontStack::Stack(Vec::new());
810
1
        acc.push("icon", &embedded);
811

            
812
1
        let content = acc.finish().expect("content");
813
1
        let run = &content.styled_runs.as_slice()[0];
814
1
        assert!(run.font_family.as_ref().is_none());
815
1
        assert!(!run.is_bold && !run.is_italic);
816
1
    }
817

            
818
    /// A uniformly-styled select-all merges *every* run into one, so the merge
819
    /// has to be an append. Rebuilding the run's string each time — which is
820
    /// what constructing the FFI `AzString` per merge would do — is quadratic
821
    /// in the document, and Ctrl+A Ctrl+C is exactly when it bites.
822
    ///
823
    /// This asserts the result rather than the timing; the guard against a
824
    /// regression is that `PendingRun::text` is a `String` and `finish` is the
825
    /// only place `AzString`s are built.
826
    #[test]
827
1
    fn a_uniformly_styled_document_collapses_to_one_run() {
828
1
        let mut acc = ClipboardExtract::default();
829
1
        let s = plain_style();
830
2001
        for i in 0..2_000 {
831
2000
            acc.push("paragraph text ", &s);
832
2000
            if i + 1 < 2_000 {
833
1999
                acc.push_inheriting("\n");
834
1999
            }
835
        }
836
1
        let content = acc.finish().expect("content");
837
1
        assert_eq!(content.styled_runs.as_slice().len(), 1);
838
1
        assert_eq!(
839
1
            content.styled_runs.as_slice()[0].text.as_str().len(),
840
1
            content.plain_text.as_str().len()
841
        );
842
1
    }
843

            
844
    /// An empty selection is not a copy. Pushing nothing must not produce a
845
    /// `ClipboardContent` that would clear the user's clipboard.
846
    #[test]
847
1
    fn an_empty_selection_yields_nothing() {
848
1
        assert!(ClipboardExtract::default().finish().is_none());
849
1
        let mut acc = ClipboardExtract::default();
850
1
        acc.push("", &plain_style());
851
1
        acc.push_inheriting("");
852
1
        assert!(acc.finish().is_none());
853
1
    }
854
}