teksilo-platform 0.27.0

Platform integration for Teksilo — winit and AccessKit adapters, clipboard, OS theme, native file dialogs, drag-and-drop and menus.
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! The system clipboard over the core Wayland protocol (`wl_data_device`).
//!
//! The protocol work (the device, the serial, serving and receiving) is the
//! shared [`WaylandDataHub`]'s; this module is the clipboard's policy on top of
//! it: which MIME types we offer, which of another application's we take, and
//! how their bytes become text.
//!
//! # Offering
//!
//! A copy offers, in one source, `text/html` (for [`set_html`]) and the plain
//! text under every name a Linux application asks for it:
//! `text/plain;charset=utf-8`, `UTF8_STRING`, `text/plain` and `TEXT` (all
//! UTF-8), and `STRING` (ISO 8859-1, as the X11 conventions XWayland follows
//! define it). The HTML goes out with a `<meta charset>` declaration when it has
//! none, the way browsers put HTML on the clipboard: without one, an importer
//! that guesses (LibreOffice does) reads UTF-8 as Windows-1252.
//!
//! # Taking
//!
//! A paste takes the best text type offered, in the order
//! [`TextMime::rank`] gives, and decodes it by its charset. HTML is decoded by
//! its byte-order mark first (Firefox used to send UTF-16 with one), then its
//! MIME `charset` parameter, then as UTF-8.
//!
//! What this process copied is answered from memory, exactly as it was given,
//! without a round trip through the compositor: the editor's self-paste
//! detection compares what it copied with what the clipboard reports, and a
//! re-decoded copy (with a charset declaration added) would not compare equal.
//!
//! [`set_html`]: super::ClipboardBackend::set_html

use std::sync::Arc;
use std::time::{Duration, Instant};

use wayland_client::backend::ObjectId;

use super::ClipboardBackend;
use crate::wayland_data::io::{Limits, TransferError, read_bounded};
use crate::wayland_data::{Payload, SelectionView, WaylandDataHub};

/// What this process put on the clipboard, kept to answer its own paste.
#[derive(Debug)]
struct OwnContent {
    text: String,
    html: Option<String>,
}

/// How long a selection whose owner timed out is not asked again. A rich
/// paste asks for HTML, then for text: without this, an owner that does not
/// answer would freeze the window once per attempt.
const STALLED_FOR: Duration = Duration::from_secs(10);

/// The system clipboard on a Wayland display. See the module docs.
pub(crate) struct WaylandClipboard {
    hub: Arc<WaylandDataHub>,
    /// The selection whose owner last timed out on a paste, and when.
    stalled: Option<(ObjectId, Instant)>,
}

impl WaylandClipboard {
    /// The clipboard of winit's Wayland display.
    pub(crate) fn new(display: &winit::event_loop::OwnedDisplayHandle) -> Result<Self, String> {
        Ok(Self {
            hub: WaylandDataHub::for_display(display)?,
            stalled: None,
        })
    }

    /// The clipboard on a hub the caller made (the compositor tests).
    #[cfg(test)]
    pub(crate) fn on_hub(hub: Arc<WaylandDataHub>) -> Self {
        Self { hub, stalled: None }
    }

    fn view(&self) -> Result<SelectionView, String> {
        self.hub.with_state(|state| state.selection())
    }

    /// Read `mime` from another application's selection.
    fn read(&mut self, mime: &str) -> Result<Vec<u8>, String> {
        let offer = self.hub.with_state(|state| state.selection_offer_id())?;
        if let (Some(offer), Some((stalled, when))) = (&offer, &self.stalled)
            && offer == stalled
            && when.elapsed() < STALLED_FOR
        {
            return Err("the application holding the clipboard did not answer a moment ago".into());
        }
        // The hub is released before the read: its thread keeps serving the
        // compositor meanwhile.
        let fd = self
            .hub
            .with_state(|state| state.receive_selection(mime))??;
        read_bounded(fd, Limits::PASTE).map_err(|err| {
            if matches!(err, TransferError::Idle(_) | TransferError::Total(_)) {
                self.stalled = offer.map(|offer| (offer, Instant::now()));
            }
            format!("reading the clipboard as {mime} failed: {err}")
        })
    }

