1
//! Clipboard Manager
2
//!
3
//! Manages clipboard content flow between the system clipboard and
4
//! the application.
5
//!
6
//! ## Architecture
7
//!
8
//! The clipboard manager acts as a bridge between system clipboard
9
//! operations and user callbacks:
10
//!
11
//! 1. **Paste Flow**: System clipboard → `ClipboardManager` → User Callback → `TextInputManager`
12
//!
13
//!    - When Ctrl+V is pressed, `event_v2` reads system clipboard and calls `set_paste_content()`
14
//!    - User's `On::Paste` callback can inspect content via `get_clipboard_content()`
15
//!    - User can modify/block paste by not calling the default paste action
16
//!    - After callback, content is cleared for next operation
17
//!
18
//! 2. **Copy Flow**: Selection → User Callback → `ClipboardManager` → System clipboard
19
//!
20
//!    - When Ctrl+C is pressed, user's `On::Copy` callback fires
21
//!    - Callback can inspect selected content and override via `set_copy_content()`
22
//!    - `event_v2` calls `get_copy_content()` to get final content (override or default)
23
//!    - Content is written to system clipboard via platform sync
24
//!    - After callback, content is cleared for next operation
25
//!
26
//! 3. **Cut Flow**: Same as Copy + delete selection
27

            
28
use crate::managers::selection::ClipboardContent;
29

            
30
/// Manages clipboard content flow between system clipboard and application
31
///
32
/// This manager temporarily holds clipboard content during clipboard operations,
33
/// allowing user callbacks to inspect and modify content before it's committed
34
/// to the system clipboard or pasted into the document.
35
#[derive(Debug, Clone, Default)]
36
pub struct ClipboardManager {
37
    /// Content from system clipboard when paste is triggered
38
    /// Available to user callbacks via `CallbackInfo::get_clipboard_content()`
39
    pending_paste_content: Option<ClipboardContent>,
40

            
41
    /// Content to be written to system clipboard after copy/cut
42
    /// Set by user callbacks via `CallbackInfo::set_copy_content()`
43
    pending_copy_content: Option<ClipboardContent>,
44
}
45

            
46
impl ClipboardManager {
47
    /// Create a new empty clipboard manager
48
    #[must_use]
49
7742
    pub const fn new() -> Self {
50
7742
        Self {
51
7742
            pending_paste_content: None,
52
7742
            pending_copy_content: None,
53
7742
        }
54
7742
    }
55

            
56
    // Paste Operations (System → Application)
57

            
58
    /// Sets content from the system clipboard (called before paste callbacks).
59
10892
    pub fn set_paste_content(&mut self, content: ClipboardContent) {
60
10892
        self.pending_paste_content = Some(content);
61
10892
    }
62

            
63
    /// Returns the pending paste content, if any.
64
    #[must_use]
65
6742
    pub const fn get_paste_content(&self) -> Option<&ClipboardContent> {
66
6742
        self.pending_paste_content.as_ref()
67
6742
    }
68

            
69
    // Copy Operations (Application → System)
70

            
71
    /// Sets content to be copied to the system clipboard.
72
10907
    pub fn set_copy_content(&mut self, content: ClipboardContent) {
73
10907
        self.pending_copy_content = Some(content);
74
10907
    }
75

            
76
    /// Returns the pending copy content, if any.
77
    #[must_use]
78
5736
    pub const fn get_copy_content(&self) -> Option<&ClipboardContent> {
79
5736
        self.pending_copy_content.as_ref()
80
5736
    }
81

            
82
    /// Takes the copy content, consuming it.
83
10811
    pub const fn take_copy_content(&mut self) -> Option<ClipboardContent> {
84
10811
        self.pending_copy_content.take()
85
10811
    }
86

            
87
    // Lifecycle Management
88

            
89
    /// Clears all pending clipboard content.
90
741
    pub fn clear(&mut self) {
91
741
        self.pending_paste_content = None;
92
741
        self.pending_copy_content = None;
93
741
    }
94

            
95
    /// Clears only paste content.
96
10758
    pub fn clear_paste(&mut self) {
97
10758
        self.pending_paste_content = None;
98
10758
    }
99

            
100
    /// Clears only copy content.
101
739
    pub fn clear_copy(&mut self) {
102
739
        self.pending_copy_content = None;
103
739
    }
104

            
105
    /// Returns `true` if there's pending paste content.
106
    #[must_use]
107
16761
    pub const fn has_paste_content(&self) -> bool {
108
16761
        self.pending_paste_content.is_some()
109
16761
    }
110

            
111
    /// Returns `true` if there's pending copy content.
112
    #[must_use]
113
15751
    pub const fn has_copy_content(&self) -> bool {
114
15751
        self.pending_copy_content.is_some()
115
15751
    }
116
}
117

            
118
#[cfg(test)]
119
mod autotest_generated {
120
    use azul_css::{props::basic::ColorU, AzString, OptionString};
121

            
122
    use super::*;
123
    use crate::managers::selection::StyledTextRun;
124

            
125
    // =========================================================================
126
    // Fixtures
127
    //
128
    // `ClipboardManager` is a two-slot `Option` cell, so the adversarial
129
    // surface is not arithmetic but *ownership and state*: the payload
130
    // (`ClipboardContent`) owns FFI vectors (`AzString`/`StyledTextRunVec`)
131
    // with destructor function pointers, so every set / take / clear / clone
132
    // is a chance for a double-free, a shallow clone that aliases a heap
133
    // buffer, or a slot leaking into the wrong slot. The tests below therefore
134
    // hammer: slot isolation, take-consumes semantics, deep-clone
135
    // independence + use-after-free, hostile payloads (1 MiB text, NUL bytes,
136
    // emoji/RTL/combining marks, NaN / infinite / negative-zero font sizes),
137
    // and a model-based state machine over the whole API.
138
    // =========================================================================
139

            
140
    /// Plain-text clipboard payload with no styled runs (what every live
141
    /// producer in the engine currently builds).
142
    fn plain(text: &str) -> ClipboardContent {
143
        ClipboardContent {
144
            plain_text: AzString::from(text),
145
            styled_runs: Vec::<StyledTextRun>::new().into(),
146
        }
147
    }
148

            
149
    /// A single styled run, parameterized on the numerically hostile field.
150
    fn run(text: &str, font_size_px: f32, family: Option<&str>) -> StyledTextRun {
151
        StyledTextRun {
152
            text: AzString::from(text),
153
            font_family: family.map_or(OptionString::None, |f| {
154
                OptionString::Some(AzString::from(f))
155
            }),
156
            font_size_px,
157
            color: ColorU {
158
                r: 1,
159
                g: 2,
160
                b: 3,
161
                a: 4,
162
            },
163
            is_bold: true,
164
            is_italic: false,
165
        }
166
    }
167

            
168
    /// Rich clipboard payload carrying `runs`.
169
    fn rich(text: &str, runs: Vec<StyledTextRun>) -> ClipboardContent {
170
        ClipboardContent {
171
            plain_text: AzString::from(text),
172
            styled_runs: runs.into(),
173
        }
174
    }
175

            
176
    /// Strings that have historically broken UTF-8 / FFI string handling.
177
    fn hostile_strings() -> Vec<String> {
178
        vec![
179
            String::new(),                           // empty
180
            "\0".to_string(),                        // lone NUL
181
            "a\0b\0\0c".to_string(),                 // interior NULs
182
            "\r\n\t\x0b\x0c\x1b[0m".to_string(),     // control chars + ANSI
183
            "👨‍👩‍👧‍👦".to_string(),                        // ZWJ emoji family
184
            "e\u{0301}\u{0301}\u{0301}".to_string(), // stacked combining marks
185
            "مرحبا بالعالم".to_string(),             // RTL
186
            "\u{202e}reversed\u{202c}".to_string(),  // bidi override
187
            "\u{feff}bom".to_string(),               // BOM
188
            "𝕬𝖟𝖚𝖑".to_string(),                      // 4-byte codepoints
189
            "\u{10ffff}".to_string(),                // max scalar value
190
            "line1\nline2\r\nline3".to_string(),     // mixed newlines
191
            "x".repeat(1024 * 1024),                 // 1 MiB
192
            "🦀".repeat(100_000),                    // 400 KiB of 4-byte chars
193
        ]
194
    }
195

            
196
    /// NaN-tolerant structural comparison: `ClipboardContent` derives
197
    /// `PartialEq`, but `StyledTextRun::font_size_px` is an `f32`, so `==` is
198
    /// not reflexive once a NaN is in play. Compare bit patterns instead.
199
    fn content_eq_bitwise(a: &ClipboardContent, b: &ClipboardContent) -> bool {
200
        if a.plain_text.as_str() != b.plain_text.as_str() {
201
            return false;
202
        }
203
        let (ra, rb) = (a.styled_runs.as_slice(), b.styled_runs.as_slice());
204
        ra.len() == rb.len()
205
            && ra.iter().zip(rb.iter()).all(|(x, y)| {
206
                x.text.as_str() == y.text.as_str()
207
                    && x.font_family == y.font_family
208
                    && x.font_size_px.to_bits() == y.font_size_px.to_bits()
209
                    && x.color == y.color
210
                    && x.is_bold == y.is_bold
211
                    && x.is_italic == y.is_italic
212
            })
213
    }
214

            
215
    // =========================================================================
216
    // 1. Constructor + invariants
217
    // =========================================================================
218

            
219
    #[test]
220
    fn new_starts_empty_on_both_slots() {
221
        let m = ClipboardManager::new();
222
        assert!(m.get_paste_content().is_none());
223
        assert!(m.get_copy_content().is_none());
224
        assert!(!m.has_paste_content());
225
        assert!(!m.has_copy_content());
226
    }
227

            
228
    #[test]
229
    fn new_is_usable_in_const_context() {
230
        // `new()` is declared `const fn`; if that ever regresses this stops
231
        // compiling rather than silently becoming a runtime constructor.
232
        const EMPTY: ClipboardManager = ClipboardManager::new();
233
        assert!(!EMPTY.has_paste_content());
234
        assert!(!EMPTY.has_copy_content());
235
    }
236

            
237
    #[test]
238
    fn default_is_indistinguishable_from_new() {
239
        let d = ClipboardManager::default();
240
        let n = ClipboardManager::new();
241
        assert_eq!(d.has_paste_content(), n.has_paste_content());
242
        assert_eq!(d.has_copy_content(), n.has_copy_content());
243
        assert_eq!(d.get_paste_content(), n.get_paste_content());
244
        assert_eq!(d.get_copy_content(), n.get_copy_content());
245
    }
246

            
247
    // =========================================================================
248
    // 2. Round-trip: what goes in comes back out, byte for byte
249
    // =========================================================================
250

            
251
    #[test]
252
    fn paste_roundtrip_preserves_hostile_payloads() {
253
        for s in hostile_strings() {
254
            let mut m = ClipboardManager::new();
255
            m.set_paste_content(plain(&s));
256

            
257
            let got = m.get_paste_content().expect("paste content must be set");
258
            assert_eq!(
259
                got.plain_text.as_str(),
260
                s.as_str(),
261
                "paste payload mutated (len {})",
262
                s.len()
263
            );
264
            assert_eq!(
265
                got.plain_text.as_str().len(),
266
                s.len(),
267
                "byte length changed"
268
            );
269
            assert!(m.has_paste_content());
270
            // The copy slot must stay untouched by a paste write.
271
            assert!(!m.has_copy_content());
272
        }
273
    }
274

            
275
    #[test]
276
    fn copy_roundtrip_preserves_hostile_payloads() {
277
        for s in hostile_strings() {
278
            let mut m = ClipboardManager::new();
279
            m.set_copy_content(plain(&s));
280

            
281
            assert_eq!(
282
                m.get_copy_content()
283
                    .expect("copy content must be set")
284
                    .plain_text
285
                    .as_str(),
286
                s.as_str()
287
            );
288
            // take() must hand back exactly what was put in.
289
            let taken = m.take_copy_content().expect("take must yield the content");
290
            assert_eq!(taken.plain_text.as_str(), s.as_str());
291
            assert_eq!(taken.plain_text.as_str().chars().count(), s.chars().count());
292
            assert!(!m.has_paste_content());
293
        }
294
    }
295

            
296
    #[test]
297
    fn empty_string_content_is_still_present_content() {
298
        // Presence, not emptiness: an empty selection copied to the clipboard
299
        // must still register as "there is content", otherwise the copy path
300
        // would silently fall back to a stale system clipboard.
301
        let mut m = ClipboardManager::new();
302
        m.set_paste_content(plain(""));
303
        m.set_copy_content(plain(""));
304

            
305
        assert!(m.has_paste_content());
306
        assert!(m.has_copy_content());
307
        assert_eq!(m.get_paste_content().unwrap().plain_text.as_str(), "");
308
        assert_eq!(m.get_copy_content().unwrap().plain_text.as_str(), "");
309
    }
310

            
311
    #[test]
312
    fn one_mib_payload_survives_a_full_set_take_cycle() {
313
        let big = "az".repeat(512 * 1024); // exactly 1 MiB
314
        let mut m = ClipboardManager::new();
315
        m.set_copy_content(plain(&big));
316

            
317
        let taken = m
318
            .take_copy_content()
319
            .expect("1 MiB payload must round-trip");
320
        assert_eq!(taken.plain_text.as_str().len(), 1024 * 1024);
321
        assert_eq!(taken.plain_text.as_str(), big.as_str());
322
        assert!(!m.has_copy_content());
323
    }
324

            
325
    #[test]
326
    fn styled_runs_roundtrip_intact() {
327
        let runs = vec![
328
            run("hello", 12.0, Some("Arial")),
329
            run("", 0.0, None),
330
            run("🦀", 999.5, Some("")),
331
        ];
332
        let content = rich("hello🦀", runs);
333

            
334
        let mut m = ClipboardManager::new();
335
        m.set_copy_content(content.clone());
336

            
337
        let got = m.get_copy_content().expect("rich content must be set");
338
        assert_eq!(got.styled_runs.as_slice().len(), 3);
339
        assert!(content_eq_bitwise(got, &content));
340
        // Derived PartialEq must agree with the structural compare when no NaN
341
        // is involved.
342
        assert_eq!(*got, content);
343

            
344
        let taken = m.take_copy_content().unwrap();
345
        assert!(content_eq_bitwise(&taken, &content));
346
    }
347

            
348
    #[test]
349
    fn many_styled_runs_roundtrip() {
350
        let runs: Vec<StyledTextRun> = (0..5_000)
351
            .map(|i| run(&format!("run-{i}"), i as f32, Some("Font")))
352
            .collect();
353
        let content = rich("many", runs);
354

            
355
        let mut m = ClipboardManager::new();
356
        m.set_paste_content(content.clone());
357

            
358
        let got = m.get_paste_content().unwrap();
359
        assert_eq!(got.styled_runs.as_slice().len(), 5_000);
360
        assert_eq!(got.styled_runs.as_slice()[4_999].text.as_str(), "run-4999");
361
        assert!(content_eq_bitwise(got, &content));
362
    }
363

            
364
    // =========================================================================
365
    // 3. Numeric hostility carried through the manager
366
    // =========================================================================
367

            
368
    #[test]
369
    fn extreme_font_sizes_pass_through_bit_exact() {
370
        let extremes = [
371
            f32::INFINITY,
372
            f32::NEG_INFINITY,
373
            f32::MAX,
374
            f32::MIN,
375
            f32::MIN_POSITIVE,
376
            f32::EPSILON,
377
            0.0_f32,
378
            -0.0_f32,
379
            -1.0_f32,
380
        ];
381

            
382
        for size in extremes {
383
            let content = rich("x", vec![run("x", size, None)]);
384
            let mut m = ClipboardManager::new();
385
            m.set_copy_content(content.clone());
386

            
387
            let got = m.take_copy_content().expect("content must survive");
388
            let stored = got.styled_runs.as_slice()[0].font_size_px;
389
            // `to_bits` so that -0.0 != 0.0 is actually caught (they compare
390
            // equal under `==`).
391
            assert_eq!(
392
                stored.to_bits(),
393
                size.to_bits(),
394
                "font_size_px {size} was not preserved bit-exactly"
395
            );
396
        }
397
    }
398

            
399
    #[test]
400
    fn nan_font_size_survives_but_breaks_derived_equality() {
401
        let content = rich("nan", vec![run("nan", f32::NAN, Some("F"))]);
402
        let mut m = ClipboardManager::new();
403
        m.set_paste_content(content.clone());
404

            
405
        let got = m
406
            .get_paste_content()
407
            .expect("NaN payload must still be stored");
408
        assert!(
409
            got.styled_runs.as_slice()[0].font_size_px.is_nan(),
410
            "NaN font size must be stored as-is, not normalized"
411
        );
412
        assert!(content_eq_bitwise(got, &content));
413

            
414
        // Documented consequence: derived PartialEq on ClipboardContent is not
415
        // reflexive once a NaN run is present. Callers must not use `==` on
416
        // clipboard content to detect "unchanged" when styled runs are in play.
417
        assert_ne!(content, content.clone());
418
        assert_ne!(m.get_paste_content(), Some(&content));
419

            
420
        // Predicates are unaffected by the payload's numeric contents.
421
        assert!(m.has_paste_content());
422
    }
423

            
424
    #[test]
425
    fn extreme_colors_pass_through() {
426
        for (r, g, b, a) in [(0, 0, 0, 0), (255, 255, 255, 255), (0, 255, 0, 1)] {
427
            let mut st = run("c", 1.0, None);
428
            st.color = ColorU { r, g, b, a };
429
            let mut m = ClipboardManager::new();
430
            m.set_copy_content(rich("c", vec![st]));
431

            
432
            let got = m.take_copy_content().unwrap();
433
            assert_eq!(got.styled_runs.as_slice()[0].color, ColorU { r, g, b, a });
434
        }
435
    }
436

            
437
    // =========================================================================
438
    // 4. take / clear semantics + slot isolation
439
    // =========================================================================
440

            
441
    #[test]
442
    fn take_copy_content_consumes_exactly_once() {
443
        let mut m = ClipboardManager::new();
444
        m.set_copy_content(plain("once"));
445
        assert!(m.has_copy_content());
446

            
447
        assert_eq!(
448
            m.take_copy_content().unwrap().plain_text.as_str(),
449
            "once",
450
            "first take must yield the content"
451
        );
452
        assert!(!m.has_copy_content(), "take must consume the slot");
453
        assert!(m.get_copy_content().is_none());
454
        assert!(
455
            m.take_copy_content().is_none(),
456
            "a second take must not resurrect the content"
457
        );
458
        assert!(m.take_copy_content().is_none());
459
    }
460

            
461
    #[test]
462
    fn take_on_fresh_manager_returns_none_repeatedly() {
463
        let mut m = ClipboardManager::new();
464
        for _ in 0..100 {
465
            assert!(m.take_copy_content().is_none());
466
        }
467
        assert!(!m.has_copy_content());
468
    }
469

            
470
    #[test]
471
    fn take_copy_does_not_disturb_paste_slot() {
472
        let mut m = ClipboardManager::new();
473
        m.set_paste_content(plain("paste"));
474
        m.set_copy_content(plain("copy"));
475

            
476
        let taken = m.take_copy_content().unwrap();
477
        assert_eq!(taken.plain_text.as_str(), "copy");
478
        assert!(m.has_paste_content(), "taking copy must not clear paste");
479
        assert_eq!(m.get_paste_content().unwrap().plain_text.as_str(), "paste");
480
    }
481

            
482
    #[test]
483
    fn set_overwrites_rather_than_accumulates() {
484
        let mut m = ClipboardManager::new();
485
        for i in 0..50 {
486
            m.set_paste_content(plain(&format!("paste-{i}")));
487
            m.set_copy_content(plain(&format!("copy-{i}")));
488
        }
489
        assert_eq!(
490
            m.get_paste_content().unwrap().plain_text.as_str(),
491
            "paste-49"
492
        );
493
        assert_eq!(m.get_copy_content().unwrap().plain_text.as_str(), "copy-49");
494

            
495
        // And the last write wins for take() too.
496
        assert_eq!(
497
            m.take_copy_content().unwrap().plain_text.as_str(),
498
            "copy-49"
499
        );
500
    }
501

            
502
    #[test]
503
    fn clear_empties_both_slots() {
504
        let mut m = ClipboardManager::new();
505
        m.set_paste_content(plain("p"));
506
        m.set_copy_content(plain("c"));
507
        m.clear();
508

            
509
        assert!(!m.has_paste_content());
510
        assert!(!m.has_copy_content());
511
        assert!(m.get_paste_content().is_none());
512
        assert!(m.get_copy_content().is_none());
513
        assert!(m.take_copy_content().is_none());
514
    }
515

            
516
    #[test]
517
    fn clear_paste_and_clear_copy_are_slot_isolated() {
518
        let mut m = ClipboardManager::new();
519
        m.set_paste_content(plain("p"));
520
        m.set_copy_content(plain("c"));
521

            
522
        m.clear_paste();
523
        assert!(!m.has_paste_content());
524
        assert!(
525
            m.has_copy_content(),
526
            "clear_paste must not touch the copy slot"
527
        );
528
        assert_eq!(m.get_copy_content().unwrap().plain_text.as_str(), "c");
529

            
530
        m.set_paste_content(plain("p2"));
531
        m.clear_copy();
532
        assert!(!m.has_copy_content());
533
        assert!(
534
            m.has_paste_content(),
535
            "clear_copy must not touch the paste slot"
536
        );
537
        assert_eq!(m.get_paste_content().unwrap().plain_text.as_str(), "p2");
538
    }
539

            
540
    #[test]
541
    fn clears_are_idempotent_on_an_empty_manager() {
542
        let mut m = ClipboardManager::new();
543
        for _ in 0..10 {
544
            m.clear();
545
            m.clear_paste();
546
            m.clear_copy();
547
        }
548
        assert!(!m.has_paste_content());
549
        assert!(!m.has_copy_content());
550

            
551
        // ...and idempotent after a real clear, too.
552
        m.set_paste_content(plain("x"));
553
        m.clear_paste();
554
        m.clear_paste();
555
        m.clear_paste();
556
        assert!(m.get_paste_content().is_none());
557
    }
558

            
559
    // =========================================================================
560
    // 5. Predicate / getter invariants
561
    // =========================================================================
562

            
563
    #[test]
564
    fn predicates_always_agree_with_getters() {
565
        let mut m = ClipboardManager::new();
566
        let check = |m: &ClipboardManager| {
567
            assert_eq!(m.has_paste_content(), m.get_paste_content().is_some());
568
            assert_eq!(m.has_copy_content(), m.get_copy_content().is_some());
569
        };
570

            
571
        check(&m);
572
        m.set_paste_content(plain(""));
573
        check(&m);
574
        m.set_copy_content(plain("\0"));
575
        check(&m);
576
        m.clear_paste();
577
        check(&m);
578
        let _ = m.take_copy_content();
579
        check(&m);
580
        m.clear();
581
        check(&m);
582
    }
583

            
584
    #[test]
585
    fn getters_are_stable_across_repeated_reads() {
586
        let mut m = ClipboardManager::new();
587
        m.set_paste_content(plain("stable"));
588

            
589
        for _ in 0..1_000 {
590
            assert_eq!(m.get_paste_content().unwrap().plain_text.as_str(), "stable");
591
            assert!(m.has_paste_content());
592
        }
593
    }
594

            
595
    // =========================================================================
596
    // 6. Ownership: deep clone, no aliasing, no use-after-free
597
    // =========================================================================
598

            
599
    #[test]
600
    fn clone_is_deep_and_independent() {
601
        let mut original = ClipboardManager::new();
602
        original.set_paste_content(plain("original-paste"));
603
        original.set_copy_content(plain("original-copy"));
604

            
605
        let mut cloned = original.clone();
606
        // Mutating the clone must not reach back into the original.
607
        cloned.set_paste_content(plain("clone-paste"));
608
        let _ = cloned.take_copy_content();
609

            
610
        assert_eq!(
611
            original.get_paste_content().unwrap().plain_text.as_str(),
612
            "original-paste"
613
        );
614
        assert!(
615
            original.has_copy_content(),
616
            "taking from the clone must not consume the original's copy slot"
617
        );
618
        assert_eq!(
619
            cloned.get_paste_content().unwrap().plain_text.as_str(),
620
            "clone-paste"
621
        );
622
        assert!(!cloned.has_copy_content());
623
    }
624

            
625
    #[test]
626
    fn clone_survives_the_original_being_dropped() {
627
        // `ClipboardContent` owns FFI vectors with destructor pointers: a
628
        // shallow clone here would alias the heap buffer and this test would
629
        // read freed memory / double-free on drop.
630
        let payload = "🦀".repeat(10_000);
631
        let cloned = {
632
            let mut original = ClipboardManager::new();
633
            original.set_paste_content(plain(&payload));
634
            original.set_copy_content(rich("rich", vec![run("r", 1.0, Some("Arial"))]));
635
            let c = original.clone();
636
            drop(original);
637
            c
638
        };
639

            
640
        assert_eq!(
641
            cloned.get_paste_content().unwrap().plain_text.as_str(),
642
            payload.as_str()
643
        );
644
        assert_eq!(
645
            cloned.get_copy_content().unwrap().styled_runs.as_slice()[0]
646
                .text
647
                .as_str(),
648
            "r"
649
        );
650
        // Dropping the clone afterwards must not double-free.
651
        drop(cloned);
652
    }
653

            
654
    #[test]
655
    fn taken_content_outlives_the_manager() {
656
        let taken = {
657
            let mut m = ClipboardManager::new();
658
            m.set_copy_content(plain("outlives"));
659
            let t = m.take_copy_content();
660
            drop(m);
661
            t
662
        };
663
        assert_eq!(taken.unwrap().plain_text.as_str(), "outlives");
664
    }
665

            
666
    #[test]
667
    fn dropping_a_loaded_manager_is_clean() {
668
        for _ in 0..100 {
669
            let mut m = ClipboardManager::new();
670
            m.set_paste_content(plain(&"x".repeat(4096)));
671
            m.set_copy_content(rich("c", vec![run("c", f32::NAN, Some("F"))]));
672
            // Dropped fully loaded, without any clear() — the destructors must
673
            // run exactly once each.
674
            drop(m);
675
        }
676
    }
677

            
678
    #[test]
679
    fn debug_format_does_not_panic_on_hostile_content() {
680
        let mut m = ClipboardManager::new();
681
        m.set_paste_content(plain("a\0b\u{202e}\u{feff}🦀"));
682
        m.set_copy_content(rich("r", vec![run("r", f32::NAN, None)]));
683

            
684
        let s = format!("{m:?}");
685
        assert!(s.contains("ClipboardManager"));
686
    }
687

            
688
    // =========================================================================
689
    // 7. Churn + model-based state machine
690
    // =========================================================================
691

            
692
    #[test]
693
    fn ten_thousand_set_take_cycles_leave_no_residue() {
694
        let mut m = ClipboardManager::new();
695
        for i in 0..10_000_u32 {
696
            m.set_copy_content(plain(&format!("c{i}")));
697
            m.set_paste_content(plain(&format!("p{i}")));
698

            
699
            let taken = m.take_copy_content().expect("copy slot was just filled");
700
            assert_eq!(taken.plain_text.as_str(), format!("c{i}"));
701
            assert!(!m.has_copy_content());
702
            m.clear_paste();
703
            assert!(!m.has_paste_content());
704
        }
705
        assert!(!m.has_paste_content());
706
        assert!(!m.has_copy_content());
707
    }
708

            
709
    #[test]
710
    fn state_machine_matches_a_two_slot_option_model() {
711
        // Drive every mutator in a deterministic pseudo-random order and check
712
        // the manager against a trivial `(Option<String>, Option<String>)`
713
        // model after every single step.
714
        let mut m = ClipboardManager::new();
715
        let mut model: (Option<String>, Option<String>) = (None, None);
716
        let mut seed: u64 = 0x5eed_1234_dead_beef;
717

            
718
        for step in 0..5_000_u32 {
719
            // xorshift64 — no rand dependency, fully reproducible.
720
            seed ^= seed << 13;
721
            seed ^= seed >> 7;
722
            seed ^= seed << 17;
723

            
724
            match seed % 7 {
725
                0 => {
726
                    let s = format!("p{step}");
727
                    m.set_paste_content(plain(&s));
728
                    model.0 = Some(s);
729
                }
730
                1 => {
731
                    let s = format!("c{step}");
732
                    m.set_copy_content(plain(&s));
733
                    model.1 = Some(s);
734
                }
735
                2 => {
736
                    let taken = m.take_copy_content();
737
                    let expected = model.1.take();
738
                    assert_eq!(
739
                        taken.map(|c| c.plain_text.as_str().to_string()),
740
                        expected,
741
                        "take_copy_content diverged from the model at step {step}"
742
                    );
743
                }
744
                3 => {
745
                    m.clear();
746
                    model = (None, None);
747
                }
748
                4 => {
749
                    m.clear_paste();
750
                    model.0 = None;
751
                }
752
                5 => {
753
                    m.clear_copy();
754
                    model.1 = None;
755
                }
756
                _ => {
757
                    // Pure reads must not mutate state.
758
                    let _ = m.get_paste_content();
759
                    let _ = m.get_copy_content();
760
                    let _ = m.has_paste_content();
761
                    let _ = m.has_copy_content();
762
                }
763
            }
764

            
765
            assert_eq!(
766
                m.get_paste_content()
767
                    .map(|c| c.plain_text.as_str().to_string()),
768
                model.0,
769
                "paste slot diverged at step {step}"
770
            );
771
            assert_eq!(
772
                m.get_copy_content()
773
                    .map(|c| c.plain_text.as_str().to_string()),
774
                model.1,
775
                "copy slot diverged at step {step}"
776
            );
777
            assert_eq!(m.has_paste_content(), model.0.is_some());
778
            assert_eq!(m.has_copy_content(), model.1.is_some());
779
        }
780
    }
781

            
782
    #[test]
783
    fn documented_paste_then_copy_flow() {
784
        // The module doc's contract: paste content is set by the platform,
785
        // read by the callback, then cleared; copy content is set by the
786
        // callback, taken by the platform, then gone.
787
        let mut m = ClipboardManager::new();
788

            
789
        // 1. Paste flow: system -> manager -> callback -> clear.
790
        m.set_paste_content(plain("from system"));
791
        assert_eq!(
792
            m.get_paste_content().unwrap().plain_text.as_str(),
793
            "from system"
794
        );
795
        m.clear_paste();
796
        assert!(!m.has_paste_content());
797

            
798
        // 2. Copy flow: callback overrides -> platform takes -> slot empties.
799
        m.set_copy_content(plain("default selection"));
800
        m.set_copy_content(plain("callback override"));
801
        assert_eq!(
802
            m.take_copy_content().unwrap().plain_text.as_str(),
803
            "callback override",
804
            "the callback's override must win over the default selection"
805
        );
806
        assert!(
807
            !m.has_copy_content(),
808
            "the copy slot must not leak into the next clipboard operation"
809
        );
810
    }
811
}