-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathUIKit.mm
More file actions
3817 lines (3525 loc) · 164 KB
/
Copy pathUIKit.mm
File metadata and controls
3817 lines (3525 loc) · 164 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
@import Darwin;
@import QuartzCore;
@import UIKit;
#import <objc/runtime.h>
#include "bridge.h"
#include "crash_exception.h"
#include "LiveExec32Shared.h"
#include "LC32LegacyCanvas.h"
#include "LC32LegacyRotation.h"
#include "../CoreGraphics/LC32CoreGraphicsHost.h"
#include <atomic>
#include <dispatch/dispatch.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef NS_ENUM(NSUInteger, LC32LegacyIPadGeometryMode) {
/* Pre-root-controller applications and some early fixed-surface engines
* keep a portrait iPad drawable and rely on UIKit's compositor turn. */
LC32LegacyIPadGeometryModePreservePortraitCanvas,
/* Applications using UIWindow.rootViewController expect UIKit to resize
* the controller hierarchy into the requested interface orientation. */
LC32LegacyIPadGeometryModeReflowRootController,
/* Some legacy landscape phone applications deliberately render through
* a portrait 320x480 surface and rotate in their projection matrix. Keep
* that drawable contract and turn only the native wrapper. */
LC32LegacyIPadGeometryModePreservePhonePortraitCanvas,
/* Some 568-point phone applications advertise tall launch art but retain
* a 480x320 game view. Keep that already-landscape drawable centered at
* 1x inside the modern scene. */
LC32LegacyIPadGeometryModePreservePhoneLandscapeCanvas,
};
@interface LC32LegacyIPadContainerController : UIViewController {
@private
UIViewController *_guestContentController;
UIView *_guestContentView;
UIView *_canvasView;
CGRect _canonicalGuestBounds;
LC32LegacyIPadGeometryMode _geometryMode;
BOOL _fittingGuestContent;
BOOL _guestLayoutPending;
NSUInteger _guestContentGeneration;
}
@property(nonatomic, readonly) UIViewController *guestContentController;
@property(nonatomic, readonly) LC32LegacyIPadGeometryMode geometryMode;
- (instancetype)initWithGuestContentController:
(UIViewController *)controller
geometryMode:(LC32LegacyIPadGeometryMode)mode;
- (void)setGuestContentController:(UIViewController *)controller
geometryMode:(LC32LegacyIPadGeometryMode)mode;
- (void)fitGuestContentForViewport:(CGRect)viewport
hostOrientation:(UIInterfaceOrientation)orientation;
- (void)scheduleGuestLayout;
@end
/*
* UIWindow.rootViewController did not exist before iOS 4. Main-nib games
* from that era commonly archive their drawable view directly under the
* window and leave the root controller nil. Modern UIKit rejects such a
* window at the end of application launch, so give the host a controller
* whose inert view sits behind the untouched guest hierarchy. The guest
* rootViewController accessor deliberately hides this implementation detail.
*/
@interface LC32LegacyWindowRootController : UIViewController
@end
@interface LC32LegacyRendererAutoresizingState : NSObject
@property(nonatomic) UIViewAutoresizing originalMask;
@property(nonatomic) BOOL yielded;
@end
@implementation LC32LegacyRendererAutoresizingState
@end
/*
symbol = r0 + r1 << 32
r0 = r2
r1 = r3
r2 = sp
r3 = sp+4
...
*/
namespace {
const void *LC32LegacyOrientationMaskKey =
&LC32LegacyOrientationMaskKey;
const void *LC32GuestSupportedOrientationsIMPKey =
&LC32GuestSupportedOrientationsIMPKey;
const void *LC32GuestPreferredOrientationIMPKey =
&LC32GuestPreferredOrientationIMPKey;
const void *LC32SettledLegacyOrientationKey =
&LC32SettledLegacyOrientationKey;
const void *LC32HideLegacyDirectGuestWindowRootKey =
&LC32HideLegacyDirectGuestWindowRootKey;
const void *LC32LegacyDirectWindowSublayerTransformKey =
&LC32LegacyDirectWindowSublayerTransformKey;
const void *LC32LegacyDirectWindowAppliedSublayerTransformKey =
&LC32LegacyDirectWindowAppliedSublayerTransformKey;
const void *LC32LegacyWindowLayersLayoutPendingKey =
&LC32LegacyWindowLayersLayoutPendingKey;
const void *LC32LegacyRootlessWindowPlacementKey =
&LC32LegacyRootlessWindowPlacementKey;
const void *LC32LegacyRootlessRendererAutoresizingKey =
&LC32LegacyRootlessRendererAutoresizingKey;
const void *LC32LegacyRootlessRendererAutoresizingStateKey =
&LC32LegacyRootlessRendererAutoresizingStateKey;
const void *LC32LegacyOverlayLayoutPendingKey =
&LC32LegacyOverlayLayoutPendingKey;
const void *LC32LegacyRootWindowGeometryKey =
&LC32LegacyRootWindowGeometryKey;
struct LC32GuestUIKitPolicy {
UIInterfaceOrientationMask declaredOrientations;
UIInterfaceOrientation preferredOrientation;
bool statusBarHidden;
bool constrainsControllerOrientations;
bool usesLegacyInitialOrientation;
};
const LC32GuestUIKitPolicy& LC32GuestInterfacePolicy(void);
UIInterfaceOrientation LC32FirstOrientationInMask(
UIInterfaceOrientationMask mask);
id LC32ObjectProperty(id object, const char *name);
std::atomic<NSInteger> LC32LegacyRequestedOrientation{
UIInterfaceOrientationUnknown};
thread_local bool LC32SuppressGuestOrientationQuery = false;
thread_local bool LC32AllowGuestOrientationQuery = false;
// A registered guest thread is not necessarily ready for renderer callbacks.
// Legacy engines can show their window before initializing the screen manager,
// sometimes in a zero-delay selector scheduled by the launch delegate.
std::atomic<bool> LC32GuestOrientationStartupComplete{true};
u32 LC32GuestOrientationStartupCallbackDepth = 0;
bool LC32CanQueryGuestOrientation(void) {
return LC32GuestOrientationStartupComplete.load(std::memory_order_acquire) &&
!LC32SuppressGuestOrientationQuery &&
Dynarmic_guest_thread_is_registered();
}
class LC32GuestOrientationQueryScope {
public:
LC32GuestOrientationQueryScope()
: previous_(LC32AllowGuestOrientationQuery) {
LC32AllowGuestOrientationQuery = true;
}
~LC32GuestOrientationQueryScope() {
LC32AllowGuestOrientationQuery = previous_;
}
private:
bool previous_;
};
/*
* Do not replace these calls with ordinary Objective-C messages. A view can
* be an instance of a synthesized guest subclass whose override is backed by
* LC32InvokeGuestSelector. UIKit invokes the compatibility layout code from
* native scene callbacks, where dynamically dispatching into ARM32 guest code
* is unsafe (and may run on a host thread that is not registered for guest
* execution). Calling UIView's typed IMP directly deliberately applies only
* the native base implementation while preserving the arm64 aggregate ABI.
*/
CGRect LC32NativeViewBounds(UIView *view) {
using Getter = CGRect (*)(id, SEL);
static Getter getter = reinterpret_cast<Getter>(
class_getMethodImplementation(UIView.class, @selector(bounds)));
return view ? getter(view, @selector(bounds)) : CGRectZero;
}
UIView *LC32NativeViewSuperview(UIView *view) {
using Getter = UIView *(*)(id, SEL);
static Getter getter = reinterpret_cast<Getter>(
class_getMethodImplementation(UIView.class, @selector(superview)));
return view ? getter(view, @selector(superview)) : nil;
}
NSArray<UIView *> *LC32NativeViewSubviews(UIView *view) {
using Getter = NSArray<UIView *> *(*)(id, SEL);
static Getter getter = reinterpret_cast<Getter>(
class_getMethodImplementation(UIView.class, @selector(subviews)));
return view ? getter(view, @selector(subviews)) : nil;
}
UIWindow *LC32NativeViewWindow(UIView *view) {
using Getter = UIWindow *(*)(id, SEL);
static Getter getter = reinterpret_cast<Getter>(
class_getMethodImplementation(UIView.class, @selector(window)));
return view ? getter(view, @selector(window)) : nil;
}
BOOL LC32NativeViewHidden(UIView *view) {
using Getter = BOOL (*)(id, SEL);
static Getter getter = reinterpret_cast<Getter>(
class_getMethodImplementation(UIView.class, @selector(isHidden)));
return view ? getter(view, @selector(isHidden)) : NO;
}
CALayer *LC32NativeViewLayer(UIView *view) {
using Getter = CALayer *(*)(id, SEL);
static Getter getter = reinterpret_cast<Getter>(
class_getMethodImplementation(UIView.class, @selector(layer)));
return view ? getter(view, @selector(layer)) : nil;
}
UIApplicationState LC32NativeApplicationState(void) {
UIApplication *application = UIApplication.sharedApplication;
using Getter = UIApplicationState (*)(id, SEL);
static Getter getter = reinterpret_cast<Getter>(
class_getMethodImplementation(
UIApplication.class, @selector(applicationState)));
return application
? getter(application, @selector(applicationState))
: UIApplicationStateInactive;
}
CGAffineTransform LC32NativeViewTransform(UIView *view) {
using Getter = CGAffineTransform (*)(id, SEL);
static Getter getter = reinterpret_cast<Getter>(
class_getMethodImplementation(UIView.class,
@selector(transform)));
return view ? getter(view, @selector(transform))
: CGAffineTransformIdentity;
}
CGPoint LC32NativeViewCenter(UIView *view) {
using Getter = CGPoint (*)(id, SEL);
static Getter getter = reinterpret_cast<Getter>(
class_getMethodImplementation(UIView.class, @selector(center)));
return view ? getter(view, @selector(center)) : CGPointZero;
}
void LC32NativeSetViewBounds(UIView *view, CGRect bounds) {
using Setter = void (*)(id, SEL, CGRect);
static Setter setter = reinterpret_cast<Setter>(
class_getMethodImplementation(UIView.class, @selector(setBounds:)));
if(view) setter(view, @selector(setBounds:), bounds);
}
void LC32NativeSetViewCenter(UIView *view, CGPoint center) {
using Setter = void (*)(id, SEL, CGPoint);
static Setter setter = reinterpret_cast<Setter>(
class_getMethodImplementation(UIView.class, @selector(setCenter:)));
if(view) setter(view, @selector(setCenter:), center);
}
void LC32NativeSetViewTransform(
UIView *view, CGAffineTransform transform) {
using Setter = void (*)(id, SEL, CGAffineTransform);
static Setter setter = reinterpret_cast<Setter>(
class_getMethodImplementation(UIView.class,
@selector(setTransform:)));
if(view) setter(view, @selector(setTransform:), transform);
}
void LC32NativeSetViewAutoresizingMask(
UIView *view, UIViewAutoresizing mask) {
using Setter = void (*)(id, SEL, UIViewAutoresizing);
static Setter setter = reinterpret_cast<Setter>(
class_getMethodImplementation(
UIView.class, @selector(setAutoresizingMask:)));
if(view) setter(view, @selector(setAutoresizingMask:), mask);
}
UIViewAutoresizing LC32NativeViewAutoresizingMask(UIView *view) {
using Getter = UIViewAutoresizing (*)(id, SEL);
static Getter getter = reinterpret_cast<Getter>(
class_getMethodImplementation(UIView.class,
@selector(autoresizingMask)));
return view ? getter(view, @selector(autoresizingMask))
: UIViewAutoresizingNone;
}
void LC32NativeSetViewNeedsLayout(UIView *view) {
using Setter = void (*)(id, SEL);
static Setter setter = reinterpret_cast<Setter>(
class_getMethodImplementation(UIView.class,
@selector(setNeedsLayout)));
if(view) setter(view, @selector(setNeedsLayout));
}
void LC32NativeLayoutViewIfNeeded(UIView *view) {
using Layout = void (*)(id, SEL);
static Layout layout = reinterpret_cast<Layout>(
class_getMethodImplementation(UIView.class,
@selector(layoutIfNeeded)));
if(view) layout(view, @selector(layoutIfNeeded));
}
void LC32NativeSendSubviewToBack(UIView *view, UIView *subview) {
using SendSubviewToBack = void (*)(id, SEL, UIView *);
static SendSubviewToBack sendSubviewToBack =
reinterpret_cast<SendSubviewToBack>(
class_getMethodImplementation(
UIView.class, @selector(sendSubviewToBack:)));
if(view && subview) {
sendSubviewToBack(view, @selector(sendSubviewToBack:), subview);
}
}
UIInterfaceOrientationMask LC32CachedGuestOrientationMask(
UIViewController *controller) {
NSNumber *cached = controller ? objc_getAssociatedObject(
controller, LC32LegacyOrientationMaskKey) : nil;
return cached ? (UIInterfaceOrientationMask)cached.unsignedLongLongValue
: LC32GuestInterfacePolicy().declaredOrientations;
}
UIInterfaceOrientation LC32InterfaceOrientationFromName(NSString *name) {
if([name isEqualToString:@"UIInterfaceOrientationPortrait"]) {
return UIInterfaceOrientationPortrait;
}
if([name isEqualToString:@"UIInterfaceOrientationPortraitUpsideDown"]) {
return UIInterfaceOrientationPortraitUpsideDown;
}
if([name isEqualToString:@"UIInterfaceOrientationLandscapeLeft"]) {
return UIInterfaceOrientationLandscapeLeft;
}
if([name isEqualToString:@"UIInterfaceOrientationLandscapeRight"]) {
return UIInterfaceOrientationLandscapeRight;
}
return UIInterfaceOrientationUnknown;
}
UIInterfaceOrientationMask LC32MaskForInterfaceOrientation(
UIInterfaceOrientation orientation) {
switch(orientation) {
case UIInterfaceOrientationPortrait:
case UIInterfaceOrientationPortraitUpsideDown:
case UIInterfaceOrientationLandscapeLeft:
case UIInterfaceOrientationLandscapeRight:
return (UIInterfaceOrientationMask)1 << orientation;
default:
return 0;
}
}
UIInterfaceOrientationMask LC32ConstrainGuestOrientationMask(
UIInterfaceOrientationMask mask) {
const LC32GuestUIKitPolicy &policy = LC32GuestInterfacePolicy();
if(!mask) return policy.declaredOrientations;
if(!policy.constrainsControllerOrientations) return mask;
/* A real supported-orientations array is an outer constraint on every
* controller. UIInterfaceOrientation is only an initial-side hint and is
* handled later, where the active window scene is known. */
const UIInterfaceOrientationMask constrained =
mask & policy.declaredOrientations;
return constrained ? constrained : policy.declaredOrientations;
}
const LC32GuestUIKitPolicy& LC32GuestInterfacePolicy(void) {
static LC32GuestUIKitPolicy policy = {
UIInterfaceOrientationMaskPortrait,
UIInterfaceOrientationPortrait,
false,
false,
false,
};
/* UIKit can query native controller policy while the shim dylib is
* loading. Do not permanently cache the fallback until LC32RunGuest has
* published the selected guest executable. */
const char *guestExecutable = getenv("LC32_GUEST_EXECUTABLE");
if(!guestExecutable || !guestExecutable[0]) return policy;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSString *path = [NSString stringWithUTF8String:
getenv("LC32_GUEST_EXECUTABLE")];
NSBundle *bundle = [NSBundle bundleWithPath:
path.stringByDeletingLastPathComponent];
NSDictionary *info = bundle.infoDictionary;
if(!info) return;
const bool usesIPadPolicy = LC32BundleNeedsLegacyIPadCanvas(
bundle, LC32GetGuestExecutableSDKVersion());
NSArray *orientationNames = usesIPadPolicy
? info[@"UISupportedInterfaceOrientations~ipad"] : nil;
if(![orientationNames isKindOfClass:NSArray.class]) {
orientationNames = info[@"UISupportedInterfaceOrientations"];
}
const bool hasSupportedOrientationArray =
[orientationNames isKindOfClass:NSArray.class];
UIInterfaceOrientationMask declared = 0;
for(id value in orientationNames) {
if(![value isKindOfClass:NSString.class]) continue;
declared |= LC32MaskForInterfaceOrientation(
LC32InterfaceOrientationFromName(value));
}
const UIInterfaceOrientation preferred =
LC32InterfaceOrientationFromName(info[@"UIInterfaceOrientation"]);
const UIInterfaceOrientationMask preferredMask =
LC32MaskForInterfaceOrientation(preferred);
const bool usesLegacyInitialOrientation =
!hasSupportedOrientationArray && preferredMask;
if(!declared && usesLegacyInitialOrientation) {
declared = preferredMask;
}
if(!declared) declared = UIInterfaceOrientationMaskPortrait;
policy.declaredOrientations = declared;
policy.preferredOrientation =
preferredMask & declared
? preferred
: UIInterfaceOrientationUnknown;
policy.statusBarHidden = [info[@"UIStatusBarHidden"] boolValue];
policy.constrainsControllerOrientations =
hasSupportedOrientationArray;
policy.usesLegacyInitialOrientation =
usesLegacyInitialOrientation;
});
return policy;
}
void LC32CacheSettledLegacyOrientation(
id object, UIInterfaceOrientation orientation) {
if(!object || !LC32GuestInterfacePolicy().usesLegacyInitialOrientation ||
!LC32MaskForInterfaceOrientation(orientation)) {
return;
}
objc_setAssociatedObject(object, LC32SettledLegacyOrientationKey,
@((NSInteger)orientation), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
UIInterfaceOrientation LC32SettledLegacyOrientation(
id object, UIInterfaceOrientationMask mask) {
if(!LC32GuestInterfacePolicy().usesLegacyInitialOrientation) {
return UIInterfaceOrientationUnknown;
}
NSNumber *cached = object ? objc_getAssociatedObject(
object, LC32SettledLegacyOrientationKey) : nil;
const UIInterfaceOrientation settled = cached
? (UIInterfaceOrientation)cached.integerValue
: UIInterfaceOrientationUnknown;
return LC32MaskForInterfaceOrientation(settled) & mask
? settled : UIInterfaceOrientationUnknown;
}
IMP LC32GuestOrientationImplementation(id object, const void *key) {
for(Class cls = object_getClass(object); cls;
cls = class_getSuperclass(cls)) {
NSNumber *value = objc_getAssociatedObject((id)cls, key);
if(value) return reinterpret_cast<IMP>(
static_cast<uintptr_t>(value.unsignedLongLongValue));
if(cls == UIViewController.class) break;
}
return nullptr;
}
UIInterfaceOrientationMask LC32GuestSupportedInterfaceOrientations(
UIViewController *controller, SEL selector) {
NSNumber *cached = objc_getAssociatedObject(
controller, LC32LegacyOrientationMaskKey);
if(!LC32AllowGuestOrientationQuery || !LC32CanQueryGuestOrientation()) {
return cached
? (UIInterfaceOrientationMask)cached.unsignedLongLongValue
: LC32GuestInterfacePolicy().declaredOrientations;
}
using SupportedOrientations =
UIInterfaceOrientationMask (*)(id, SEL);
SupportedOrientations original =
reinterpret_cast<SupportedOrientations>(
LC32GuestOrientationImplementation(
controller, LC32GuestSupportedOrientationsIMPKey));
UIInterfaceOrientationMask mask = original
? original(controller, selector) : 0;
mask = LC32ConstrainGuestOrientationMask(mask);
objc_setAssociatedObject(controller, LC32LegacyOrientationMaskKey,
@(mask), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
return mask;
}
UIInterfaceOrientationMask LC32ControllerSupportedInterfaceOrientations(
UIViewController *controller) {
using SupportedOrientations =
UIInterfaceOrientationMask (*)(id, SEL);
UIInterfaceOrientationMask mask = controller
? reinterpret_cast<SupportedOrientations>(objc_msgSend)(
controller, @selector(supportedInterfaceOrientations))
: 0;
mask = LC32ConstrainGuestOrientationMask(mask);
if(controller) {
objc_setAssociatedObject(controller, LC32LegacyOrientationMaskKey,
@(mask), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
return mask;
}
UIInterfaceOrientation LC32GuestPreferredInterfaceOrientation(
UIViewController *controller, SEL selector) {
using PreferredOrientation = UIInterfaceOrientation (*)(id, SEL);
PreferredOrientation original =
reinterpret_cast<PreferredOrientation>(
LC32GuestOrientationImplementation(
controller, LC32GuestPreferredOrientationIMPKey));
const UIInterfaceOrientation guestPreferred =
original && LC32AllowGuestOrientationQuery &&
LC32CanQueryGuestOrientation()
? original(controller, selector)
: UIInterfaceOrientationUnknown;
const UIInterfaceOrientationMask mask =
LC32ControllerSupportedInterfaceOrientations(controller);
const UIInterfaceOrientation requested = (UIInterfaceOrientation)
LC32LegacyRequestedOrientation.load(std::memory_order_relaxed);
if(LC32MaskForInterfaceOrientation(requested) & mask) {
return requested;
}
const UIInterfaceOrientation settled =
LC32SettledLegacyOrientation(controller, mask);
if(settled != UIInterfaceOrientationUnknown) {
return settled;
}
if(LC32MaskForInterfaceOrientation(guestPreferred) & mask) {
return guestPreferred;
}
const UIInterfaceOrientation bundlePreferred =
LC32GuestInterfacePolicy().preferredOrientation;
if(LC32MaskForInterfaceOrientation(bundlePreferred) & mask) {
return bundlePreferred;
}
return LC32FirstOrientationInMask(mask);
}
Method LC32ClassOwnMethod(Class cls, SEL selector) {
unsigned int count = 0;
Method *methods = class_copyMethodList(cls, &count);
Method result = nullptr;
for(unsigned int index = 0; index < count; index++) {
if(method_getName(methods[index]) == selector) {
result = methods[index];
break;
}
}
free(methods);
return result;
}
struct LC32GuestLoadViewFrame {
__unsafe_unretained UIViewController *controller;
LC32GuestLoadViewFrame *previous;
};
thread_local LC32GuestLoadViewFrame *LC32GuestLoadViewFrames = nullptr;
bool LC32GuestLoadViewIsActive(UIViewController *controller) {
for(LC32GuestLoadViewFrame *frame = LC32GuestLoadViewFrames;
frame; frame = frame->previous) {
if(frame->controller == controller) return true;
}
return false;
}
class LC32GuestLoadViewScope {
public:
explicit LC32GuestLoadViewScope(UIViewController *controller)
: frame{controller, LC32GuestLoadViewFrames} {
LC32GuestLoadViewFrames = &frame;
}
~LC32GuestLoadViewScope() {
LC32GuestLoadViewFrames = frame.previous;
}
private:
LC32GuestLoadViewFrame frame;
};
void LC32GuestLoadView(UIViewController *controller, SEL selector) {
if(LC32GuestLoadViewIsActive(controller)) {
/* LC32InvokeHostSelector normally intercepts the reentrant -view read
* before native UIKit reaches this callback. Keep a no-op backstop for
* any other same-controller native load path; installing a generic
* UIView here would make the legacy override believe loading finished. */
return;
}
LC32GuestLoadViewScope scope(controller);
(void)LC32InvokeGuestSelector(
controller, selector, 0, 0, 0, 0, 0, 0);
}
void LC32GuestWillRotate(UIViewController *controller, SEL selector,
UIInterfaceOrientation orientation, NSTimeInterval duration) {
if(!LC32CanQueryGuestOrientation()) return;
// A typed native IMP receives duration in d0. Darwin ARMv7 uses four-byte
// argument alignment here: self/cmd/orientation occupy r0-r2, the double's
// low word is r3, and its high word is the first stack argument. Do not
// insert the eight-byte alignment padding used by generic AAPCS examples.
// Verified with Clang's armv7-apple-ios Objective-C caller and callee.
static_assert(sizeof(duration) == sizeof(u64));
u64 durationBits;
memcpy(&durationBits, &duration, sizeof(durationBits));
u32 arguments[] = {
[controller guest_self],
guest_sel_registerName(sel_getName(selector)),
static_cast<u32>(orientation),
static_cast<u32>(durationBits),
static_cast<u32>(durationBits >> 32),
};
(void)guest_objc_msgSend(sizeof(arguments) / sizeof(*arguments), arguments);
}
bool LC32NativeViewIfLoaded(UIViewController *controller, UIView **view) {
if(!view) return false;
using Getter = UIView *(*)(id, SEL);
static Getter getter = reinterpret_cast<Getter>(
class_getMethodImplementation(
UIViewController.class, @selector(viewIfLoaded)));
*view = controller ? getter(controller, @selector(viewIfLoaded)) : nil;
return true;
}
bool LC32ClassIsUIViewController(Class cls) {
const Class viewControllerClass = UIViewController.class;
for(Class current = cls; current;
current = class_getSuperclass(current)) {
if(current == viewControllerClass) return true;
}
return false;
}
bool LC32GuestClassHierarchyDefinesSelector(Class cls, SEL selector) {
for(Class current = cls; current && current != UIViewController.class;
current = class_getSuperclass(current)) {
if(LC32ClassOwnMethod(current, selector)) return true;
/* The class currently being registered is not marked until after
* objc_registerClassPair. Registered guest superclasses are marked,
* while the first native superclass terminates this search. */
if(current != cls && ![(id)current isGuestClass]) break;
}
return false;
}
UIInterfaceOrientation LC32FirstOrientationInMask(
UIInterfaceOrientationMask mask) {
static const UIInterfaceOrientation order[] = {
UIInterfaceOrientationPortrait,
UIInterfaceOrientationLandscapeLeft,
UIInterfaceOrientationLandscapeRight,
UIInterfaceOrientationPortraitUpsideDown,
};
for(UIInterfaceOrientation orientation : order) {
if(mask & LC32MaskForInterfaceOrientation(orientation)) {
return orientation;
}
}
return UIInterfaceOrientationPortrait;
}
UIInterfaceOrientationMask LC32LegacySupportedInterfaceOrientations(
UIViewController *controller, SEL) {
if(!LC32AllowGuestOrientationQuery || !LC32CanQueryGuestOrientation()) {
NSNumber *cached = objc_getAssociatedObject(
controller, LC32LegacyOrientationMaskKey);
return cached ? (UIInterfaceOrientationMask)cached.unsignedLongLongValue
: LC32GuestInterfacePolicy().declaredOrientations;
}
UIInterfaceOrientationMask mask = 0;
const SEL legacySelector =
@selector(shouldAutorotateToInterfaceOrientation:);
using LegacyAutorotation = BOOL (*)(id, SEL, UIInterfaceOrientation);
LegacyAutorotation shouldAutorotate =
reinterpret_cast<LegacyAutorotation>(objc_msgSend);
static const UIInterfaceOrientation orientations[] = {
UIInterfaceOrientationPortrait,
UIInterfaceOrientationPortraitUpsideDown,
UIInterfaceOrientationLandscapeLeft,
UIInterfaceOrientationLandscapeRight,
};
for(UIInterfaceOrientation orientation : orientations) {
if(shouldAutorotate(controller, legacySelector, orientation)) {
mask |= LC32MaskForInterfaceOrientation(orientation);
}
}
mask = LC32ConstrainGuestOrientationMask(mask);
objc_setAssociatedObject(controller, LC32LegacyOrientationMaskKey,
@(mask), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
return mask;
}
UIInterfaceOrientation LC32LegacyPreferredInterfaceOrientation(
UIViewController *controller, SEL) {
const UIInterfaceOrientationMask mask =
LC32ControllerSupportedInterfaceOrientations(controller);
const UIInterfaceOrientation requested = (UIInterfaceOrientation)
LC32LegacyRequestedOrientation.load(std::memory_order_relaxed);
if(LC32MaskForInterfaceOrientation(requested) & mask) return requested;
const UIInterfaceOrientation settled =
LC32SettledLegacyOrientation(controller, mask);
if(settled != UIInterfaceOrientationUnknown) return settled;
const UIInterfaceOrientation declared =
LC32GuestInterfacePolicy().preferredOrientation;
if(LC32MaskForInterfaceOrientation(declared) & mask) return declared;
return LC32FirstOrientationInMask(mask);
}
BOOL LC32LegacyPrefersStatusBarHidden(UIViewController *, SEL) {
return LC32GuestInterfacePolicy().statusBarHidden;
}
void LC32ScaleLegacyIPadWindow(UIWindow *window);
CGRect LC32WindowSceneBounds(UIWindow *window);
bool LC32UsesClassicFullScreenViewport(UIWindow *window);
CGRect LC32LegacyViewportInView(UIWindow *window, UIView *view);
UIInterfaceOrientation LC32WindowSceneOrientation(
UIWindow *window, CGRect sceneBounds);
UIInterfaceOrientationMask LC32SupportedOrientationsForController(
UIViewController *controller);
bool LC32ObjectUsesGuestClass(id object);
UIViewController *LC32NativeWindowRootViewController(UIWindow *window);
void LC32NativeSetWindowRootViewController(
UIWindow *window, UIViewController *controller);
void LC32NativeSetWindowFrame(UIWindow *window, CGRect frame);
UIViewController *LC32GuestWindowRootViewController(UIWindow *window);
void LC32InstallGuestWindowRootViewController(
UIWindow *window, UIViewController *controller,
LC32LegacyIPadGeometryMode geometryMode);
UIInterfaceOrientation LC32LegacyTargetOrientation(
UIViewController *controller);
bool LC32WindowNeedsLegacyPhoneCanvas(
UIWindow *window, UIViewController *controller);
bool LC32WindowNeedsImmediateLegacyPhoneCanvas(
UIWindow *window, UIViewController *controller);
bool LC32FitLegacyDirectWindowLayers(UIWindow *window);
void LC32RestoreRootlessRendererAutoresizing(UIWindow *window);
bool LC32TransformNearlyEquals(
CGAffineTransform left, CGAffineTransform right);
UIInterfaceOrientation LC32LegacyRootWindowGeometry(
UIView *view, bool requireGuestLandscapeBounds,
UIWindow *installingWindow = nil, UIViewController *installingRoot = nil);
void LC32FitLegacyControllerRoot(UIView *view);
bool LC32GeometryModePreservesPhoneCanvas(
LC32LegacyIPadGeometryMode geometryMode) {
return geometryMode ==
LC32LegacyIPadGeometryModePreservePhonePortraitCanvas ||
geometryMode ==
LC32LegacyIPadGeometryModePreservePhoneLandscapeCanvas;
}
LC32LegacyIPadContainerController *LC32LegacyContainerForWindow(
UIWindow *window) {
UIViewController *root = LC32NativeWindowRootViewController(window);
return [root isKindOfClass:LC32LegacyIPadContainerController.class]
? (LC32LegacyIPadContainerController *)root : nil;
}
struct LC32LegacyCanvasPolicy {
LC32LegacyIPadCanvasKind kind;
bool usesFixedLandscapeIPadCanvas;
bool usesFixedLandscapePhoneCanvas;
bool mayRetainLegacyLandscapePhoneCanvas;
};
const LC32LegacyCanvasPolicy& LC32GuestLegacyCanvasPolicy(void) {
static LC32LegacyCanvasPolicy result = {
LC32LegacyIPadCanvasNone,
false,
false,
false,
};
const char *guestExecutable = getenv("LC32_GUEST_EXECUTABLE");
/* UIKit can create internal windows while the shim dylib is loading.
* Do not consume the cache until LC32RunGuest has published the guest. */
if(!guestExecutable || !guestExecutable[0]) return result;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSString *path = [NSString stringWithUTF8String:
getenv("LC32_GUEST_EXECUTABLE")];
NSBundle *bundle = [NSBundle bundleWithPath:
path.stringByDeletingLastPathComponent];
result.kind = LC32BundleLegacyIPadCanvasKind(
bundle, LC32GetGuestExecutableSDKVersion());
result.usesFixedLandscapeIPadCanvas =
LC32BundleUsesFixedLandscapeIPadCanvas(bundle, result.kind);
result.usesFixedLandscapePhoneCanvas =
LC32BundleUsesFixedLandscapePhoneCanvas(
bundle, LC32GetGuestExecutableSDKVersion());
result.mayRetainLegacyLandscapePhoneCanvas =
LC32BundleMayRetainLegacyLandscapePhoneCanvas(
bundle, LC32GetGuestExecutableSDKVersion());
});
return result;
}
LC32LegacyIPadCanvasKind LC32GuestLegacyIPadCanvasKind(void) {
return LC32GuestLegacyCanvasPolicy().kind;
}
bool LC32GuestNeedsLegacyIPadCanvas(void) {
return LC32GuestLegacyIPadCanvasKind() != LC32LegacyIPadCanvasNone;
}
bool LC32GuestUsesFixedLandscapeIPadCanvas(void) {
return LC32GuestLegacyCanvasPolicy().usesFixedLandscapeIPadCanvas;
}
bool LC32GuestUsesFixedLandscapePhoneCanvas(void) {
return LC32GuestLegacyCanvasPolicy()
.usesFixedLandscapePhoneCanvas;
}
bool LC32GuestMayRetainLegacyLandscapePhoneCanvas(void) {
return LC32GuestLegacyCanvasPolicy()
.mayRetainLegacyLandscapePhoneCanvas;
}
Class LC32NativeWindowDispatchClass(UIWindow *window) {
Class dispatchClass = object_getClass(window);
while(dispatchClass && [(id)dispatchClass isGuestClass]) {
dispatchClass = class_getSuperclass(dispatchClass);
}
return dispatchClass;
}
UIViewController *LC32NativeWindowRootViewController(UIWindow *window) {
Class dispatchClass = LC32NativeWindowDispatchClass(window);
if(!window || !dispatchClass) return nil;
struct objc_super superInfo = {window, dispatchClass};
using GetRootViewController =
UIViewController *(*)(struct objc_super *, SEL);
return reinterpret_cast<GetRootViewController>(objc_msgSendSuper)(
&superInfo, @selector(rootViewController));
}
void LC32NativeSetWindowRootViewController(
UIWindow *window, UIViewController *controller) {
Class dispatchClass = LC32NativeWindowDispatchClass(window);
if(!window || !dispatchClass) return;
if(LC32UIKitLegacyCompatibilityEnabled() &&
![controller isKindOfClass:LC32LegacyWindowRootController.class]) {
LC32RestoreRootlessRendererAutoresizing(window);
}
struct objc_super superInfo = {window, dispatchClass};
using SetRootViewController =
void (*)(struct objc_super *, SEL, UIViewController *);
reinterpret_cast<SetRootViewController>(objc_msgSendSuper)(
&superInfo, @selector(setRootViewController:), controller);
}
void LC32NativeSetWindowFrame(UIWindow *window, CGRect frame) {
Class dispatchClass = LC32NativeWindowDispatchClass(window);
if(!window || !dispatchClass) return;
using SetFrame = void (*)(id, SEL, CGRect);
SetFrame setter = reinterpret_cast<SetFrame>(
class_getMethodImplementation(dispatchClass, @selector(setFrame:)));
setter(window, @selector(setFrame:), frame);
}
bool LC32WindowNeedsLegacyIPadContainer(UIWindow *window) {
if(!window || !LC32GuestNeedsLegacyIPadCanvas()) return false;
const CGRect hostBounds = LC32WindowSceneBounds(window);
const CGFloat shortEdge = MIN(hostBounds.size.width,
hostBounds.size.height);
return shortEdge > 0 && shortEdge < 600;
}
UIInterfaceOrientation LC32LegacyTargetOrientation(
UIViewController *controller) {
const UIInterfaceOrientation requested = (UIInterfaceOrientation)
LC32LegacyRequestedOrientation.load(std::memory_order_relaxed);
if(LC32MaskForInterfaceOrientation(requested)) return requested;
const LC32GuestUIKitPolicy &policy = LC32GuestInterfacePolicy();
const UIInterfaceOrientation settled =
LC32SettledLegacyOrientation(
controller, UIInterfaceOrientationMaskAll);
if(settled != UIInterfaceOrientationUnknown) return settled;
if(LC32MaskForInterfaceOrientation(policy.preferredOrientation)) {
return policy.preferredOrientation;
}
return LC32FirstOrientationInMask(policy.declaredOrientations);
}
UIViewController *LC32GuestWindowRootViewController(UIWindow *window) {
UIViewController *root = LC32NativeWindowRootViewController(window);
if([root isKindOfClass:LC32LegacyIPadContainerController.class]) {
root = ((LC32LegacyIPadContainerController *)root)
.guestContentController;
}
return [root isKindOfClass:LC32LegacyWindowRootController.class]
? nil : root;
}
void LC32InstallGuestWindowRootViewController(
UIWindow *window, UIViewController *controller,
LC32LegacyIPadGeometryMode geometryMode) {
if(!window || !window.guest_selfOrNull) return;
LC32LegacyIPadContainerController *container =
LC32LegacyContainerForWindow(window);
const bool requestsPhoneCanvas =
LC32GeometryModePreservesPhoneCanvas(geometryMode);
const bool preservesInstalledPhoneCanvas = container &&
LC32GeometryModePreservesPhoneCanvas(container.geometryMode);
const bool needsPhoneCanvas = requestsPhoneCanvas &&
(preservesInstalledPhoneCanvas ||
LC32WindowNeedsLegacyPhoneCanvas(window, controller));
const bool needsContainer = controller &&
(LC32WindowNeedsLegacyIPadContainer(window) || needsPhoneCanvas);
if(!needsContainer) {
/* nil uninstalls the compatibility root. If the scene no longer
* needs classic-iPad virtualization, detach the child before
* promoting it back to UIWindow.rootViewController. */
#if !__has_feature(objc_arc)
[controller retain];
#endif
if(container) {
[container setGuestContentController:nil
geometryMode:geometryMode];
}
UIView *rootView = nil;
LC32NativeViewIfLoaded(controller, &rootView);
const UIInterfaceOrientation oldRootOrientation = rootView
? LC32LegacyRootWindowGeometry(rootView, true, window, controller)
: UIInterfaceOrientationUnknown;
LC32NativeSetWindowRootViewController(window, controller);
if(oldRootOrientation) {
/* Capture before UIKit's initial root layout can transpose the
* guest's already-landscape bounds. Unattached renderers perform
* their old orientation setup before setRootViewController:. */
objc_setAssociatedObject(rootView, LC32LegacyRootWindowGeometryKey,
@(oldRootOrientation), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
dispatch_async(dispatch_get_main_queue(), ^{
LC32FitLegacyControllerRoot(rootView);
});
}
#if !__has_feature(objc_arc)
[controller release];
#endif
return;
}
if(!container) {
/* Retain across replacing UIWindow's old root: UIKit is allowed to
* release that controller as part of the assignment. Install an
* empty native container first so addChildViewController: never sees
* a controller which is simultaneously UIWindow's root. */
#if !__has_feature(objc_arc)
[controller retain];
#endif
container = [[LC32LegacyIPadContainerController alloc]
initWithGuestContentController:nil geometryMode:geometryMode];
LC32NativeSetWindowRootViewController(window, container);
[container setGuestContentController:controller
geometryMode:geometryMode];
#if !__has_feature(objc_arc)
[controller release];
[container release];
#endif
} else {
[container setGuestContentController:controller
geometryMode:geometryMode];
}
LC32ScaleLegacyIPadWindow(window);
}
CGRect LC32WindowSceneBounds(UIWindow *window) {
UIWindowScene *scene = window.windowScene;
/* Keep this helper in scene coordinates for eligibility and orientation
* policy. Canvas placement uses LC32LegacyViewportInView below, which
* preserves the source coordinate space instead of copying raw numbers. */
id<UICoordinateSpace> coordinateSpace = nil;
if(@available(iOS 26.0, *)) {
coordinateSpace = (id<UICoordinateSpace>)LC32ObjectProperty(
scene.effectiveGeometry, "coordinateSpace");
if(coordinateSpace) return coordinateSpace.bounds;
}
coordinateSpace = scene.coordinateSpace;
if(coordinateSpace) return coordinateSpace.bounds;
return (window.screen ?: UIScreen.mainScreen).bounds;
}
bool LC32WindowNeedsLegacyPhoneCanvas(
UIWindow *window, UIViewController *controller) {
if(!window || !window.guest_selfOrNull || !controller ||
!LC32ObjectUsesGuestClass(controller) ||
LC32GuestNeedsLegacyIPadCanvas()) {
return false;
}
if(LC32GuestUsesFixedLandscapePhoneCanvas()) {
/* The bundle classifier already restricts this to pre-iPhone-5,
* landscape-only phone apps without tall launch art. They need the
* legacy compositor even when Classic Mode exposes exactly 480x320. */
return true;
}
if(!LC32GuestMayRetainLegacyLandscapePhoneCanvas()) {
return false;