    fn set(&self, text: &str, html: Option<&str>) -> Result<(), String> {
        let payload = payload(text, html);
        let owner = Arc::new(OwnContent {
            text: text.to_string(),
            html: html.map(str::to_string),
        });
        self.hub
            .with_state(|state| state.set_selection(payload, owner))?
    }
}

fn own(data: &Arc<dyn std::any::Any + Send + Sync>) -> Option<&OwnContent> {
    data.downcast_ref::<OwnContent>()
}

impl ClipboardBackend for WaylandClipboard {
    fn get_text(&mut self) -> Result<String, String> {
        match self.view()? {
            SelectionView::Own(data) => own(&data)
                .map(|content| content.text.clone())
                .ok_or_else(|| "the clipboard holds no text".to_string()),
            SelectionView::Foreign(mimes) => {
                let best = best_text_mime(&mimes)
                    .ok_or_else(|| "the clipboard holds no text".to_string())?;
                let bytes = self.read(best.mime)?;
                Ok(best.decode(&bytes))
            }
            SelectionView::Empty => Err("the clipboard is empty".into()),
        }
    }

    fn set_text(&mut self, text: &str) -> Result<(), String> {
        self.set(text, None)
    }

    fn has_text(&mut self) -> bool {
        match self.view() {
            Ok(SelectionView::Own(data)) => own(&data).is_some_and(|c| !c.text.is_empty()),
            Ok(SelectionView::Foreign(mimes)) => best_text_mime(&mimes).is_some(),
            Ok(SelectionView::Empty) | Err(_) => false,
        }
    }

    fn get_html(&mut self) -> Result<String, String> {
        match self.view()? {
            SelectionView::Own(data) => own(&data)
                .and_then(|content| content.html.clone())
                .filter(|html| !html.is_empty())
                .ok_or_else(|| "no html payload".to_string()),
            SelectionView::Foreign(mimes) => {
                let mime = html_mime(&mimes).ok_or_else(|| "no html payload".to_string())?;
                let bytes = self.read(mime)?;
                Ok(decode_html(mime, &bytes))
            }
            SelectionView::Empty => Err("the clipboard is empty".into()),
        }
    }

    fn set_html(&mut self, html: &str, plain_fallback: &str) -> Result<(), String> {
        self.set(plain_fallback, Some(html))
    }

    fn has_html(&mut self) -> bool {
        match self.view() {
            Ok(SelectionView::Own(data)) => own(&data)
                .and_then(|c| c.html.as_deref())
                .is_some_and(|html| !html.is_empty()),
            Ok(SelectionView::Foreign(mimes)) => html_mime(&mimes).is_some(),
            Ok(SelectionView::Empty) | Err(_) => false,
        }
    }
}

// ---------------------------------------------------------------------------
// MIME policy (pure, tested without a compositor)
// ---------------------------------------------------------------------------

/// The text types a copy offers, each with how its bytes are written.
const TEXT_OFFERS: &[(&str, Charset)] = &[
    ("text/plain;charset=utf-8", Charset::Utf8),
    ("UTF8_STRING", Charset::Utf8),
    ("text/plain", Charset::Utf8),
    ("TEXT", Charset::Utf8),
    ("STRING", Charset::Latin1),
];

/// The HTML type a copy offers.
const HTML_MIME: &str = "text/html";

/// What a copy of `text` (and `html`) offers, in one source.
fn payload(text: &str, html: Option<&str>) -> Payload {
    let mut payload: Payload = Vec::with_capacity(TEXT_OFFERS.len() + 1);
    if let Some(html) = html {
        payload.push((
            HTML_MIME.to_string(),
            Arc::from(with_charset_declaration(html).into_bytes()),
        ));
    }
    let utf8: Arc<[u8]> = Arc::from(text.as_bytes());
    for (mime, charset) in TEXT_OFFERS {
        let bytes = match charset {
            Charset::Latin1 => Arc::from(encode_latin1(text)),
            _ => utf8.clone(),
        };
        payload.push(((*mime).to_string(), bytes));
    }
    payload
}

