Repository navigation
Expand file tree
/
Copy pathpaste.rs
More file actions
1298 lines (1205 loc) · 44.8 KB
/
Copy pathpaste.rs
File metadata and controls
1298 lines (1205 loc) · 44.8 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
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::ffi::{c_char, c_void};
use std::fs;
use std::ops::RangeInclusive;
use std::path::Path;
use std::ptr;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
use std::time::Instant;
use color_eyre::eyre::{Result, eyre};
use objc2::rc::Retained;
use objc2::runtime::ProtocolObject;
use objc2_app_kit::{NSPasteboard, NSPasteboardItem, NSPasteboardTypeString, NSPasteboardWriting};
use objc2_foundation::{NSArray, NSData, NSString};
use crate::keyboard;
use crate::suppression::InputActivity;
pub struct Paster {
clipboard: Retained<NSPasteboard>,
activity: InputActivity,
continuation: Option<Continuation>,
clipboard_restore: Arc<Mutex<ClipboardRestore>>,
prepared_clipboard: Option<PreparedClipboard>,
}
#[derive(Clone, Copy)]
pub enum PasteMode {
Continue,
Standalone,
/// Labs › Copy dictation only: the text goes to the clipboard as an
/// ordinary entry and nothing is pasted, typed, or restored.
CopyOnly,
}
struct PreparedClipboard {
change_count: isize,
snapshot: ClipboardSnapshot,
capture_ms: u128,
}
struct Continuation {
revision: u64,
inserted: String,
}
#[derive(Default)]
struct ClipboardRestore {
generation: u64,
original: Option<ClipboardSnapshot>,
last_change_count: Option<isize>,
}
impl ClipboardRestore {
fn register(
&mut self,
previous: ClipboardSnapshot,
previous_change_count: isize,
inserted_change_count: isize,
) -> u64 {
self.generation = self.generation.wrapping_add(1);
if self.last_change_count != Some(previous_change_count) {
self.original = Some(previous);
}
self.last_change_count = Some(inserted_change_count);
self.generation
}
/// Labs › Keep dictation on clipboard: the paste stays on the clipboard,
/// so no earlier snapshot may come back and any pending restore stands
/// down.
fn keep(&mut self) {
self.generation = self.generation.wrapping_add(1);
self.original = None;
self.last_change_count = None;
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct ClipboardSnapshot {
items: Vec<Vec<ClipboardFlavor>>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct ClipboardFlavor {
data_type: String,
data: Vec<u8>,
flags: u32,
}
type PasteboardRef = *const c_void;
type PasteboardItemId = *mut c_void;
type CfTypeRef = *const c_void;
type CfStringRef = *const c_void;
type CfArrayRef = *const c_void;
type CfDataRef = *const c_void;
const CF_STRING_ENCODING_UTF8: u32 = 0x0800_0100;
const BAD_PASTEBOARD_FLAVOR: i32 = -25133;
const DUPLICATE_PASTEBOARD_FLAVOR: i32 = -25134;
const PASTE_SETTLE_DELAY: Duration = Duration::from_millis(100);
// Chromium 155 and 156 on macOS can drop a ⌘V that races its own pasteboard
// change notification, however long Hex waits first (#136, #212). The bug
// arrived with Chromium CL 8217390 and is fixed by CL 8503629 in 157.
const CLIPBOARD_RACE_CHROMIUM: RangeInclusive<u32> = 155..=156;
const SYSTEM_TRANSLATED_FLAVOR: u32 = 1 << 8;
#[link(name = "ApplicationServices", kind = "framework")]
unsafe extern "C" {
fn PasteboardCreate(name: CfStringRef, pasteboard: *mut PasteboardRef) -> i32;
fn PasteboardSynchronize(pasteboard: PasteboardRef) -> u32;
fn PasteboardClear(pasteboard: PasteboardRef) -> i32;
fn PasteboardGetItemCount(pasteboard: PasteboardRef, count: *mut usize) -> i32;
fn PasteboardGetItemIdentifier(
pasteboard: PasteboardRef,
index: isize,
item: *mut PasteboardItemId,
) -> i32;
fn PasteboardCopyItemFlavors(
pasteboard: PasteboardRef,
item: PasteboardItemId,
flavors: *mut CfArrayRef,
) -> i32;
fn PasteboardGetItemFlavorFlags(
pasteboard: PasteboardRef,
item: PasteboardItemId,
flavor: CfStringRef,
flags: *mut u32,
) -> i32;
fn PasteboardCopyItemFlavorData(
pasteboard: PasteboardRef,
item: PasteboardItemId,
flavor: CfStringRef,
data: *mut CfDataRef,
) -> i32;
fn PasteboardPutItemFlavor(
pasteboard: PasteboardRef,
item: PasteboardItemId,
flavor: CfStringRef,
data: CfDataRef,
flags: u32,
) -> i32;
}
#[link(name = "CoreFoundation", kind = "framework")]
unsafe extern "C" {
fn CFArrayGetCount(array: CfArrayRef) -> isize;
fn CFArrayGetValueAtIndex(array: CfArrayRef, index: isize) -> *const c_void;
fn CFDataCreate(allocator: *const c_void, bytes: *const u8, length: isize) -> CfDataRef;
fn CFDataGetBytePtr(data: CfDataRef) -> *const u8;
fn CFDataGetLength(data: CfDataRef) -> isize;
fn CFStringGetLength(value: CfStringRef) -> isize;
fn CFStringGetMaximumSizeForEncoding(length: isize, encoding: u32) -> isize;
fn CFStringGetCString(
value: CfStringRef,
buffer: *mut c_char,
buffer_size: isize,
encoding: u32,
) -> bool;
fn CFStringCreateWithBytes(
allocator: *const c_void,
bytes: *const u8,
length: isize,
encoding: u32,
is_external_representation: u8,
) -> CfStringRef;
fn CFRelease(value: CfTypeRef);
}
struct PasteboardHandle(PasteboardRef);
impl Drop for PasteboardHandle {
fn drop(&mut self) {
unsafe { CFRelease(self.0) };
}
}
impl Paster {
pub fn new(activity: InputActivity) -> Self {
Self {
clipboard: NSPasteboard::generalPasteboard(),
activity,
continuation: None,
clipboard_restore: Arc::new(Mutex::new(ClipboardRestore::default())),
prepared_clipboard: None,
}
}
pub fn prepare(&mut self) {
let change_count = self.clipboard.changeCount();
if self
.prepared_clipboard
.as_ref()
.is_some_and(|prepared| prepared.change_count == change_count)
{
return;
}
self.prepared_clipboard = None;
let _restore = self
.clipboard_restore
.lock()
.unwrap_or_else(|error| error.into_inner());
let started = Instant::now();
match capture_clipboard(&self.clipboard) {
Ok(snapshot) => {
self.prepared_clipboard = Some(PreparedClipboard {
change_count,
snapshot,
capture_ms: started.elapsed().as_millis(),
});
}
Err(error) => tracing::debug!(%error, "eager clipboard capture failed"),
}
}
/// Commit only after clipboard preparation, immediately before the first write.
/// A rejected commit leaves both the clipboard and continuation unchanged.
pub fn paste(
&mut self,
text: &str,
mode: PasteMode,
commit: impl FnOnce() -> bool,
) -> Result<()> {
self.paste_text(text, mode, commit)
}
fn paste_text(
&mut self,
text: &str,
mode: PasteMode,
commit: impl FnOnce() -> bool,
) -> Result<()> {
if matches!(mode, PasteMode::CopyOnly) {
return self.copy_only(text, commit);
}
let revision = self.activity.revision();
let text = self
.continuation
.as_ref()
.filter(|continuation| {
!matches!(mode, PasteMode::Standalone) && continuation.revision == revision
})
.map_or_else(
|| text.to_string(),
|continuation| join(&continuation.inserted, text),
);
if crate::context::frontmost_bundle_path().is_some_and(|bundle| has_clipboard_race(&bundle))
{
commit_prepared_paste(
|| Ok(()),
commit,
|()| {
if matches!(mode, PasteMode::Standalone) {
self.continuation = None;
}
tracing::debug!("typing instead of pasting into Chromium 155 or 156");
keyboard::type_text(&text)?;
if crate::labs::keep_on_clipboard() {
self.clipboard_restore
.lock()
.unwrap_or_else(|error| error.into_inner())
.keep();
if let Err(error) = write_clipboard_text(&self.clipboard, &text, false) {
tracing::warn!(%error, "could not leave the dictation on the clipboard");
}
}
Ok(())
},
)?;
} else {
self.paste_through_clipboard(&text, mode, commit)?;
}
self.continuation = (!matches!(mode, PasteMode::Standalone)).then_some(Continuation {
revision,
inserted: text,
});
Ok(())
}
/// Leaves `text` on the clipboard for the user to paste: no ⌘V, no typed
/// text, and no restore. A pending restore stands down and no earlier
/// snapshot comes back, and the next paste starts a new continuation.
fn copy_only(&mut self, text: &str, commit: impl FnOnce() -> bool) -> Result<()> {
commit_prepared_paste(
|| Ok(()),
commit,
|()| {
self.continuation = None;
self.prepared_clipboard = None;
self.clipboard_restore
.lock()
.unwrap_or_else(|error| error.into_inner())
.keep();
write_clipboard_text(&self.clipboard, text, false)
},
)
}
fn paste_through_clipboard(
&mut self,
text: &str,
mode: PasteMode,
commit: impl FnOnce() -> bool,
) -> Result<()> {
let generation = commit_prepared_paste(
|| {
let restore = self
.clipboard_restore
.lock()
.unwrap_or_else(|error| error.into_inner());
let previous_change_count = self.clipboard.changeCount();
let prepared = self.prepared_clipboard.take();
let previous = if let Some(prepared) = prepared
&& prepared.change_count == previous_change_count
{
tracing::debug!(
clipboard_capture_ms = prepared.capture_ms,
"used eagerly captured clipboard"
);
prepared.snapshot
} else {
let started = Instant::now();
let snapshot = capture_clipboard(&self.clipboard)?;
tracing::debug!(
clipboard_capture_ms = started.elapsed().as_millis(),
"captured clipboard at paste time"
);
snapshot
};
if self.clipboard.changeCount() != previous_change_count {
return Err(eyre!("clipboard changed while Hex was preserving it"));
}
Ok((restore, previous, previous_change_count))
},
commit,
|(mut restore, previous, previous_change_count)| {
if matches!(mode, PasteMode::Standalone) {
self.continuation = None;
}
// Read as the paste commits, so the toggle applies at once.
let keep = crate::labs::keep_on_clipboard();
if let Err(error) = write_clipboard_text(&self.clipboard, text, !keep) {
if let Err(restore_error) = restore_clipboard(&self.clipboard, &previous) {
tracing::error!(%restore_error, "could not recover the clipboard after a failed write");
}
return Err(error);
}
if keep {
restore.keep();
return Ok(None);
}
let inserted_change_count = self.clipboard.changeCount();
Ok(Some(restore.register(
previous,
previous_change_count,
inserted_change_count,
)))
},
)?;
let clipboard_restore = self.clipboard_restore.clone();
complete_paste(
|| keyboard::post_command('v'),
move || {
let Some(generation) = generation else {
return;
};
thread::spawn(move || {
thread::sleep(Duration::from_millis(500));
let mut restore = clipboard_restore
.lock()
.unwrap_or_else(|error| error.into_inner());
if restore.generation != generation {
return;
}
let clipboard = NSPasteboard::generalPasteboard();
if restore.last_change_count != Some(clipboard.changeCount()) {
restore.original = None;
restore.last_change_count = None;
return;
}
let Some(previous) = restore.original.take() else {
return;
};
let result = restore_clipboard(&clipboard, &previous);
restore.last_change_count = None;
if let Err(error) = result {
tracing::warn!(%error, "could not restore clipboard after paste");
}
});
},
thread::sleep,
)
}
}
pub(crate) fn commit_prepared_paste<P, T>(
prepare: impl FnOnce() -> Result<P>,
commit: impl FnOnce() -> bool,
paste: impl FnOnce(P) -> Result<T>,
) -> Result<T> {
let prepared = prepare()?;
// Waiting for restoration and materializing promised clipboard data remain cancellable.
// Once committed, even a failed first write may have changed the clipboard.
if !commit() {
return Err(eyre!("paste was cancelled"));
}
paste(prepared)
}
/// Whether the app at `bundle` embeds a Chromium 155 or 156 framework. Every
/// version found counts, so a browser that has staged an update before
/// relaunching is covered whichever version is running; typing works in any
/// version, so the wrong guess there costs nothing.
fn has_clipboard_race(bundle: &Path) -> bool {
chromium_major_versions(bundle).any(|major| CLIPBOARD_RACE_CHROMIUM.contains(&major))
}
/// Chromium browsers (Chrome, Helium, Brave, Edge, Chromium itself and
/// most forks) ship `Contents/Frameworks/<Name> Framework.framework/Versions/
/// <major>.<minor>.<build>.<patch>/`. Electron's `Versions/A` has no version.
fn chromium_major_versions(bundle: &Path) -> impl Iterator<Item = u32> {
fs::read_dir(bundle.join("Contents/Frameworks"))
.into_iter()
.flatten()
.flatten()
.filter(|framework| {
framework
.file_name()
.to_str()
.is_some_and(|name| name.ends_with("Framework.framework"))
})
.flat_map(|framework| fs::read_dir(framework.path().join("Versions")).into_iter())
.flatten()
.flatten()
.filter_map(|version| chromium_major_version(version.file_name().to_str()?))
}
fn chromium_major_version(version: &str) -> Option<u32> {
let components = version
.split('.')
.map(str::parse::<u32>)
.collect::<Result<Vec<_>, _>>()
.ok()?;
match components[..] {
[major, _, _, _] => Some(major),
_ => None,
}
}
fn complete_paste(
post_paste: impl FnOnce() -> Result<()>,
schedule_restore: impl FnOnce(),
mut wait: impl FnMut(Duration),
) -> Result<()> {
let posted = post_paste();
schedule_restore();
posted?;
// Keep the clipboard stable for the target's 100 ms consumption window.
// This is not an acknowledgment; longer OS or application stalls can still lose a paste.
wait(PASTE_SETTLE_DELAY);
Ok(())
}
fn capture_clipboard(clipboard: &NSPasteboard) -> Result<ClipboardSnapshot> {
let capture_started = Instant::now();
let pasteboard = create_pasteboard(&clipboard.name())?;
unsafe { PasteboardSynchronize(pasteboard.0) };
let mut item_count = 0;
check_status(
unsafe { PasteboardGetItemCount(pasteboard.0, &mut item_count) },
"count clipboard items",
)?;
let mut items = Vec::with_capacity(item_count);
for index in 1..=item_count {
let mut item = ptr::null_mut();
check_status(
unsafe { PasteboardGetItemIdentifier(pasteboard.0, index as isize, &mut item) },
"identify a clipboard item",
)?;
let mut flavors = ptr::null();
check_status(
unsafe { PasteboardCopyItemFlavors(pasteboard.0, item, &mut flavors) },
"list clipboard formats",
)?;
if flavors.is_null() {
return Err(eyre!("could not list clipboard formats"));
}
let flavor_count = unsafe { CFArrayGetCount(flavors) };
let result = (0..flavor_count)
.map(|flavor_index| {
let flavor = unsafe { CFArrayGetValueAtIndex(flavors, flavor_index) };
if flavor.is_null() {
return Err(eyre!("clipboard format was unavailable"));
}
let mut flags = 0;
check_status(
unsafe { PasteboardGetItemFlavorFlags(pasteboard.0, item, flavor, &mut flags) },
"inspect clipboard format",
)?;
Ok((flavor, flags))
})
.collect::<Result<Vec<_>>>()
.and_then(|flavor_entries| {
let has_authoritative_flavor = flavor_entries
.iter()
.any(|&(_, flags)| flags & SYSTEM_TRANSLATED_FLAVOR == 0);
flavor_entries
.into_iter()
.map(|(flavor, flags)| {
let data_type = cf_string(flavor)?;
if !should_preserve_flavor(flags, has_authoritative_flavor) {
tracing::debug!(%data_type, "skipping synthesized clipboard format");
return Ok(None);
}
let mut data = ptr::null();
let flavor_started = Instant::now();
let status = unsafe {
PasteboardCopyItemFlavorData(pasteboard.0, item, flavor, &mut data)
};
let flavor_ms = flavor_started.elapsed().as_millis();
if flavor_ms >= 100 {
tracing::warn!(
%data_type,
flavor_ms,
"clipboard format was slow to materialize"
);
}
if status == BAD_PASTEBOARD_FLAVOR {
tracing::debug!(%data_type, "skipping unavailable clipboard format");
return Ok(None);
}
check_status(status, "preserve clipboard format")?;
if data.is_null() {
return Err(eyre!("clipboard format data was unavailable"));
}
let bytes = cf_data(data);
unsafe { CFRelease(data) };
Ok(Some(ClipboardFlavor {
data_type,
data: bytes?,
flags: flags & 0x0f,
}))
})
.collect::<Result<Vec<_>>>()
});
unsafe { CFRelease(flavors) };
items.push(result?.into_iter().flatten().collect());
}
let capture_ms = capture_started.elapsed().as_millis();
if capture_ms >= 100 {
tracing::warn!(capture_ms, item_count, "clipboard snapshot was slow");
}
Ok(ClipboardSnapshot { items })
}
fn should_preserve_flavor(flags: u32, has_authoritative_flavor: bool) -> bool {
!has_authoritative_flavor || flags & SYSTEM_TRANSLATED_FLAVOR == 0
}
/// nspasteboard.org markers asking clipboard managers not to record a write.
/// The transcript is only on the clipboard for the duration of the paste,
/// unless Labs › Keep dictation on clipboard leaves it there (`transient`
/// false), when it is an ordinary clipboard entry.
const CLIPBOARD_MANAGER_MARKERS: [&str; 2] = [
"org.nspasteboard.TransientType",
"org.nspasteboard.AutoGeneratedType",
];
fn write_clipboard_text(clipboard: &NSPasteboard, text: &str, transient: bool) -> Result<()> {
// One item carrying the text and its markers, published by a single write,
// so a polling clipboard manager never observes the text without them.
let item = NSPasteboardItem::new();
let marker_data = NSData::new();
let markers_written = !transient
|| CLIPBOARD_MANAGER_MARKERS
.iter()
.all(|marker| item.setData_forType(&marker_data, &NSString::from_str(marker)));
let text_written =
item.setString_forType(&NSString::from_str(text), unsafe { NSPasteboardTypeString });
if !(markers_written && text_written) {
return Err(eyre!("could not prepare the transcript for the clipboard"));
}
clipboard.clearContents();
write_items(clipboard, &[item])
}
fn restore_clipboard(clipboard: &NSPasteboard, snapshot: &ClipboardSnapshot) -> Result<()> {
let pasteboard = create_pasteboard(&clipboard.name())?;
unsafe { PasteboardSynchronize(pasteboard.0) };
check_status(
unsafe { PasteboardClear(pasteboard.0) },
"clear the clipboard",
)?;
for (item_index, item) in snapshot.items.iter().enumerate() {
let item_id = (item_index + 1) as PasteboardItemId;
for flavor in item {
let data_type = cf_string_create(&flavor.data_type)?;
let data = unsafe {
CFDataCreate(
ptr::null(),
flavor.data.as_ptr(),
flavor.data.len() as isize,
)
};
if data.is_null() {
unsafe { CFRelease(data_type) };
return Err(eyre!("could not encode a clipboard format"));
}
let status = unsafe {
PasteboardPutItemFlavor(pasteboard.0, item_id, data_type, data, flavor.flags)
};
unsafe {
CFRelease(data);
CFRelease(data_type);
}
if status == DUPLICATE_PASTEBOARD_FLAVOR {
tracing::debug!(data_type = %flavor.data_type, "skipping synthesized clipboard format");
continue;
}
check_status(status, "restore clipboard format")?;
}
}
Ok(())
}
fn write_items(clipboard: &NSPasteboard, items: &[Retained<NSPasteboardItem>]) -> Result<()> {
let objects = items
.iter()
.map(|item| ProtocolObject::from_ref(&**item))
.collect::<Vec<&ProtocolObject<dyn NSPasteboardWriting>>>();
let objects = NSArray::from_slice(&objects);
clipboard
.writeObjects(&objects)
.then_some(())
.ok_or_else(|| eyre!("could not write the clipboard"))
}
fn create_pasteboard(name: &NSString) -> Result<PasteboardHandle> {
let mut pasteboard = ptr::null();
check_status(
unsafe { PasteboardCreate((name as *const NSString).cast(), &mut pasteboard) },
"open the clipboard",
)?;
(!pasteboard.is_null())
.then_some(PasteboardHandle(pasteboard))
.ok_or_else(|| eyre!("could not open the clipboard"))
}
fn check_status(status: i32, action: &str) -> Result<()> {
(status == 0)
.then_some(())
.ok_or_else(|| eyre!("could not {action} (status {status})"))
}
fn cf_string_create(value: &str) -> Result<CfStringRef> {
let value = unsafe {
CFStringCreateWithBytes(
ptr::null(),
value.as_ptr(),
value.len() as isize,
CF_STRING_ENCODING_UTF8,
0,
)
};
(!value.is_null())
.then_some(value)
.ok_or_else(|| eyre!("could not encode a clipboard format name"))
}
fn cf_string(value: CfStringRef) -> Result<String> {
let length = unsafe { CFStringGetLength(value) };
let capacity = unsafe { CFStringGetMaximumSizeForEncoding(length, CF_STRING_ENCODING_UTF8) }
.saturating_add(1);
let mut bytes = vec![0; capacity as usize];
if !unsafe {
CFStringGetCString(
value,
bytes.as_mut_ptr().cast(),
capacity,
CF_STRING_ENCODING_UTF8,
)
} {
return Err(eyre!("could not decode a clipboard format name"));
}
let length = bytes
.iter()
.position(|byte| *byte == 0)
.unwrap_or(bytes.len());
bytes.truncate(length);
String::from_utf8(bytes).map_err(Into::into)
}
fn cf_data(value: CfDataRef) -> Result<Vec<u8>> {
let length = unsafe { CFDataGetLength(value) };
if length < 0 {
return Err(eyre!("clipboard format had an invalid length"));
}
if length == 0 {
return Ok(Vec::new());
}
let bytes = unsafe { CFDataGetBytePtr(value) };
if bytes.is_null() {
return Err(eyre!("clipboard format data was unavailable"));
}
Ok(unsafe { std::slice::from_raw_parts(bytes, length as usize) }.to_vec())
}
fn join(previous: &str, next: &str) -> String {
let sentence_start = ends_sentence(previous);
let mut next = set_initial_case(next, sentence_start);
let needs_space = previous
.chars()
.next_back()
.is_some_and(|character| !character.is_whitespace() && !is_opening(character))
&& next
.chars()
.next()
.is_some_and(|character| !character.is_whitespace() && !is_closing(character));
if needs_space {
next.insert(0, ' ');
}
next
}
fn ends_sentence(text: &str) -> bool {
text.trim_end()
.trim_end_matches(['\'', '"', ')', ']', '}'])
.ends_with(['.', '?', '!'])
}
fn is_opening(character: char) -> bool {
matches!(character, '(' | '[' | '{')
}
fn is_closing(character: char) -> bool {
matches!(
character,
',' | '.' | '?' | '!' | ';' | ':' | ')' | ']' | '}'
)
}
fn set_initial_case(text: &str, uppercase: bool) -> String {
let Some((index, character)) = text
.char_indices()
.find(|(_, character)| character.is_alphabetic())
else {
return text.to_string();
};
if uppercase && character.is_lowercase() {
return replace_character(text, index, character.to_uppercase());
}
if !uppercase && character.is_uppercase() && sentence_initial_word(text, index) {
return replace_character(text, index, character.to_lowercase());
}
text.to_string()
}
fn sentence_initial_word(text: &str, start: usize) -> bool {
let word = text[start..]
.split(|character: char| !character.is_alphabetic() && character != '\'')
.next()
.unwrap_or_default();
matches!(
word.to_ascii_lowercase().as_str(),
"a" | "an"
| "and"
| "as"
| "because"
| "but"
| "for"
| "if"
| "nor"
| "or"
| "so"
| "the"
| "then"
| "though"
| "to"
| "when"
| "while"
| "yet"
)
}
fn replace_character(text: &str, index: usize, replacement: impl Iterator<Item = char>) -> String {
let character_length = text[index..].chars().next().unwrap().len_utf8();
let mut output = String::with_capacity(text.len());
output.push_str(&text[..index]);
output.extend(replacement);
output.push_str(&text[index + character_length..]);
output
}
#[cfg(test)]
mod tests {
use std::cell::{Cell, RefCell};
use super::*;
static PASTEBOARD_TEST: Mutex<()> = Mutex::new(());
#[test]
fn rejected_commit_does_not_write_paste_or_restore() {
let steps = RefCell::new(Vec::new());
let result = commit_prepared_paste(
|| {
steps.borrow_mut().push("prepare");
Ok(())
},
|| {
steps.borrow_mut().push("commit");
false
},
|()| {
steps.borrow_mut().push("write");
complete_paste(
|| {
steps.borrow_mut().push("post");
Ok(())
},
|| steps.borrow_mut().push("restore"),
|_| steps.borrow_mut().push("settle"),
)
},
);
assert_eq!(result.unwrap_err().to_string(), "paste was cancelled");
assert_eq!(steps.into_inner(), ["prepare", "commit"]);
}
#[test]
fn failed_preparation_does_not_commit_or_write() {
let result = commit_prepared_paste(
|| Err::<(), _>(eyre!("snapshot failed")),
|| panic!("failed preparation must remain cancellable"),
|()| -> Result<()> { panic!("failed preparation must not mutate the clipboard") },
);
assert_eq!(result.unwrap_err().to_string(), "snapshot failed");
}
#[test]
fn sequential_pastes_settle_before_overwrite() {
let clipboard = Cell::new("");
let pending = Cell::new(false);
let consumed = RefCell::new(Vec::new());
let steps = RefCell::new(Vec::new());
let paste = |text| {
clipboard.set(text);
complete_paste(
|| {
pending.set(true);
steps.borrow_mut().push("post");
Ok(())
},
|| steps.borrow_mut().push("restore"),
|delay| {
assert_eq!(delay, PASTE_SETTLE_DELAY);
assert!(pending.replace(false));
consumed.borrow_mut().push(clipboard.get());
steps.borrow_mut().push("settle");
},
)
};
paste("first").unwrap();
assert_eq!(*consumed.borrow(), ["first"]);
paste("second").unwrap();
assert_eq!(*consumed.borrow(), ["first", "second"]);
assert_eq!(
steps.into_inner(),
["post", "restore", "settle", "post", "restore", "settle"]
);
}
#[test]
fn restoration_is_scheduled_after_a_stalled_post_completes() {
let elapsed = Cell::new(Duration::ZERO);
let restore_scheduled_at = Cell::new(None);
complete_paste(
|| {
elapsed.set(Duration::from_secs(1));
assert_eq!(restore_scheduled_at.get(), None);
Ok(())
},
|| restore_scheduled_at.set(Some(elapsed.get())),
|delay| elapsed.set(elapsed.get() + delay),
)
.unwrap();
assert_eq!(restore_scheduled_at.get(), Some(Duration::from_secs(1)));
assert_eq!(elapsed.get(), Duration::from_secs(1) + PASTE_SETTLE_DELAY);
}
#[test]
fn failed_paste_still_schedules_restore_without_settling() {
let steps = RefCell::new(Vec::new());
let result = complete_paste(
|| {
steps.borrow_mut().push("post");
Err(eyre!("post failed"))
},
|| steps.borrow_mut().push("restore"),
|_| steps.borrow_mut().push("settle"),
);
assert_eq!(result.unwrap_err().to_string(), "post failed");
assert_eq!(steps.into_inner(), ["post", "restore"]);
}
#[test]
fn detects_the_chromium_major_version_from_the_bundle_framework() {
let root = std::env::temp_dir().join(format!("hex-chromium-{}", std::process::id()));
let bundle = |name: &str, frameworks: &[(&str, &[&str])]| {
let bundle = root.join(name);
for (framework, versions) in frameworks {
for version in *versions {
fs::create_dir_all(
bundle
.join("Contents/Frameworks")
.join(framework)
.join("Versions")
.join(version),
)
.unwrap();
}
}
fs::create_dir_all(bundle.join("Contents")).unwrap();
bundle
};
let chrome = bundle(
"Google Chrome.app",
&[("Google Chrome Framework.framework", &["155.0.8059.40"])],
);
let helium = bundle(
"Helium.app",
&[("Helium Framework.framework", &["156.0.8078.48"])],
);
let staged = bundle(
"Brave Browser.app",
&[(
"Brave Browser Framework.framework",
&["156.1.88.10", "157.1.89.2"],
)],
);
let fixed = bundle(
"Microsoft Edge.app",
&[("Microsoft Edge Framework.framework", &["157.0.8103.15"])],
);
let older = bundle(
"Chromium.app",
&[("Chromium Framework.framework", &["154.0.7999.1"])],
);
let electron = bundle(
"Slack.app",
&[
("Electron Framework.framework", &["A", "Current"]),
("Squirrel.framework", &["155.0.0.0"]),
],
);
let safari = bundle("Safari.app", &[]);
assert_eq!(chromium_major_versions(&chrome).collect::<Vec<_>>(), [155]);
let mut staged_versions = chromium_major_versions(&staged).collect::<Vec<_>>();
staged_versions.sort_unstable();
assert_eq!(staged_versions, [156, 157]);
for affected in [&chrome, &helium, &staged] {
assert!(has_clipboard_race(affected), "{}", affected.display());
}
for unaffected in [
&fixed,
&older,
&electron,
&safari,
&root.join("Missing.app"),
] {
assert!(!has_clipboard_race(unaffected), "{}", unaffected.display());
}
fs::remove_dir_all(&root).unwrap();
}
#[test]
fn chromium_versions_need_four_numeric_components() {
assert_eq!(chromium_major_version("155.0.8059.84"), Some(155));
assert_eq!(chromium_major_version("156.1.88.10"), Some(156));
for version in [
"A",
"Current",
"155",
"155.0.8059",
"155.0.8059.84.1",
"155.0.x.1",
] {
assert_eq!(chromium_major_version(version), None, "{version}");
}