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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
//! Hand-written Objective-C runtime FFI, and the C structures AppKit passes
//! across it.
//!
//! The windowing backend table's macOS row (`docs/notes/backends.md`), which
//! reads in full: "hand-written
//! Objective-C runtime FFI (`objc_msgSend`) to AppKit". Every declaration below
//! is ours; there is no `objc2`, no `cocoa`, no `core-foundation`, and no
//! framework of any kind.
//!
//! # Decision: `#[link]`, not `dlopen` — the same argument `win32::ffi` makes
//!
//! `x11::ffi` and `wayland::ffi` both load their libraries with `dlopen`,
//! because the registry in [`backend`](crate::backend) is a fall-through list
//! and an entry has to be able to fail at *runtime*: a `DT_NEEDED` on
//! `libwayland-client.so.0` kills the process in `ld.so` before
//! [`open`](crate::open) runs, on any machine that does not have it — and a
//! machine without libwayland is an ordinary machine.
//!
//! **That premise does not hold here either.** AppKit, Foundation, QuartzCore,
//! CoreGraphics, Carbon and `libobjc` are the operating system: a macOS that
//! lacks them is not a macOS this engine failed to support, it is one that
//! cannot run a process. There is nothing for a runtime probe to discover, and
//! `dlopen`ing system frameworks would buy exactly one thing — a fallible code
//! path with no failure. macOS has a single backend, so nothing falls
//! through to anything and the registry consequence that forces the Linux
//! answer is absent.
//!
//! # Decision: `objc_msgSend` is transmuted at every call, from one place
//!
//! **`objc_msgSend` has no variadic ABI on `aarch64-apple-darwin`.** Apple's
//! arm64 calling convention passes variadic arguments on the stack while normal
//! arguments go in registers, and `objc_msgSend` is not a variadic function at
//! all — it is a trampoline that must be *called with the exact signature of the
//! method it dispatches to*, so that every argument is already in the register
//! the implementation will read it from. Declaring it as
//! `fn(Id, Sel, ...) -> Id` and calling it with three arguments compiles, links,
//! runs, and silently hands the method whatever happened to be in the register
//! it looked in.
//!
//! So this module exports the symbol as an opaque address and one generic
//! function, [`msg_send`], that transmutes it to a caller-supplied function
//! pointer type. Every call site therefore **writes the method's signature
//! down**, which is the only form of this that a compiler can check anything
//! about. The named helpers below ([`msg`], [`msg_void`], …) are that generic
//! applied to the shapes used more than twice; anything else spells its
//! signature out at the call site.
//!
//! # Decision: large struct returns take a different symbol on x86_64
//!
//! An `NSRect` is four `CGFloat`s. The System V ABI returns a 32-byte structure
//! through a hidden pointer, and the Objective-C runtime has a *separate*
//! trampoline for that case — `objc_msgSend_stret` — because the hidden pointer
//! displaces the receiver from its usual register. AArch64 has an indirect
//! result register (`x8`) that is not one of the argument registers, so it needs
//! no such split and `objc_msgSend_stret` does not exist there at all.
//!
//! [`msg_send_stret`] is that difference, and it is implemented on **both**
//! sides rather than only on the one the CI runner uses. A `cfg` arm that exists
//! for Apple silicon and silently does the wrong thing on an Intel Mac is not
//! portability; it is a defect that reports as a pass.
//!
//! # What is deliberately not declared
//!
//! | Not used | What it would buy | Why not |
//! | --- | --- | --- |
//! | `toggleFullScreen:` and `NSWindowStyleMaskFullScreen` | Spaces fullscreen | the windowing rules in `docs/notes/backends.md` drop exclusive fullscreen and keep two modes; Spaces fullscreen is a third, with its own animation, its own space and its own failure modes. Borderless here is a frameless window at screen size — see [`window`](super::window) |
//! | `NSPasteboardTypeString` and `NSPasteboardTypeFileURL` as `NSString *` globals | the two type identifiers | they are *values* — `public.utf8-plain-text` and `public.file-url` — and a compatibility contract with every other application, so [`pasteboard`](super::pasteboard) spells them out where a Linux host's tests can read them. Reaching them through a linker symbol would put the one part of the pasteboard mapping that can be silently wrong somewhere no test can see |
//! | `pasteboard:provideDataForType:` and a non-nil `addTypes:owner:` | lazily provided pasteboard data | the callback has to be answered from a run-loop turn this backend does not own between two [`pump`](crate::Shell::pump)s, and a lazy owner owes the pasteboard a flush before the process exits. [`pasteboard`](super::pasteboard) argues both; it is the same refusal `win32::clipboard` makes about `WM_RENDERFORMAT` |
//! | `NSFilenamesPboardType`, `com.apple.pasteboard.promised-file-url` | older and promised file drops | deprecated in 10.13 and, for a promise, a file the seam has no way to name a destination directory for. See [`pasteboard`](super::pasteboard) |
//! | `IOHIDManager`, `IOHIDGetAccelerationWithKey` | genuinely unaccelerated pointer deltas | `NSEvent`'s `deltaX`/`deltaY` carry the system's pointer acceleration and macOS exposes no public way to take it off. Reaching past AppKit into IOKit for it is a slice of its own; [`caps`](super::AppKitShell::caps) states exactly what [`RAW_POINTER_MOTION`](crate::ShellCaps::RAW_POINTER_MOTION) does and does not mean here |
//! | any `_windowResize*Cursor` and `busyButClickableCursor` | diagonal-resize and busy cursors | **private selectors.** `NSCursor`'s public set has no diagonal resize and no wait cursor; [`pointer::cursor_selector`](super::pointer::cursor_selector) names each approximation rather than calling a method Apple does not publish |
//! | `NSAutoreleasePool` as an object | a scope for autoreleased returns | [`objc_autoreleasePoolPush`](sys::objc_autoreleasePoolPush)/[`objc_autoreleasePoolPop`](sys::objc_autoreleasePoolPop) are the same thing without a message send, and are the form that works under ARC and non-ARC alike |
//! | `CGDisplayModeGetRefreshRate`'s `CGDisplayModeGetRefreshRateRational` twin | an exact 60000/1001 | it does not exist; the `double` this one returns already expresses 59.94, which is more than Win32's integer hertz can do |
//! | `NSApplication`'s delegate slot | screen-parameter changes | taking it would displace a host application's own delegate. `NSNotificationCenter` is the polite form and is what [`app`](super::app) uses |
use c_void;
// Only the macOS half sends messages or builds strings; on every other host this
// module is compiled for its structures alone (see the `extern` gate below), and
// an unconditional import would be an unused one there.
use ;
// Apple dropped every 32-bit target years before this backend was written, and
// `CGFloat` is `f32` there rather than `f64` — so every signature in this module
// would be wrong on one. Failing in the compiler is the honest answer; silently
// compiling arithmetic that is half the width the ABI expects is not.
compile_error!;
// ---------------------------------------------------------------------------
// Scalar aliases
// ---------------------------------------------------------------------------
/// Any Objective-C object pointer: `id`, and also `Class`, which is one.
///
/// One alias rather than a newtype per class, for the reason the X11 backend
/// gives for its single `Cookie` and the Win32 backend for its single `Handle`:
/// they are the same thing to the runtime, and the type system cannot check
/// which class a pointer actually names. Where the distinction matters it is in
/// the parameter name.
pub type Id = *mut c_void;
/// A `Class`, which is an object too. Named apart for readability only.
pub type Class = *mut c_void;
/// A selector — an interned method name, `SEL`.
pub type Sel = *const c_void;
/// An `IMP`: the function pointer behind a method.
///
/// Declared with no arguments because [`class_addMethod`] takes it as an opaque
/// address and the *type encoding* string beside it is what describes the real
/// signature. Every implementation this backend installs is cast to this from a
/// correctly-typed `extern "C"` function.
pub type Imp = unsafe extern "C" fn;
/// `CGFloat`. `f64` on every 64-bit Apple target; see the `compile_error!`
/// above.
pub type CGFloat = f64;
/// `NSInteger`.
pub type NSInteger = isize;
/// `NSUInteger`.
pub type NSUInteger = usize;
/// `BOOL`, as **`i8` rather than `bool`**.
///
/// It is `signed char` on x86_64 and `_Bool` on arm64, and only the second has
/// exactly two valid bit patterns. Rust's `bool` has exactly two, so reading an
/// x86_64 `BOOL` return directly into one would be undefined behaviour the day
/// some method answered `2`. Everything crossing this boundary is an `i8` and is
/// compared against zero; [`YES`] and [`NO`] are what goes the other way.
pub type ObjcBool = i8;
/// `YES`.
pub const YES: ObjcBool = 1;
/// `NO`.
pub const NO: ObjcBool = 0;
/// The type encoding of `BOOL` in a method signature, which is not the same
/// character on the two architectures.
///
/// `signed char` on x86_64, `_Bool` on arm64. It is passed to
/// [`class_addMethod`], where the runtime reads it to build an `NSInvocation` if
/// anything ever forwards one of these methods — so a wrong character is a
/// wrong-sized read of a return value in a code path nothing here exercises and
/// AppKit might.
pub const ENC_BOOL: &str = "B";
/// See the `aarch64` arm.
pub const ENC_BOOL: &str = "c";
// ---------------------------------------------------------------------------
// Structures
// ---------------------------------------------------------------------------
/// `NSPoint` / `CGPoint`.
///
/// **Y is up.** The origin of the screen coordinate space is the bottom-left of
/// the primary display, which is the opposite of every other backend in this
/// crate; [`geometry`](super::geometry) is where that is converted and is the
/// only place it should be.
/// `NSSize` / `CGSize`.
/// `NSRect` / `CGRect` — an origin and a size, never two corners.
///
/// The opposite of Win32's `RECT`, which is two corners and never an origin and
/// a size. Getting that backwards is the classic mistake on each platform, in
/// opposite directions.
/// `NSRange` — the location and length `NSTextInputClient` speaks in.
///
/// **UTF-16 code units, not bytes and not characters**, because that is what an
/// `NSString` is indexed by. Sixteen bytes of two integers, so both target ABIs
/// return it in registers and it never needs [`msg_send_stret`] — unlike
/// [`NSRect`], which is the only shape here that does.
/// The Objective-C type encoding of an `NSRange` on a 64-bit target.
///
/// Two `NSUInteger`s, which encode as `Q`. Passed to [`class_addMethod`] for
/// every `NSTextInputClient` method that takes or returns one; a wrong encoding
/// is a wrong-width read in the forwarding path nothing here exercises and an
/// input method might.
pub const ENC_RANGE: &str = "{_NSRange=QQ}";
/// The type encoding of an `NSRect`, which is a `CGRect`.
pub const ENC_RECT: &str = "{CGRect={CGPoint=dd}{CGSize=dd}}";
/// The type encoding of an `NSPoint`, which is a `CGPoint`.
pub const ENC_POINT: &str = "{CGPoint=dd}";
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
/// `NSWindowStyleMask` values.
/// `CGWindowLevelKey` values: what `CGWindowLevelForKey` turns into a window
/// level. Asked for at run time rather than spelled as numbers, because the
/// levels are the window server's to define.
/// `NSWindowCollectionBehavior` values.
/// Everything else that is a bare number.
/// `NSEventModifierFlags`, and the device-dependent bits underneath them.
///
/// # Two layers, and only the lower one says *which* Shift
///
/// The documented flags in the high half (`1 << 16` upwards) say that *a* Shift
/// is held. `flagsChanged:` is the only notification a modifier key produces on
/// this platform — there is no `keyDown:` for Shift — so a backend that wants to
/// report [`ShiftLeft`](crcbl_core::KeyCode::ShiftLeft) going down has to know
/// which one changed and whether it is now down. The **device-dependent** bits in
/// the low half carry exactly that, one per physical key, and they are what
/// [`keys::modifier_is_down`](super::keys::modifier_is_down) reads.
///
/// They come from `IOKit/hidsystem/IOLLEvent.h`'s `NX_DEVICE*KEYMASK` rather
/// than from AppKit's own header, which is why they are spelled out here with
/// their IOKit names beside them.
/// `NSTrackingAreaOptions`.
// ---------------------------------------------------------------------------
// The runtime and the frameworks
// ---------------------------------------------------------------------------
// Every `extern` block in this module is macOS-only, and that is not the usual
// "this code cannot work elsewhere" gate. `#[link(kind = "framework")]` is
// **rejected by rustc on a non-Apple target** rather than merely being useless
// there, so a declaration outside this gate would stop the Linux build of this
// crate from compiling at all — and the pure modules beside it
// ([`geometry`](super::geometry), [`events`](super::events)) exist precisely so
// that the arithmetic is exercised by `cargo test` on the machine this engine is
// developed on. The types and constants above are compiled everywhere, which is
// what lets those modules name them.
pub use ;
/// The three declarations that exist for the macOS test suite alone.
pub use ;
// ---------------------------------------------------------------------------
// Class and selector lookup
// ---------------------------------------------------------------------------
/// The class named `name`, or `None` if this image does not have it.
///
/// `None` is not hypothetical paranoia: it is what a build that failed to link a
/// framework would produce, and turning it into a
/// [`ShellError::Connect`](crate::ShellError::Connect) naming the class is a
/// diagnosis. The alternative — sending a message to `nil` — does nothing and
/// returns zero, forever, silently.
/// The selector for `name`, registering it if this process has not seen it.
///
/// Cannot fail: `sel_registerName` interns the string and returns a pointer into
/// the runtime's own table. Cheap enough to call per use — it is a hash lookup —
/// which is why there is no selector cache to keep in sync with the call sites.
/// A scope in which autoreleased objects are valid, and at whose end they are
/// released.
///
/// Every AppKit method that returns an object it did not `alloc` — and that is
/// most of them, `[NSScreen screens]` and `[NSString stringWithUTF8String:]`
/// included — returns it **autoreleased**. With no pool in place the runtime
/// logs "autoreleased with no pool in place — just leaking" and does exactly
/// that. A normal Cocoa application gets a pool per turn of `NSApplication`'s
/// run loop; this backend does not have that loop, so it pushes its own around
/// every entry point that talks to AppKit.
///
/// [`objc_autoreleasePoolPush`](sys::objc_autoreleasePoolPush) rather than an
/// `NSAutoreleasePool` object: it is the same mechanism with no message send,
/// and it is the form that is legal under ARC — which matters because a host
/// application that embeds this engine is compiled with ARC even though this
/// crate is not.
;
// ---------------------------------------------------------------------------
// Message sending
// ---------------------------------------------------------------------------
/// `objc_msgSend`, transmuted to the exact signature of the method being sent.
///
/// **This is the one place the trampoline's address is taken**, and the reason
/// is the module documentation's: on `aarch64-apple-darwin` there is no variadic
/// ABI to declare it with, so the only correct call is one whose signature
/// matches the method's. Every caller therefore writes that signature down:
///
/// ```ignore
/// let set_frame: unsafe extern "C" fn(Id, Sel, NSRect, ObjcBool) =
/// unsafe { ffi::msg_send() };
/// unsafe { set_frame(window, ffi::sel(c"setFrame:display:"), rect, ffi::YES) };
/// ```
///
/// The size assertion is what stops `F` being anything but a function pointer —
/// `transmute_copy` would otherwise happily reinterpret a wider or narrower
/// type. It is a comparison of two constants and costs a shell call nothing.
///
/// # Safety
///
/// `F` must be a function pointer type whose signature is **exactly** the
/// receiver, the selector, and the arguments of the method that will be
/// dispatched, with that method's return type. A mismatch is not a type error at
/// any later point; it is arguments read out of the wrong registers.
pub unsafe
/// [`msg_send`] for a method whose return value does not fit in the ABI's return
/// registers.
///
/// On x86_64 that is `objc_msgSend_stret`, because the hidden return pointer
/// displaces the receiver out of `rdi`. On aarch64 the indirect result register
/// `x8` is not an argument register, nothing is displaced, and the symbol does
/// not exist — so the ordinary trampoline is correct and is what this returns.
///
/// In practice the only such type here is [`NSRect`], at 32 bytes. [`NSSize`]
/// and [`NSPoint`] are 16 and go back in registers on both architectures, which
/// is why `[screen frame]` needs this and `[window contentAspectRatio]` does
/// not.
///
/// # Safety
///
/// As [`msg_send`], and additionally: `F`'s return type must be one the target's
/// C ABI genuinely returns indirectly. Using this for a small return type is
/// wrong on x86_64 in the same way that not using it for a large one is.
pub unsafe
// The shapes used more than twice, so that the common call sites read as calls
// rather than as transmutes. Each is `msg_send` applied once, and each names its
// full signature in the same place its callers would have.
//
// `# Safety` on every one of these is the same sentence and is stated once here:
// the receiver must be a live object of a class that implements the selector,
// with arguments of the types the signature names. That is the obligation
// `objc_msgSend` always carries and none of these wrappers can discharge.
/// `[receiver sel]` returning an object.
///
/// # Safety
///
/// See the note above this function: `receiver` must implement `selector` with
/// this signature.
pub unsafe
/// `[receiver sel]` returning nothing.
///
/// # Safety
///
/// As [`msg`].
pub unsafe
/// `[receiver sel]` returning `BOOL`.
///
/// # Safety
///
/// As [`msg`].
pub unsafe
/// `[receiver sel]` returning a `CGFloat`.
///
/// # Safety
///
/// As [`msg`].
pub unsafe
/// `[receiver sel]` returning an `NSUInteger`.
///
/// # Safety
///
/// As [`msg`].
pub unsafe
/// `[receiver sel]` returning an `NSRect` — the one shape that needs
/// [`msg_send_stret`].
///
/// # Safety
///
/// As [`msg`].
pub unsafe
/// `[receiver sel:object]` returning an object.
///
/// # Safety
///
/// As [`msg`].
pub unsafe
/// `[receiver sel:object]` returning nothing.
///
/// # Safety
///
/// As [`msg`].
pub unsafe
/// `[receiver sel:BOOL]`.
///
/// # Safety
///
/// As [`msg`].
pub unsafe
/// `[receiver sel:NSUInteger]`.
///
/// # Safety
///
/// As [`msg`].
pub unsafe
/// `[receiver sel:NSInteger]`.
///
/// # Safety
///
/// As [`msg`].
pub unsafe
/// `[receiver sel:NSSize]`.
///
/// # Safety
///
/// As [`msg`].
pub unsafe
/// `[receiver respondsToSelector:]`.
///
/// The version check this backend uses instead of a deployment-target macro:
/// `localizedName` arrived in 10.15 and `activate` in 14, and sending either to
/// a system that does not have it is a crash rather than a graceful nothing.
///
/// # Safety
///
/// `receiver` must be a live object; every object answers this selector.
pub unsafe
/// An `NSString` holding `text`, autoreleased into the innermost [`Pool`].
///
/// `None` when `text` contains an interior NUL, which would silently truncate
/// the string — the same refusal the Win32 backend makes for the same reason.
///
/// # Safety
///
/// An autorelease pool must be in scope, or the string leaks.
pub unsafe
/// An `NSString`'s contents, lossily.
///
/// Lossy for the reason the Win32 backend's device-name reader gives: this is a
/// display string — a monitor's name — and one bad byte is better shown as a
/// replacement character than dropped.
///
/// # Safety
///
/// `string` must be a live `NSString` (or `nil`, which answers `None`), and an
/// autorelease pool must be in scope.
pub unsafe