/// `html`, with a UTF-8 declaration in front unless it declares a charset of
/// its own near its head.
fn with_charset_declaration(html: &str) -> String {
    if declares_charset(html) {
        html.to_string()
    } else {
        format!("<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">{html}")
    }
}

/// Whether a `<meta>` tag in the first 1024 characters of `html` names a
/// charset (`<meta charset=...>`, or `http-equiv` with a `content` type that
/// carries one). The word in the text itself does not count: a copy of a
/// sentence about charsets still needs the declaration.
fn declares_charset(html: &str) -> bool {
    let head: String = html
        .chars()
        .take(1024)
        .collect::<String>()
        .to_ascii_lowercase();
    let mut rest = head.as_str();
    while let Some(start) = rest.find("<meta") {
        let tag = &rest[start..];
        let end = tag.find('>').unwrap_or(tag.len());
        if tag[..end].contains("charset") {
            return true;
        }
        rest = &tag[end..];
    }
    false
}

/// ISO 8859-1, each character past U+00FF written as `?`.
fn encode_latin1(text: &str) -> Vec<u8> {
    text.chars()
        .map(|c| u8::try_from(u32::from(c)).unwrap_or(b'?'))
        .collect()
}

/// A character encoding we can read.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Charset {
    Utf8,
    /// UTF-16 by its byte-order mark, little-endian without one.
    Utf16,
    Utf16Le,
    Utf16Be,
    Latin1,
    /// The X11 `TEXT` target: UTF-8 when it is valid UTF-8, else ISO 8859-1.
    Utf8OrLatin1,
}

impl Charset {
    fn from_label(label: &str) -> Option<Self> {
        match label.trim().trim_matches('"').to_ascii_lowercase().as_str() {
            "utf-8" | "utf8" => Some(Self::Utf8),
            "utf-16" | "utf16" | "unicode" => Some(Self::Utf16),
            "utf-16le" => Some(Self::Utf16Le),
            "utf-16be" => Some(Self::Utf16Be),
            "iso-8859-1" | "iso8859-1" | "iso_8859-1" | "latin1" | "latin-1" | "us-ascii"
            | "ascii" => Some(Self::Latin1),
            _ => None,
        }
    }

    fn decode(self, bytes: &[u8]) -> String {
        let text = match self {
            Self::Utf8 => decode_utf8(bytes),
            Self::Utf16 => match bytes {
                [0xFE, 0xFF, rest @ ..] => decode_utf16(rest, u16::from_be_bytes),
                [0xFF, 0xFE, rest @ ..] => decode_utf16(rest, u16::from_le_bytes),
                _ => decode_utf16(bytes, u16::from_le_bytes),
            },
            Self::Utf16Le => decode_utf16(strip_prefix(bytes, &[0xFF, 0xFE]), u16::from_le_bytes),
            Self::Utf16Be => decode_utf16(strip_prefix(bytes, &[0xFE, 0xFF]), u16::from_be_bytes),
            Self::Latin1 => bytes.iter().map(|&b| char::from(b)).collect(),
            Self::Utf8OrLatin1 => match std::str::from_utf8(bytes) {
                Ok(text) => text.to_string(),
                Err(_) => bytes.iter().map(|&b| char::from(b)).collect(),
            },
        };
        // C-string senders end with a NUL, which is not text.
        text.trim_end_matches('\0').to_string()
    }
}

fn strip_prefix<'a>(bytes: &'a [u8], prefix: &[u8]) -> &'a [u8] {
    bytes.strip_prefix(prefix).unwrap_or(bytes)
}

fn decode_utf8(bytes: &[u8]) -> String {
    String::from_utf8_lossy(strip_prefix(bytes, &[0xEF, 0xBB, 0xBF])).into_owned()
}

