-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathbackend.rs
More file actions
816 lines (700 loc) · 30.5 KB
/
Copy pathbackend.rs
File metadata and controls
816 lines (700 loc) · 30.5 KB
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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
use std::fmt;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;
use ironrdp_cliprdr::backend::{ClipboardMessage, CliprdrBackend, CliprdrBackendFactory};
use ironrdp_cliprdr::pdu::{
ClipboardFormat, ClipboardFormatId, ClipboardGeneralCapabilityFlags, FileContentsRequest,
FileContentsResponse, FormatDataRequest, FormatDataResponse, LockDataId,
};
use ironrdp_core::impl_as_any;
use ironrdp_pdu::IntoOwned;
use ironrdp_server::{CliprdrServerFactory, ServerEvent, ServerEventSender};
use tokio::sync::mpsc;
use super::formats::{fix_bitfields_dib, utf16le_to_utf8, PendingWrite, MAX_CLIPBOARD_SIZE};
use super::wayland::clipboard_thread;
pub struct HyprCliprdrFactory {
event_sender: Option<mpsc::UnboundedSender<ServerEvent>>,
}
impl HyprCliprdrFactory {
pub fn new() -> Self {
Self { event_sender: None }
}
}
impl ServerEventSender for HyprCliprdrFactory {
fn set_sender(&mut self, sender: mpsc::UnboundedSender<ServerEvent>) {
self.event_sender = Some(sender);
}
}
impl CliprdrBackendFactory for HyprCliprdrFactory {
fn build_cliprdr_backend(&self) -> Box<dyn CliprdrBackend> {
let clipboard_data = Arc::new(Mutex::new(None::<Vec<u8>>));
let clipboard_image = Arc::new(Mutex::new(None::<Vec<u8>>));
let pending_write = Arc::new(Mutex::new(None::<PendingWrite>));
let suppress = Arc::new(AtomicBool::new(false));
let running = Arc::new(AtomicBool::new(true));
Box::new(HyprCliprdrBackend {
event_sender: self.event_sender.clone(),
remote_formats: Vec::new(),
watcher_thread: None,
suppress_watcher: suppress,
clipboard_data,
clipboard_image,
pending_write,
running,
last_requested_format: None,
})
}
}
impl CliprdrServerFactory for HyprCliprdrFactory {}
struct HyprCliprdrBackend {
event_sender: Option<mpsc::UnboundedSender<ServerEvent>>,
remote_formats: Vec<ClipboardFormat>,
watcher_thread: Option<thread::JoinHandle<()>>,
suppress_watcher: Arc<AtomicBool>,
clipboard_data: Arc<Mutex<Option<Vec<u8>>>>,
clipboard_image: Arc<Mutex<Option<Vec<u8>>>>, // CF_DIB bytes
pending_write: Arc<Mutex<Option<PendingWrite>>>,
running: Arc<AtomicBool>,
last_requested_format: Option<ClipboardFormatId>,
}
impl_as_any!(HyprCliprdrBackend);
impl fmt::Debug for HyprCliprdrBackend {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HyprCliprdrBackend")
.field("remote_formats", &self.remote_formats.len())
.field("watching", &self.watcher_thread.is_some())
.finish()
}
}
impl Drop for HyprCliprdrBackend {
fn drop(&mut self) {
self.running.store(false, Ordering::SeqCst);
if let Some(handle) = self.watcher_thread.take() {
let _ = handle.join();
}
}
}
impl CliprdrBackend for HyprCliprdrBackend {
fn temporary_directory(&self) -> &str {
"/tmp"
}
fn client_capabilities(&self) -> ClipboardGeneralCapabilityFlags {
ClipboardGeneralCapabilityFlags::USE_LONG_FORMAT_NAMES
}
fn on_ready(&mut self) {
tracing::info!("Clipboard channel ready");
self.start_clipboard_watcher();
}
fn on_request_format_list(&mut self) {
let mut formats = Vec::new();
let has_text = self
.clipboard_data
.lock()
.ok()
.and_then(|g| g.as_ref().map(|d| !d.is_empty()))
.unwrap_or(false);
if has_text {
formats.push(ClipboardFormat::new(ClipboardFormatId::CF_UNICODETEXT));
}
let has_image = self
.clipboard_image
.lock()
.ok()
.and_then(|g| g.as_ref().map(|d| !d.is_empty()))
.unwrap_or(false);
if has_image {
formats.push(ClipboardFormat::new(ClipboardFormatId::CF_DIB));
}
if !formats.is_empty() {
if let Some(ref sender) = self.event_sender {
let _ = sender.send(ServerEvent::Clipboard(ClipboardMessage::SendInitiateCopy(
formats,
)));
}
}
}
fn on_process_negotiated_capabilities(
&mut self,
_capabilities: ClipboardGeneralCapabilityFlags,
) {
}
fn on_remote_copy(&mut self, available_formats: &[ClipboardFormat]) {
tracing::trace!(
formats = available_formats.len(),
"Clipboard: remote clipboard updated"
);
self.remote_formats = available_formats.to_vec();
let has_unicode = available_formats
.iter()
.any(|f| f.id == ClipboardFormatId::CF_UNICODETEXT);
let has_dibv5 = available_formats
.iter()
.any(|f| f.id == ClipboardFormatId::CF_DIBV5);
let has_dib = available_formats
.iter()
.any(|f| f.id == ClipboardFormatId::CF_DIB);
// Prefer text over image; prefer CF_DIBV5 over CF_DIB (better BITFIELDS support)
let format = if has_unicode {
Some(ClipboardFormatId::CF_UNICODETEXT)
} else if has_dibv5 {
Some(ClipboardFormatId::CF_DIBV5)
} else if has_dib {
Some(ClipboardFormatId::CF_DIB)
} else {
None
};
self.last_requested_format = format;
if let Some(fmt) = format {
if let Some(ref sender) = self.event_sender {
let _ = sender.send(ServerEvent::Clipboard(ClipboardMessage::SendInitiatePaste(
fmt,
)));
}
}
}
fn on_format_data_request(&mut self, request: FormatDataRequest) {
let response = if request.format == ClipboardFormatId::CF_UNICODETEXT {
let data = self.clipboard_data.lock().ok().and_then(|g| g.clone());
match data {
Some(ref data) if !data.is_empty() => {
let text = String::from_utf8_lossy(data);
FormatDataResponse::new_unicode_string(&text).into_owned()
}
_ => FormatDataResponse::new_error().into_owned(),
}
} else if request.format == ClipboardFormatId::CF_DIB {
let data = self.clipboard_image.lock().ok().and_then(|g| g.clone());
match data {
Some(dib_data) if !dib_data.is_empty() => {
FormatDataResponse::new_data(dib_data).into_owned()
}
_ => FormatDataResponse::new_error().into_owned(),
}
} else {
FormatDataResponse::new_error().into_owned()
};
if let Some(ref sender) = self.event_sender {
let _ = sender.send(ServerEvent::Clipboard(ClipboardMessage::SendFormatData(
response,
)));
}
}
fn on_format_data_response(&mut self, response: FormatDataResponse<'_>) {
self.handle_format_data_response(response, MAX_CLIPBOARD_SIZE);
}
fn on_file_contents_request(&mut self, _request: FileContentsRequest) {}
fn on_file_contents_response(&mut self, _response: FileContentsResponse<'_>) {}
fn on_lock(&mut self, _data_id: LockDataId) {}
fn on_unlock(&mut self, _data_id: LockDataId) {}
}
impl HyprCliprdrBackend {
fn handle_format_data_response(
&mut self,
response: FormatDataResponse<'_>,
max_clipboard_size: usize,
) {
let requested_format = self.last_requested_format.take();
if response.is_error() {
return;
}
let data = response.data();
if data.is_empty() {
return;
}
if data.len() > max_clipboard_size {
tracing::warn!(
size = data.len(),
max = max_clipboard_size,
"Clipboard data too large, ignoring"
);
return;
}
match requested_format {
Some(ClipboardFormatId::CF_DIBV5) => {
if self.is_cached_image(data) {
tracing::debug!("Clipboard: client image echoes our own copy, ignoring");
return;
}
match ironrdp_cliprdr_format::bitmap::dibv5_to_png(data) {
Ok(png_data) => {
tracing::trace!(len = png_data.len(), "Clipboard: converted DIBV5 to PNG");
self.suppress_watcher.store(true, Ordering::SeqCst);
if let Ok(mut guard) = self.pending_write.lock() {
*guard = Some(PendingWrite::Image(png_data));
}
}
Err(e) => {
tracing::warn!("Clipboard: failed to convert DIBV5 to PNG: {}", e);
}
}
}
Some(ClipboardFormatId::CF_DIB) => {
if self.is_cached_image(data) {
tracing::debug!("Clipboard: client image echoes our own copy, ignoring");
return;
}
let png_result = ironrdp_cliprdr_format::bitmap::dib_to_png(data).or_else(|_| {
let fixed = fix_bitfields_dib(data).ok_or_else(|| {
ironrdp_cliprdr_format::bitmap::BitmapError::Unsupported(
"cannot fix BITFIELDS",
)
})?;
ironrdp_cliprdr_format::bitmap::dib_to_png(&fixed)
});
match png_result {
Ok(png_data) => {
tracing::trace!(len = png_data.len(), "Clipboard: converted DIB to PNG");
self.suppress_watcher.store(true, Ordering::SeqCst);
if let Ok(mut guard) = self.pending_write.lock() {
*guard = Some(PendingWrite::Image(png_data));
}
}
Err(e) => {
tracing::warn!("Clipboard: failed to convert DIB to PNG: {}", e);
}
}
}
Some(ClipboardFormatId::CF_UNICODETEXT) => {
let utf8 = utf16le_to_utf8(data);
if utf8.is_empty() {
return;
}
// Windows rewrites line endings to CRLF; normalize both for
// the echo check and for what Wayland applications paste.
let normalized = utf8.replace("\r\n", "\n");
if self.is_cached_text(&normalized) {
tracing::debug!("Clipboard: client text echoes our own copy, ignoring");
return;
}
tracing::trace!(
len = normalized.len(),
"Clipboard: received text from RDP client"
);
self.suppress_watcher.store(true, Ordering::SeqCst);
if let Ok(mut guard) = self.pending_write.lock() {
*guard = Some(PendingWrite::Text(normalized.into_bytes()));
}
}
Some(format) => {
tracing::trace!(?format, "Clipboard: ignoring unrequested response format");
}
None => {
tracing::trace!("Clipboard: ignoring format data response without pending request");
}
}
}
/// A client copy that matches our own announced clipboard is the client
/// echoing our copy back (e.g. a client-side clipboard manager rewriting
/// the clipboard after our format list). Taking the Wayland selection
/// over it would steal ownership from the application the user just
/// copied from and route every in-session paste through the RDP loop.
fn is_cached_text(&self, normalized: &str) -> bool {
self.clipboard_data
.lock()
.ok()
.and_then(|g| {
g.as_ref().map(|cached| {
String::from_utf8_lossy(cached).replace("\r\n", "\n") == normalized
})
})
.unwrap_or(false)
}
fn is_cached_image(&self, data: &[u8]) -> bool {
self.clipboard_image
.lock()
.ok()
.and_then(|g| g.as_ref().map(|cached| cached.as_slice() == data))
.unwrap_or(false)
}
fn start_clipboard_watcher(&mut self) {
let sender = match self.event_sender.clone() {
Some(s) => s,
None => return,
};
let suppress = Arc::clone(&self.suppress_watcher);
let clipboard_data = Arc::clone(&self.clipboard_data);
let clipboard_image = Arc::clone(&self.clipboard_image);
let pending_write = Arc::clone(&self.pending_write);
let running = Arc::clone(&self.running);
match thread::Builder::new()
.name("clipboard-watcher".into())
.spawn(move || {
if let Err(e) = clipboard_thread(
sender,
suppress,
clipboard_data,
clipboard_image,
pending_write,
running,
) {
tracing::error!("Clipboard thread error: {:#}", e);
}
}) {
Ok(handle) => {
self.watcher_thread = Some(handle);
tracing::info!("Clipboard: watching via wlr-data-control-v1");
}
Err(e) => {
tracing::error!("Clipboard: failed to spawn watcher thread: {}", e);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use proptest::prelude::*;
use std::io::Cursor;
const ONE_BY_ONE_RGBA_PNG: &[u8] = &[
0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, b'I', b'H', b'D',
b'R', 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f,
0x15, 0xc4, 0x89, 0x00, 0x00, 0x00, 0x0d, b'I', b'D', b'A', b'T', 0x78, 0x9c, 0x63, 0xf8,
0xcf, 0xc0, 0xf0, 0x1f, 0x00, 0x05, 0x00, 0x01, 0xff, 0x89, 0x99, 0x3d, 0x1d, 0x00, 0x00,
0x00, 0x00, b'I', b'E', b'N', b'D', 0xae, 0x42, 0x60, 0x82,
];
fn backend_with_events() -> (HyprCliprdrBackend, mpsc::UnboundedReceiver<ServerEvent>) {
let (event_tx, event_rx) = mpsc::unbounded_channel();
(
HyprCliprdrBackend {
event_sender: Some(event_tx),
remote_formats: Vec::new(),
watcher_thread: None,
suppress_watcher: Arc::new(AtomicBool::new(false)),
clipboard_data: Arc::new(Mutex::new(None)),
clipboard_image: Arc::new(Mutex::new(None)),
pending_write: Arc::new(Mutex::new(None)),
running: Arc::new(AtomicBool::new(true)),
last_requested_format: None,
},
event_rx,
)
}
fn utf16le(text: &str) -> Vec<u8> {
let mut bytes: Vec<u8> = text.encode_utf16().flat_map(u16::to_le_bytes).collect();
bytes.extend_from_slice(&[0, 0]);
bytes
}
#[test]
fn client_text_echo_of_our_copy_keeps_wayland_selection() {
let (mut backend, _rx) = backend_with_events();
*backend.clipboard_data.lock().unwrap() = Some(b"hello\nworld".to_vec());
backend.last_requested_format = Some(ClipboardFormatId::CF_UNICODETEXT);
let payload = utf16le("hello\r\nworld");
backend.handle_format_data_response(
FormatDataResponse::new_data(payload.as_slice()),
MAX_CLIPBOARD_SIZE,
);
assert!(backend.pending_write.lock().unwrap().is_none());
assert!(!backend.suppress_watcher.load(Ordering::SeqCst));
}
#[test]
fn client_text_copy_is_written_with_normalized_line_endings() {
let (mut backend, _rx) = backend_with_events();
backend.last_requested_format = Some(ClipboardFormatId::CF_UNICODETEXT);
let payload = utf16le("from\r\nclient");
backend.handle_format_data_response(
FormatDataResponse::new_data(payload.as_slice()),
MAX_CLIPBOARD_SIZE,
);
let pending = backend.pending_write.lock().unwrap();
let Some(PendingWrite::Text(text)) = pending.as_ref() else {
panic!("expected text pending write");
};
assert_eq!(text.as_slice(), b"from\nclient");
}
#[test]
fn client_image_echo_of_our_copy_keeps_wayland_selection() {
let (mut backend, _rx) = backend_with_events();
let dib = ironrdp_cliprdr_format::bitmap::png_to_cf_dib(ONE_BY_ONE_RGBA_PNG)
.expect("test PNG converts to DIB");
*backend.clipboard_image.lock().unwrap() = Some(dib.clone());
backend.last_requested_format = Some(ClipboardFormatId::CF_DIB);
backend.handle_format_data_response(
FormatDataResponse::new_data(dib.as_slice()),
MAX_CLIPBOARD_SIZE,
);
assert!(backend.pending_write.lock().unwrap().is_none());
assert!(!backend.suppress_watcher.load(Ordering::SeqCst));
}
fn recv_clipboard_event(
event_rx: &mut mpsc::UnboundedReceiver<ServerEvent>,
) -> ClipboardMessage {
match event_rx.try_recv().expect("clipboard event queued") {
ServerEvent::Clipboard(message) => message,
other => panic!("unexpected server event: {other:?}"),
}
}
fn decode_png(data: &[u8]) -> (u32, u32, png::ColorType, Vec<u8>) {
let decoder = png::Decoder::new(Cursor::new(data));
let mut reader = decoder.read_info().expect("PNG header decodes");
let mut buffer = vec![0; reader.output_buffer_size().expect("PNG output buffer size")];
let info = reader.next_frame(&mut buffer).expect("PNG frame decodes");
assert_eq!(info.bit_depth, png::BitDepth::Eight);
buffer.truncate(info.buffer_size());
(info.width, info.height, info.color_type, buffer)
}
fn rgba_png_pixel(pixel: [u8; 4]) -> Vec<u8> {
let mut png_data = Vec::new();
{
let mut encoder = png::Encoder::new(&mut png_data, 1, 1);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
let mut writer = encoder.write_header().expect("PNG header");
writer.write_image_data(&pixel).expect("PNG pixel");
}
png_data
}
fn assert_pending_image_pixel(
backend: &HyprCliprdrBackend,
color_type: png::ColorType,
pixel: &[u8],
) {
let pending = backend.pending_write.lock().unwrap();
let PendingWrite::Image(data) = pending.as_ref().expect("pending write") else {
panic!("expected image pending write");
};
let (width, height, actual_color_type, actual_pixel) = decode_png(data);
assert_eq!((width, height), (1, 1));
assert_eq!(actual_color_type, color_type);
assert_eq!(actual_pixel, pixel);
}
fn bitfields_dib_from_png() -> Vec<u8> {
let dib = ironrdp_cliprdr_format::bitmap::png_to_cf_dib(ONE_BY_ONE_RGBA_PNG)
.expect("test PNG converts to DIB");
let mut bitfields = Vec::with_capacity(dib.len() + 12);
bitfields.extend_from_slice(&dib[..16]);
bitfields.extend_from_slice(&3u32.to_le_bytes());
bitfields.extend_from_slice(&dib[20..40]);
bitfields.extend_from_slice(&0x00ff_0000u32.to_le_bytes());
bitfields.extend_from_slice(&0x0000_ff00u32.to_le_bytes());
bitfields.extend_from_slice(&0x0000_00ffu32.to_le_bytes());
bitfields.extend_from_slice(&dib[40..]);
bitfields
}
#[test]
fn request_format_list_advertises_text_and_image_formats() {
let (mut backend, mut event_rx) = backend_with_events();
*backend.clipboard_data.lock().unwrap() = Some(b"hello".to_vec());
*backend.clipboard_image.lock().unwrap() = Some(vec![1, 2, 3, 4]);
backend.on_request_format_list();
let ClipboardMessage::SendInitiateCopy(formats) = recv_clipboard_event(&mut event_rx)
else {
panic!("expected SendInitiateCopy");
};
let ids = formats.iter().map(|format| format.id).collect::<Vec<_>>();
assert_eq!(
ids,
vec![ClipboardFormatId::CF_UNICODETEXT, ClipboardFormatId::CF_DIB]
);
}
#[test]
fn request_format_list_does_not_emit_empty_clipboard() {
let (mut backend, mut event_rx) = backend_with_events();
backend.on_request_format_list();
assert!(event_rx.try_recv().is_err());
}
#[test]
fn remote_copy_prefers_unicode_then_dibv5_then_dib() {
for (formats, expected) in [
(
vec![
ClipboardFormat::new(ClipboardFormatId::CF_DIB),
ClipboardFormat::new(ClipboardFormatId::CF_DIBV5),
ClipboardFormat::new(ClipboardFormatId::CF_UNICODETEXT),
],
ClipboardFormatId::CF_UNICODETEXT,
),
(
vec![
ClipboardFormat::new(ClipboardFormatId::CF_DIB),
ClipboardFormat::new(ClipboardFormatId::CF_DIBV5),
],
ClipboardFormatId::CF_DIBV5,
),
(
vec![ClipboardFormat::new(ClipboardFormatId::CF_DIB)],
ClipboardFormatId::CF_DIB,
),
] {
let (mut backend, mut event_rx) = backend_with_events();
backend.on_remote_copy(&formats);
assert_eq!(backend.last_requested_format, Some(expected));
let ClipboardMessage::SendInitiatePaste(format) = recv_clipboard_event(&mut event_rx)
else {
panic!("expected SendInitiatePaste");
};
assert_eq!(format, expected);
}
}
#[test]
fn remote_copy_ignores_unsupported_formats() {
let (mut backend, mut event_rx) = backend_with_events();
let formats = [ClipboardFormat::new(ClipboardFormatId::CF_TEXT)];
backend.on_remote_copy(&formats);
assert_eq!(backend.remote_formats, formats);
assert_eq!(backend.last_requested_format, None);
assert!(event_rx.try_recv().is_err());
}
#[test]
fn remote_copy_clears_stale_requested_format_when_no_supported_format_exists() {
let (mut backend, mut event_rx) = backend_with_events();
backend.on_remote_copy(&[ClipboardFormat::new(ClipboardFormatId::CF_UNICODETEXT)]);
let ClipboardMessage::SendInitiatePaste(format) = recv_clipboard_event(&mut event_rx)
else {
panic!("expected SendInitiatePaste");
};
assert_eq!(format, ClipboardFormatId::CF_UNICODETEXT);
assert_eq!(
backend.last_requested_format,
Some(ClipboardFormatId::CF_UNICODETEXT)
);
backend.on_remote_copy(&[ClipboardFormat::new(ClipboardFormatId::CF_TEXT)]);
assert_eq!(backend.last_requested_format, None);
assert!(event_rx.try_recv().is_err());
}
#[test]
fn format_data_request_returns_unicode_text_response() {
let (mut backend, mut event_rx) = backend_with_events();
*backend.clipboard_data.lock().unwrap() = Some("hello".as_bytes().to_vec());
backend.on_format_data_request(FormatDataRequest {
format: ClipboardFormatId::CF_UNICODETEXT,
});
let ClipboardMessage::SendFormatData(response) = recv_clipboard_event(&mut event_rx) else {
panic!("expected SendFormatData");
};
assert!(!response.is_error());
assert_eq!(
response.data(),
&[b'h', 0, b'e', 0, b'l', 0, b'l', 0, b'o', 0, 0, 0]
);
}
#[test]
fn format_data_response_writes_text_pending_for_wayland() {
let (mut backend, _event_rx) = backend_with_events();
backend.last_requested_format = Some(ClipboardFormatId::CF_UNICODETEXT);
backend.on_format_data_response(FormatDataResponse::new_data(&[b'o', 0, b'k', 0, 0, 0]));
assert!(backend.suppress_watcher.load(Ordering::SeqCst));
let pending = backend.pending_write.lock().unwrap();
match pending.as_ref().expect("pending write") {
PendingWrite::Text(data) => assert_eq!(data, b"ok"),
PendingWrite::Image(_) => panic!("expected text pending write"),
}
}
#[test]
fn format_data_response_without_pending_request_is_ignored() {
let (mut backend, _event_rx) = backend_with_events();
backend.on_format_data_response(FormatDataResponse::new_data(&[b'o', 0, b'k', 0, 0, 0]));
assert!(!backend.suppress_watcher.load(Ordering::SeqCst));
assert!(backend.pending_write.lock().unwrap().is_none());
}
#[test]
fn late_format_data_response_after_unsupported_copy_is_ignored() {
let (mut backend, _event_rx) = backend_with_events();
backend.last_requested_format = Some(ClipboardFormatId::CF_UNICODETEXT);
backend.on_remote_copy(&[ClipboardFormat::new(ClipboardFormatId::CF_TEXT)]);
backend.on_format_data_response(FormatDataResponse::new_data(&[b'o', 0, b'k', 0, 0, 0]));
assert_eq!(backend.last_requested_format, None);
assert!(!backend.suppress_watcher.load(Ordering::SeqCst));
assert!(backend.pending_write.lock().unwrap().is_none());
}
#[test]
fn format_data_response_ignores_oversized_payload_without_mutating_pending_write() {
let (mut backend, _event_rx) = backend_with_events();
backend.last_requested_format = Some(ClipboardFormatId::CF_UNICODETEXT);
*backend.pending_write.lock().unwrap() = Some(PendingWrite::Text(b"old".to_vec()));
let oversized = [0, 0, 0, 0, 0];
backend.handle_format_data_response(FormatDataResponse::new_data(&oversized), 4);
assert!(!backend.suppress_watcher.load(Ordering::SeqCst));
assert_eq!(backend.last_requested_format, None);
let pending = backend.pending_write.lock().unwrap();
match pending.as_ref().expect("existing pending write remains") {
PendingWrite::Text(data) => assert_eq!(data, b"old"),
PendingWrite::Image(_) => panic!("expected existing text pending write"),
}
}
#[test]
fn format_data_response_writes_dib_image_pending_for_wayland() {
let (mut backend, _event_rx) = backend_with_events();
backend.last_requested_format = Some(ClipboardFormatId::CF_DIB);
let dib = ironrdp_cliprdr_format::bitmap::png_to_cf_dib(ONE_BY_ONE_RGBA_PNG)
.expect("test PNG converts to DIB");
backend.on_format_data_response(FormatDataResponse::new_data(&dib));
assert!(backend.suppress_watcher.load(Ordering::SeqCst));
assert_eq!(backend.last_requested_format, None);
assert_pending_image_pixel(&backend, png::ColorType::Rgb, &[255, 0, 0]);
}
#[test]
fn format_data_response_writes_dibv5_image_pending_for_wayland() {
let (mut backend, _event_rx) = backend_with_events();
backend.last_requested_format = Some(ClipboardFormatId::CF_DIBV5);
let dibv5 = ironrdp_cliprdr_format::bitmap::png_to_cf_dibv5(ONE_BY_ONE_RGBA_PNG)
.expect("test PNG converts to DIBV5");
backend.on_format_data_response(FormatDataResponse::new_data(&dibv5));
assert!(backend.suppress_watcher.load(Ordering::SeqCst));
assert_eq!(backend.last_requested_format, None);
assert_pending_image_pixel(&backend, png::ColorType::Rgba, &[255, 0, 0, 255]);
}
#[test]
fn format_data_response_preserves_dibv5_transparent_alpha_for_wayland() {
let (mut backend, _event_rx) = backend_with_events();
backend.last_requested_format = Some(ClipboardFormatId::CF_DIBV5);
let png = rgba_png_pixel([17, 34, 51, 127]);
let dibv5 =
ironrdp_cliprdr_format::bitmap::png_to_cf_dibv5(&png).expect("PNG converts to DIBV5");
backend.on_format_data_response(FormatDataResponse::new_data(&dibv5));
assert!(backend.suppress_watcher.load(Ordering::SeqCst));
assert_eq!(backend.last_requested_format, None);
assert_pending_image_pixel(&backend, png::ColorType::Rgba, &[17, 34, 51, 127]);
}
#[test]
fn format_data_response_writes_dib_alpha_as_rgb_for_wayland() {
let (mut backend, _event_rx) = backend_with_events();
backend.last_requested_format = Some(ClipboardFormatId::CF_DIB);
let png = rgba_png_pixel([17, 34, 51, 127]);
let dib = ironrdp_cliprdr_format::bitmap::png_to_cf_dib(&png).expect("PNG converts to DIB");
backend.on_format_data_response(FormatDataResponse::new_data(&dib));
assert!(backend.suppress_watcher.load(Ordering::SeqCst));
assert_eq!(backend.last_requested_format, None);
assert_pending_image_pixel(&backend, png::ColorType::Rgb, &[17, 34, 51]);
}
#[test]
fn format_data_response_repairs_bitfields_dib_before_png_conversion() {
let (mut backend, _event_rx) = backend_with_events();
backend.last_requested_format = Some(ClipboardFormatId::CF_DIB);
let dib = bitfields_dib_from_png();
backend.on_format_data_response(FormatDataResponse::new_data(&dib));
assert!(backend.suppress_watcher.load(Ordering::SeqCst));
assert_eq!(backend.last_requested_format, None);
assert_pending_image_pixel(&backend, png::ColorType::Rgb, &[255, 0, 0]);
}
#[test]
fn format_data_response_ignores_corrupt_dib_without_pending_write() {
let (mut backend, _event_rx) = backend_with_events();
backend.last_requested_format = Some(ClipboardFormatId::CF_DIB);
backend.on_format_data_response(FormatDataResponse::new_data(b"not a dib"));
assert!(!backend.suppress_watcher.load(Ordering::SeqCst));
assert_eq!(backend.last_requested_format, None);
assert!(backend.pending_write.lock().unwrap().is_none());
}
proptest! {
#[test]
fn generated_clipboard_image_responses_do_not_panic_or_write_invalid_png(
data in proptest::collection::vec(any::<u8>(), 0..256),
use_dibv5 in any::<bool>(),
) {
let (mut backend, _event_rx) = backend_with_events();
backend.last_requested_format = Some(if use_dibv5 {
ClipboardFormatId::CF_DIBV5
} else {
ClipboardFormatId::CF_DIB
});
backend.handle_format_data_response(FormatDataResponse::new_data(&data), 256);
if let Some(PendingWrite::Image(png_data)) = backend.pending_write.lock().unwrap().as_ref() {
let _ = decode_png(png_data);
prop_assert!(backend.suppress_watcher.load(Ordering::SeqCst));
}
prop_assert_eq!(backend.last_requested_format, None);
}
}
}