fn decode_utf16(bytes: &[u8], unit: fn([u8; 2]) -> u16) -> String {
    let units = bytes.as_chunks::<2>().0.iter().map(|pair| unit(*pair));
    char::decode_utf16(units)
        .map(|c| c.unwrap_or(char::REPLACEMENT_CHARACTER))
        .collect()
}

/// A text type another application offers, and how to read it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct TextMime<'a> {
    mime: &'a str,
    charset: Charset,
    /// Lower is better.
    rank: u8,
}

/// The rank of `text/uri-list`, below every plain text type.
const URI_LIST_RANK: u8 = 6;

impl TextMime<'_> {
    fn decode(&self, bytes: &[u8]) -> String {
        let text = self.charset.decode(bytes);
        if self.rank == URI_LIST_RANK {
            uri_list_text(&text)
        } else {
            text
        }
    }
}

/// The URIs of a `text/uri-list` (RFC 2483: CRLF-separated, `#` starts a
/// comment line), one per line.
fn uri_list_text(list: &str) -> String {
    list.lines()
        .map(str::trim)
        .filter(|line| !line.is_empty() && !line.starts_with('#'))
        .collect::<Vec<_>>()
        .join("\n")
}

/// Split `type/subtype;param=value;…` into the lowercase essence and the
/// `charset` parameter, if any.
fn essence_and_charset(mime: &str) -> (String, Option<&str>) {
    let mut parts = mime.split(';');
    let essence = parts.next().unwrap_or("").trim().to_ascii_lowercase();
    let charset = parts.find_map(|param| {
        let (name, value) = param.split_once('=')?;
        name.trim().eq_ignore_ascii_case("charset").then_some(value)
    });
    (essence, charset)
}

impl<'a> TextMime<'a> {
    /// How good `mime` is as text, or `None` when it is not text we read.
    ///
    /// 0. `text/plain;charset=utf-8`: the standard, exact name;
    /// 1. `UTF8_STRING`: the X11 name for the same, all XWayland clients;
    /// 2. `text/plain` with another charset we can decode;
    /// 3. `text/plain` with none: UTF-8 in practice on Linux;
    /// 4. `TEXT`: X11's "any encoding", UTF-8 when it is valid UTF-8;
    /// 5. `STRING`: X11's ISO 8859-1, which loses everything past U+00FF;
    /// 6. `text/uri-list`, read as its URIs: all a file manager offers for a
    ///    copied file (Dolphin), which `arboard` pasted as text too.
    fn rank(mime: &'a str) -> Option<Self> {
        let (rank, charset) = match mime {
            "UTF8_STRING" => (1, Charset::Utf8),
            "TEXT" => (4, Charset::Utf8OrLatin1),
            "STRING" => (5, Charset::Latin1),
            _ => {
                let (essence, charset) = essence_and_charset(mime);
                if essence == "text/uri-list" {
                    return Some(Self {
                        mime,
                        charset: Charset::Utf8,
                        rank: URI_LIST_RANK,
                    });
                }
                if essence != "text/plain" {
                    return None;
                }
                match charset {
                    None => (3, Charset::Utf8),
                    Some(label) => match Charset::from_label(label)? {
                        Charset::Utf8 => (0, Charset::Utf8),
                        other => (2, other),
                    },
                }
            }
        };
        Some(Self {
            mime,
            charset,
            rank,
        })
    }
}

/// The best text type in `offered`.
fn best_text_mime(offered: &[String]) -> Option<TextMime<'_>> {
    offered
        .iter()
        .filter_map(|mime| TextMime::rank(mime))
        .min_by_key(|candidate| candidate.rank)
}

/// The HTML type in `offered`: `text/html` itself first, then one with
/// parameters.
fn html_mime(offered: &[String]) -> Option<&str> {
    offered
        .iter()
        .find(|m| m.as_str() == HTML_MIME)
        .or_else(|| {
            offered
                .iter()
                .find(|m| essence_and_charset(m).0 == HTML_MIME)
        })
        .map(String::as_str)
}

/// Decode HTML: byte-order mark first, then the type's `charset` parameter,
/// then UTF-8.
fn decode_html(mime: &str, bytes: &[u8]) -> String {
    let charset = match bytes {
        [0xEF, 0xBB, 0xBF, ..] => Charset::Utf8,
        [0xFF, 0xFE, ..] | [0xFE, 0xFF, ..] => Charset::Utf16,
        _ => essence_and_charset(mime)
            .1
            .and_then(Charset::from_label)
            .unwrap_or(Charset::Utf8),
    };
    charset.decode(bytes)
}

#[cfg(test)]
mod compositor_tests;

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

    fn strings(list: &[&str]) -> Vec<String> {
        list.iter().map(|s| (*s).to_string()).collect()
    }

    #[test]
    fn utf8_text_plain_beats_every_other_text_type() {
        let offered = strings(&[
            "STRING",
            "TEXT",
            "text/plain",
            "UTF8_STRING",
            "text/plain;charset=utf-8",
            "text/html",
        ]);
        assert_eq!(
            best_text_mime(&offered).map(|m| m.mime),
            Some("text/plain;charset=utf-8")
        );
    }

    #[test]
    fn the_ranking_falls_back_in_order() {
        let order = [
            "UTF8_STRING",
            "text/plain;charset=utf-16",
            "text/plain",
            "TEXT",
            "STRING",
            "text/uri-list",
        ];
        for i in 0..order.len() {
            let offered = strings(&order[i..]);
            assert_eq!(best_text_mime(&offered).map(|m| m.mime), Some(order[i]));
        }
    }

    #[test]
    fn charset_parameters_are_read_however_they_are_written() {
        for mime in [
            "text/plain;charset=UTF-8",
            "text/plain; charset=\"utf-8\"",
            "TEXT/PLAIN;CHARSET=utf8",
        ] {
            let offered = strings(&[mime]);
            let best = best_text_mime(&offered).unwrap();
            assert_eq!((best.rank, best.charset), (0, Charset::Utf8), "{mime}");
        }
    }

    #[test]
    fn an_unknown_charset_and_non_text_are_not_taken() {
        assert_eq!(
            best_text_mime(&strings(&["text/plain;charset=koi8-r", "image/png"])),
            None
        );
    }

    #[test]
    fn a_copied_file_pastes_as_its_uri() {
        // Dolphin offers a copied file as `text/uri-list` and nothing else.
        let offered = strings(&["text/uri-list"]);
        let best = best_text_mime(&offered).unwrap();
        assert_eq!(
            best.decode(b"# from Dolphin\r\nfile:///home/a/x.txt\r\nfile:///home/a/y%20z.txt\r\n"),
            "file:///home/a/x.txt\nfile:///home/a/y%20z.txt"
        );
    }

    #[test]
    fn charsets_decode() {
        assert_eq!(Charset::Utf8.decode("été\0".as_bytes()), "été");
        assert_eq!(Charset::Utf8.decode(b"\xEF\xBB\xBFbom"), "bom");
        assert_eq!(Charset::Latin1.decode(&[0x63, 0x61, 0x66, 0xE9]), "café");
        assert_eq!(Charset::Utf16.decode(&[0xFF, 0xFE, b'h', 0, b'i', 0]), "hi");
        assert_eq!(Charset::Utf16.decode(&[0xFE, 0xFF, 0, b'h', 0, b'i']), "hi");
        assert_eq!(Charset::Utf16.decode(&[b'h', 0, b'i', 0]), "hi");
        assert_eq!(Charset::Utf16Be.decode(&[0, b'o', 0, b'k']), "ok");
        assert_eq!(Charset::Utf8OrLatin1.decode("été".as_bytes()), "été");
        assert_eq!(Charset::Utf8OrLatin1.decode(&[0xE9]), "é");
    }

    #[test]
    fn html_is_decoded_by_its_mark_then_its_charset_then_as_utf8() {
        let utf16: Vec<u8> = [0xFF, 0xFE]
            .into_iter()
            .chain("<b>é</b>".encode_utf16().flat_map(u16::to_le_bytes))
            .collect();
        assert_eq!(decode_html("text/html", &utf16), "<b>é</b>");
        assert_eq!(
            decode_html("text/html;charset=iso-8859-1", &[b'<', b'p', b'>', 0xE9]),
            "<p>é"
        );
        assert_eq!(decode_html("text/html", "<p>é</p>".as_bytes()), "<p>é</p>");
    }

    #[test]
    fn html_is_found_with_or_without_parameters() {
        assert_eq!(
            html_mime(&strings(&["text/plain", "text/html"])),
            Some("text/html")
        );
        assert_eq!(
            html_mime(&strings(&["text/html;charset=utf-8"])),
            Some("text/html;charset=utf-8")
        );
        assert_eq!(html_mime(&strings(&["text/plain", "text/xhtml"])), None);
    }

    #[test]
    fn a_copy_of_text_offers_every_text_name_and_no_html() {
        let payload = payload("café ✓", None);
        let mimes: Vec<&str> = payload.iter().map(|(m, _)| m.as_str()).collect();
        assert_eq!(
            mimes,
            [
                "text/plain;charset=utf-8",
                "UTF8_STRING",
                "text/plain",
                "TEXT",
                "STRING"
            ]
        );
        for (mime, bytes) in &payload {
            let expected: &[u8] = if mime == "STRING" {
                b"caf\xE9 ?"
            } else {
                "café ✓".as_bytes()
            };
            assert_eq!(&**bytes, expected, "{mime}");
        }
    }

    #[test]
    fn a_copy_of_html_offers_html_and_its_plain_text_in_one_source() {
        let payload = payload("plain", Some("<p>rich</p>"));
        assert_eq!(payload[0].0, "text/html");
        let html = std::str::from_utf8(&payload[0].1).unwrap();
        assert!(html.ends_with("<p>rich</p>"));
        assert!(html.contains("charset=utf-8"));
        let plain = payload
            .iter()
            .find(|(m, _)| m == "text/plain;charset=utf-8")
            .unwrap();
        assert_eq!(&*plain.1, b"plain");
    }

    #[test]
    fn html_that_declares_its_charset_is_offered_unchanged() {
        let html = "<html><head><meta charset=\"utf-8\"></head><body>x</body></html>";
        assert_eq!(with_charset_declaration(html), html);
    }

    #[test]
    fn an_http_equiv_declaration_counts_too() {
        let html = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1252\"><p>x</p>";
        assert_eq!(with_charset_declaration(html), html);
    }

    #[test]
    fn the_word_charset_in_the_text_is_not_a_declaration() {
        let html = "<p>Set the charset to UTF-8, café</p>";
        let served = with_charset_declaration(html);
        assert!(
            served.starts_with("<meta http-equiv=\"content-type\""),
            "{served}"
        );
        assert!(served.ends_with(html));
    }

    #[test]
    fn a_meta_without_a_charset_is_not_a_declaration() {
        assert!(!declares_charset(
            "<meta name=\"generator\" content=\"x\"><p>the charset</p>"
        ));
    }

    #[test]
    fn the_editor_marker_stays_near_the_head() {
        // The rich-text editor finds its own copies by a comment in the first
        // 1024 bytes; the declaration must not push it out of that window.
        let html = "<!--teksilo-rtc:0123456789abcdef0123456789abcdef--><p>x</p>";
        let served = with_charset_declaration(html);
        assert!(served.find("teksilo-rtc:").unwrap() < 200);
    }

    #[test]
    fn our_copy_round_trips_through_our_own_decoder() {
        for (mime, bytes) in payload("ligne 1\nligne 2 ☃ ✓", None) {
            let decoded = best_text_mime(std::slice::from_ref(&mime))
                .unwrap()
                .decode(&bytes);
            let expected = if mime == "STRING" {
                "ligne 1\nligne 2 ? ?"
            } else {
                "ligne 1\nligne 2 ☃ ✓"
            };
            assert_eq!(decoded, expected, "{mime}");
        }
    }
}