/
UIView.mm
3858 lines (3247 loc) · 114 KB
/
UIView.mm
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
//******************************************************************************
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//******************************************************************************
#import <StubReturn.h>
#import "Starboard.h"
#import <UIKit/UIApplication.h>
#import <UIKit/UIGraphics.h>
#import <UIKit/UIImage.h>
#import <UIKit/UIImageView.h>
#import <UIKit/UILayoutGuide.h>
#import <UIKit/UINavigationController.h>
#import <UIKit/UITextField.h>
#import <UIKit/UIView.h>
#import <UIKit/UIWindow.h>
#import <UIKit/UIGestureRecognizerSubclass.h>
#import <UIKit/UILongPressGestureRecognizer.h>
#import <UIKit/UIPinchGestureRecognizer.h>
#import <UIKit/UISwipeGestureRecognizer.h>
#import <UIKit/UITapGestureRecognizer.h>
#import "UIAnimationNotification.h"
#import "UIAppearanceSetter.h"
#import "UIViewInternal.h"
#import "UIWindowInternal.h"
#import "UIViewControllerInternal.h"
#import "UIGestureRecognizerInternal.h"
#import "CACompositor.h"
#import "CALayerInternal.h"
#import "CAAnimationInternal.h"
#import "CGContextInternal.h"
#import <AutoLayout.h>
#import <NSLayoutConstraint+AutoLayout.h>
#import "NSLayoutAnchorInternal.h"
#import <UILayoutGuide+AutoLayout.h>
#import <UIView+AutoLayout.h>
#import <windows.h>
#import <LoggingNative.h>
#import <NSLogging.h>
#import <objc/blocks_runtime.h>
#import "UIEventInternal.h"
#import "UITouchInternal.h"
#import "_UIDirectManipulationRecognizer.h"
#import "_UIGestureCoordinator.h"
#import "StringHelpers.h"
#import "CppWinRTHelpers.h"
#import <QuartzCore/CABasicAnimation.h>
#import <QuartzCore/CALayer.h>
#import <QuartzCore/CAMediaTimingFunction.h>
#import <QuartzCore/CATransition.h>
#import <QuartzCore/CoreAnimationFunctions.h>
#include "COMIncludes.h"
#import <winrt/Windows.UI.Xaml.Automation.h>
#include "COMIncludes_End.h"
#import <math.h>
#import <string>
using namespace winrt::Windows::UI::Xaml;
using namespace winrt::Windows::UI::Input;
namespace WF = winrt::Windows::Foundation;
@class UIAppearanceSetter;
static const wchar_t* TAG = L"UIView";
static const bool DEBUG_ALL = false;
static const bool DEBUG_TOUCHES_VERBOSE = DEBUG_ALL || false;
static const bool DEBUG_TOUCHES = DEBUG_TOUCHES_VERBOSE || false;
static const bool DEBUG_TOUCHES_LIGHT = DEBUG_TOUCHES || false;
static const bool DEBUG_HIT_TESTING = DEBUG_ALL || false;
static const bool DEBUG_HIT_TESTING_LIGHT = DEBUG_HIT_TESTING || false;
static const bool DEBUG_LAYOUT = DEBUG_ALL || false;
const CGFloat UIViewNoIntrinsicMetric = -1.0f;
/** @Status Stub */
const CGSize UILayoutFittingCompressedSize = StubConstant();
/** @Status Stub */
const CGSize UILayoutFittingExpandedSize = StubConstant();
BOOL g_alwaysSendViewEvents = TRUE;
int g_animationsDisabled = 0, g_nestedAnimationsDisabled = 0;
BOOL g_presentingAnimated = FALSE;
typedef void (^animationBlockFunc)(void);
typedef void (^completionBlockFunc)(BOOL);
#define CALLBLOCK(b) b()
#define CALLCOMPLETIONBLOCK(b, finished) b(finished)
#define COPYBLOCK(b) Block_copy(b)
typedef struct {
int _numAnimations;
double _animationDuration;
double _animationDelay;
id _animationDelegate;
idretaint<CAMediaTimingFunction> _animationCurve;
id _animationID;
void* _context;
SEL _animationWillStartSelector;
SEL _animationDidStopSelector;
BOOL _autoReverses;
BOOL _beginsFromCurrentState;
float _repeatCount;
UIAnimationNotification* _animationNotifier;
completionBlockFunc _completionBlock;
} AnimationProperties;
static AnimationProperties _animationProperties[32];
static int stackLevel = 0;
int viewCount = 0;
@implementation UIView {
idretaintype(CALayer) layer;
bool _deallocating;
}
@synthesize preferredFocusedView;
@synthesize traitCollection;
@synthesize collisionBoundsType;
@synthesize collisionBoundingPath;
// Struct which binds a static UITouch instance to a XAML pointer id.
// TouchPoints are created on-demand (in touchPointFromPointerId below),
// and they are bound to a single XAML pointer id for the remainder of the app lifetime.
struct TouchPoint {
static const int s_invalidPointerId = -1;
int pointerId = s_invalidPointerId;
bool isPressed = false;
StrongId<UITouch> touch;
};
// The collection of static touchpoints we'll use for the duration of this app.
TouchPoint s_touchPoints[10] = {};
// Returns a static TouchPoint instance for the given pointerId. Creates one if it doesn't already exist.
static TouchPoint& _touchPointFromPointerId(int pointerId) {
// Look for an existing entry for this pointer id
for (auto& touchPoint : s_touchPoints) {
if (touchPoint.pointerId == pointerId) {
return touchPoint;
}
}
// No existing entry found, so reserve one
for (auto& touchPoint : s_touchPoints) {
if (touchPoint.pointerId == TouchPoint::s_invalidPointerId) {
touchPoint.pointerId = pointerId;
// Allocate a UITouch instance for this entry if necessary
if (!touchPoint.touch) {
touchPoint.touch.attach([UITouch _createWithPoint:CGPointMake(0, 0)]);
}
return touchPoint;
}
}
// Out of touch points!
FAIL_FAST();
}
// Reset the given touch point, making it available for reuse on further touch events
static void _resetTouchPoint(TouchPoint& touchPoint) {
if (DEBUG_TOUCHES_VERBOSE) {
TraceVerbose(TAG, L"Resetting touch point: %d.", touchPoint.pointerId);
}
touchPoint.touch->_view = nil;
touchPoint.pointerId = TouchPoint::s_invalidPointerId;
}
static std::string _printViewhierarchy(UIView* leafView) {
std::string logString;
char buffer[1024];
for (UIView* current = leafView; current != nil; current = current->priv->superview) {
int charactersWritten = sprintf_s(&buffer[0],
ARRAYSIZE(buffer) - 1, // Leave room for our null terminator
"%hs(0x%p, _isHitTestable=%hs, XAML_HitTestable=%hs)<-",
object_getClassName(current),
current,
[current _isHitTestable] ? "true" : "false",
current.layer._xamlElement.IsHitTestVisible() ? "true" : "false");
buffer[charactersWritten] = '\0';
logString += buffer;
}
return logString;
}
- (UIView*)_doHitTest:(UITouch*)touch allTouches:(NSMutableSet<UITouch*>*)allTouches {
if (!DEBUG_HIT_TESTING_LIGHT && !UIApplication.displayMode.useLegacyHitTesting) {
// Don't do any unneeded work
return self;
}
// Create a temp event solely for hit-testing purposes
UIEvent* hitTestEvent = [[UIEvent _createWithTouches:allTouches forNewTouch:touch] autorelease];
// Perform a hit test starting at the owning window
UIWindow* rootWindow = [self _getWindowInternal];
CGPoint point = { touch->_touchX, touch->_touchY };
point = [rootWindow _convertPoint:point fromView:rootWindow toView:rootWindow];
UIView* hitTestResult = [rootWindow hitTest:point withEvent:hitTestEvent];
if (hitTestResult && (hitTestResult != self)) {
if (DEBUG_HIT_TESTING_LIGHT) {
std::string selfTree = _printViewhierarchy(self);
std::string hitTestTree = _printViewhierarchy(hitTestResult);
TraceWarning(TAG,
L"XAML's chosen hit test view: \r\n\t %hs \r\n ...does not match the legacy hit test results: \r\n\t %hs.",
selfTree.c_str(),
hitTestTree.c_str());
}
// Note: This functionality will be deprecated in future releases
if (UIApplication.displayMode.useLegacyHitTesting) {
TraceWarning(TAG,
L"Returning legacy hit test view %hs(0x%p) because UIApplication.displayMode.useLegacyHitTesting is enabled.",
object_getClassName(hitTestResult),
hitTestResult);
return hitTestResult;
}
}
// By default, use 'self' even if the hit test didn't match up
return self;
}
- (UITouchPhase)_processPointerEvent:(const Input::PointerRoutedEventArgs&)pointerEventArgs forTouchPhase:(UITouchPhase)touchPhase {
// The collection of active touches reused for the duration of this app
static StrongId<NSMutableSet<UITouch*>> s_allTouches = [NSMutableSet<UITouch*> set];
// The touch event we'll reuse for the duration of this app
static StrongId<UIEvent> s_touchEvent = [[UIEvent alloc] init];
// Grab our owning window so we can translate the touch point to its coordinate space.
UIWindow* owningWindow = [self _getWindowInternal];
// Sometimes we're seeing touches for Views that don't have a parent; we should probably track this down at some point,
// as these Views should probably be temporarily hit-test disabled during the transition.
// At least log for now in case we see any strange behavior that results from this.
if (!owningWindow) {
TraceVerbose(TAG,
L"Touched view %hs(0x%p) for phase %d doesn't have a parent window with which to translate the touch point "
L"coordinates; falling back to XAML's root coordinate space.",
object_getClassName(self),
self,
touchPhase);
}
// Get the point value in this view's parent UIWindow's coordinates
UIElement owningWindowElement = nullptr;
if (GetCACompositor()->IsRunningAsFramework()) {
// In framework mode there's no meaningful parent UIWindow
owningWindowElement = Window::Current().Content();
} else if (owningWindow != nil) {
owningWindowElement = owningWindow.layer._xamlElement;
}
PointerPoint pointerPoint = pointerEventArgs.GetCurrentPoint(owningWindowElement);
// Locate the static TouchPoint object for this pointerId
TouchPoint& touchPoint = _touchPointFromPointerId(pointerPoint.PointerId());
// Ignore move events if the pointer isn't pressed
if ((touchPhase != UITouchPhaseBegan) && !touchPoint.isPressed) {
if (DEBUG_TOUCHES_VERBOSE) {
TraceVerbose(TAG, L"Touch point not pressed; ignoring touch event for phase:%d.", touchPhase);
}
// Reset the touch point since we don't need it
_resetTouchPoint(touchPoint);
return UITouchPhaseCancelled;
}
// Update the touch info for this pointer event
// Also, adding pointerEventArgs to the specific Touch so that it can be used in UIButton's touchesBegan:withEvent method
// to mark the event as unhandled
[touchPoint.touch _updateWithPoint:pointerPoint routedEventArgs:pointerEventArgs forPhase:touchPhase];
// Preprocess pointer event
SEL touchEventName;
switch (touchPhase) {
case UITouchPhaseBegan:
// Toggle the touchPoint's pressed state
touchPoint.isPressed = true;
// Add this touch to the set of all current touches in the app
[s_allTouches addObject:touchPoint.touch];
if (DEBUG_HIT_TESTING_LIGHT) {
TraceVerbose(TAG, L"Hit testing view %hs(0x%p).", object_getClassName(self), self);
}
// Update the hit-tested view. (Only one owner per UITouch lifetime)
touchPoint.touch->_view = [self _doHitTest:touchPoint.touch allTouches:s_allTouches];
// Assign the correct selector
touchEventName = @selector(touchesBegan:withEvent:);
break;
case UITouchPhaseMoved:
// Assign the correct selector
touchEventName = @selector(touchesMoved:withEvent:);
break;
case UITouchPhaseEnded:
// Assign the correct selector
touchEventName = @selector(touchesEnded:withEvent:);
touchPoint.isPressed = false;
break;
case UITouchPhaseCancelled:
// Assign the correct selector
touchEventName = @selector(touchesCancelled:withEvent:);
touchPoint.isPressed = false;
break;
default:
FAIL_FAST();
}
// Keep the static touch event up to date
[s_touchEvent _updateWithTouches:s_allTouches touchEvent:touchPoint.touch];
// Run through GestureCoordinator to fire appropriate gestures
bool touchCanceled =
[[_UIGestureCoordinator singleton] processGesturesForTouch:touchPoint.touch event:s_touchEvent touchEventName:touchEventName];
// The gesture was recognized, so cancel any current touches on the view (including this touch)
if (touchCanceled) {
touchPoint.touch->_phase = UITouchPhaseCancelled;
touchEventName = @selector(touchesCancelled:withEvent:);
}
if (!touchPoint.touch->_view) {
// Ignore if the pointer isn't captured
if (DEBUG_TOUCHES_LIGHT) {
TraceVerbose(TAG, L"View for touch is nil!, ignoring touch for touchPhase %d.", touchPhase);
}
} else if (touchPhase != UITouchPhaseBegan && ![touchPoint.touch->_view->priv->currentTouches containsObject:touchPoint.touch]) {
// Ignore if the pointer isn't captured
if (DEBUG_TOUCHES_LIGHT) {
TraceVerbose(TAG,
L"View %hs(0x%p) not aware of touch, ignoring touch for touchPhase %d.",
object_getClassName(touchPoint.touch->_view),
static_cast<UIView*>(touchPoint.touch->_view),
touchPhase);
}
} else if (touchPhase == UITouchPhaseBegan && !touchPoint.touch->_view->priv->multipleTouchEnabled &&
([touchPoint.touch->_view->priv->currentTouches count] > 0)) {
// Ignore if we already have a touch for this view and !multipleTouchEnabled
if (DEBUG_TOUCHES_LIGHT) {
TraceVerbose(TAG,
L"View %hs(0x%p) already has a touch, ignoring this subsequent touch due to !multipleTouchEnabled.",
object_getClassName(touchPoint.touch->_view),
static_cast<UIView*>(touchPoint.touch->_view));
}
} else {
// Prepare to send the event to the target view
NSMutableSet* touchesForEvent;
switch (touchPoint.touch->_phase) {
case UITouchPhaseBegan:
// Track the touch in this view
[touchPoint.touch->_view->priv->currentTouches addObject:touchPoint.touch];
if (DEBUG_TOUCHES_LIGHT) {
TraceVerbose(TAG,
L"Firing UITouchPhaseBegan to %hs(0x%p).",
object_getClassName(touchPoint.touch->_view),
static_cast<UIView*>(touchPoint.touch->_view));
}
// Use this sole touch for the event we send to the view
touchesForEvent = [NSMutableSet setWithObject:touchPoint.touch];
break;
case UITouchPhaseMoved:
if (DEBUG_TOUCHES_LIGHT) {
TraceVerbose(TAG,
L"Firing UITouchPhaseMoved to %hs(0x%p).",
object_getClassName(touchPoint.touch->_view),
static_cast<UIView*>(touchPoint.touch->_view));
}
// There was a time we used *all* of the view's current tracked touches for the event, rather than one
// at a time. We likely chose this because the iOS input stack was grouping touches together, however
// that no longer appears to be the case. Grouping them causes a problem when a new touch begins,
// another moves, and both were sent as a move, causing previousLocationInView to return bogus results.
touchesForEvent = [NSMutableSet setWithObject:touchPoint.touch];
break;
case UITouchPhaseEnded:
case UITouchPhaseCancelled:
if (DEBUG_TOUCHES_LIGHT) {
TraceVerbose(TAG,
L"Firing %hs to %hs(0x%p).",
(touchPoint.touch->_phase == UITouchPhaseEnded) ? "UITouchPhaseEnded" : "UITouchPhaseCancelled",
object_getClassName(touchPoint.touch->_view),
static_cast<UIView*>(touchPoint.touch->_view));
}
// Remove the touch point from the view
[touchPoint.touch->_view->priv->currentTouches removeObject:touchPoint.touch];
// Use this sole touch for the event we send to the view
touchesForEvent = [NSMutableSet setWithObject:touchPoint.touch];
break;
default:
break;
}
// Send the appropriate event to the hit test view
[touchPoint.touch->_view performSelector:touchEventName withObject:touchesForEvent withObject:s_touchEvent];
}
// Final cleanup based on the actual pointer event (not the coerced event after running through gestures)
switch (touchPhase) {
case UITouchPhaseEnded:
case UITouchPhaseCancelled: {
if (DEBUG_TOUCHES) {
TraceVerbose(TAG, L"Final cleanup for touch point %d, due to touch phase %d.", touchPoint.pointerId, touchPhase);
}
// Clean up s_allTouches as this is no longer a valid touch point
[s_allTouches removeObject:touchPoint.touch];
// Reset the touch point since we're no longer tracking it
_resetTouchPoint(touchPoint);
/////////////////////////////////////////////////////////////////////////////
// TODO: This block will be removed once we move to WinRT gesture recognizers
// If all fingers come off the screen, reset all gestures
BOOL shouldResetTrackingGesturesList = YES;
for (auto& touchPoint : s_touchPoints) {
if (touchPoint.touch && touchPoint.touch->_view) {
shouldResetTrackingGesturesList = NO;
}
}
if (shouldResetTrackingGesturesList) {
[[_UIGestureCoordinator singleton] resetTrackingGestureList];
}
// TODO: This block will be removed once we move to WinRT gesture recognizers
/////////////////////////////////////////////////////////////////////////////
} break;
default:
break;
}
// Clear out the stored _pointerPoint on the touch for this event since we shouldn't hold onto them
touchPoint.touch->_pointerPoint = nullptr;
// Return the coerced UITouchPhase to the caller
return touchPoint.touch->_phase;
}
// Calculate whether or not this view should be hit testable
- (BOOL)_isHitTestable {
if (!priv->userInteractionEnabled) {
if (DEBUG_HIT_TESTING) {
TraceVerbose(TAG,
L"_isHitTestable returning NO for %hs(0x%p) because !priv->userInteractionEnabled.",
object_getClassName(self),
self);
}
return NO;
}
if ([self isHidden]) {
if (DEBUG_HIT_TESTING) {
TraceVerbose(TAG, L"_isHitTestable returning NO for %hs(0x%p) because [self isHidden].", object_getClassName(self), self);
}
return NO;
}
if ([self alpha] <= 0.01f) {
if (DEBUG_HIT_TESTING) {
TraceVerbose(TAG, L"_isHitTestable returning NO for %hs(0x%p) because [self alpha] <= 0.01f.", object_getClassName(self), self);
}
return NO;
}
return YES;
}
// Update hit test state on our backing XAML element
- (void)_updateHitTestability {
// Should we currently be hit testable?
BOOL isHitTestable = [self _isHitTestable];
if (DEBUG_HIT_TESTING) {
if (self.layer._xamlElement.IsHitTestVisible() != isHitTestable) {
TraceVerbose(TAG,
L"Changing the XAML element for %hs(0x%p) to hit-testable=%hs.",
object_getClassName(self),
self,
isHitTestable ? "true" : "false");
} else {
TraceVerbose(TAG,
L"The XAML element for %hs(0x%p) is already set to hit-testable=%hs.",
object_getClassName(self),
self,
isHitTestable ? "true" : "false");
}
}
// Update our _xamlElement as needed
self.layer._xamlElement.IsHitTestVisible(isHitTestable);
}
- (void)_initPrivWithFrame:(CGRect)frame xamlElement:(RTObject*)xamlElement {
// Nothing to do if we're already initialized
if (self->priv) {
return;
}
if (DEBUG_LAYOUT) {
TraceVerbose(TAG,
L"[%f,%f] @ %fx%f",
(float)frame.origin.x,
(float)frame.origin.y,
(float)frame.size.width,
(float)frame.size.height);
}
viewCount++;
// If we don't have a backing xamlElement, create one for this UIView type
if (!xamlElement) {
xamlElement = [[self class] createXamlElement];
}
// Create and initialize our backing presentation layer
if (!xamlElement) {
// No Xaml element was specified, so default layer init is fine
self->layer.attach([[[[self class] layerClass] alloc] init]);
} else {
// A Xaml element was specified, so we must initialize the layer with this backing xaml element
FrameworkElement element = objcwinrt::from_rtobj<FrameworkElement>(xamlElement);
self->layer.attach([[[[self class] layerClass] alloc] _initWithXamlElement:element]);
}
[self->layer setDelegate:self];
// Create the private backing object
self->priv = new UIViewPrivateState(self);
// Configure autolayout
static bool isAutoLayoutInitialized = InitializeAutoLayout();
[self autoLayoutAlloc];
// Set the XAML element's name so it's easily found in the VS live tree viewer
auto elementName = Strings::NarrowToWide<HSTRING>(object_getClassName(self));
self.layer._xamlElement.Name(winrt::hstring_view(elementName.Get()));
// Subscribe to the XAML node's input events
self->priv->_pointerPressedEventRegistration =
self.layer._xamlElement.PointerPressed(objcwinrt::callback([self] (const WF::IInspectable& sender, const Input::PointerRoutedEventArgs& e) {
// Capture the pointer within this xaml element
if (!self.layer._xamlElement.CapturePointer(e.Pointer())) {
TraceWarning(TAG, L"Failed to capture pointer...");
}
// Set the event to handled, then process it as a UITouch
e.Handled(true);
[self _processPointerEvent:e forTouchPhase:UITouchPhaseBegan];
}));
self->priv->_pointerMovedEventRegistration =
self.layer._xamlElement.PointerMoved(objcwinrt::callback([self] (const WF::IInspectable& sender, const Input::PointerRoutedEventArgs& e) {
// Set the event to handled, then process it as a UITouch
e.Handled(true);
[self _processPointerEvent:e forTouchPhase:UITouchPhaseMoved];
}));
self->priv->_pointerReleasedEventRegistration =
self.layer._xamlElement.PointerReleased(objcwinrt::callback([self] (const WF::IInspectable& sender, const Input::PointerRoutedEventArgs& e) {
// Set the event to handled, then process it as a UITouch
e.Handled(true);
[self _processPointerEvent:e forTouchPhase:UITouchPhaseEnded];
// release the pointer capture
self.layer._xamlElement.ReleasePointerCapture(e.Pointer());
}));
self->priv->_pointerCanceledEventRegistration =
self.layer._xamlElement.PointerCanceled(objcwinrt::callback([self] (const WF::IInspectable& sender, const Input::PointerRoutedEventArgs& e) {
// Set the event to handled, then process it as a UITouch
e.Handled(true);
// Uncommon event; we'll use the same handling as pointer capture lost (below)
[self _processPointerEvent:e forTouchPhase:UITouchPhaseCancelled];
}));
self->priv->_pointerCaptureLostEventRegistration =
self.layer._xamlElement.PointerCaptureLost(objcwinrt::callback([self] (const WF::IInspectable& sender, const Input::PointerRoutedEventArgs& e) {
// Set the event to handled, then process it as a UITouch
e.Handled(true);
// Treat capture lost just like a pointer canceled (which is actually quite uncommon)
[self _processPointerEvent:e forTouchPhase:UITouchPhaseCancelled];
}));
}
/**
@Public No
*/
- (void)initAccessibility {
self.isAccessibilityElement = NO;
self.accessibilityTraits = UIAccessibilityTraitNone;
[self updateAccessibility];
}
/**
@Public No
*/
- (void)updateAccessibility {
IWUpdateAccessibility(self.layer, self);
}
/**
@Status Interoperable
*/
- (instancetype)initWithFrame:(CGRect)frame {
// Run on the main thread because the underlying XAML objects can only be
// called from the UI thread
RunSynchronouslyOnMainThread(^{
[self _initPrivWithFrame:frame xamlElement:nil];
// Default state
[self setOpaque:TRUE];
[self setFrame:frame];
[self setNeedsDisplay];
[self initAccessibility];
});
return self;
}
/**
Microsoft extension
*/
- (instancetype)initWithFrame:(CGRect)frame xamlElement:(RTObject*)xamlElement {
// Run on the main thread because the underlying XAML objects can only be
// called from the UI thread
RunSynchronouslyOnMainThread(^{
[self _initPrivWithFrame:frame xamlElement:xamlElement];
// Default state
[self setOpaque:TRUE];
[self setFrame:frame];
[self setNeedsDisplay];
[self initAccessibility];
});
return self;
}
/**
@Status Interoperable
*/
- (instancetype)init {
CGRect pos;
pos.origin.x = 0;
pos.origin.y = 0;
pos.size.width = 0;
pos.size.height = 0;
return [self initWithFrame:pos];
}
#define PAUSE_ANIMATIONS() g_nestedAnimationsDisabled++;
#define CONTINUE_ANIMATIONS() \
g_nestedAnimationsDisabled--; \
if (g_nestedAnimationsDisabled < 0) \
g_nestedAnimationsDisabled = 0;
/**
@Status Caveat
@Notes May not be fully implemented
*/
- (instancetype)initWithCoder:(NSCoder*)coder {
// Init priv, get our backing Xaml element, etc.
[self _initPrivWithFrame:CGRectZero xamlElement:nil];
CGRect bounds;
id boundsObj = [coder decodeObjectForKey:@"UIBounds"];
if (boundsObj != nil) {
if ([boundsObj isKindOfClass:[NSString class]]) {
bounds = CGRectFromString(boundsObj);
} else {
memcpy(&bounds, reinterpret_cast<const char*>([boundsObj bytes]) + 1, sizeof(CGRect));
}
} else {
bounds.origin.x = 0;
bounds.origin.y = 0;
bounds.size.width = 0;
bounds.size.height = 0;
}
CGPoint center;
id centerObj = [coder decodeObjectForKey:@"UICenter"];
if (centerObj) {
if ([centerObj isKindOfClass:[NSString class]]) {
center = CGPointFromString(centerObj);
} else {
memcpy(¢er, reinterpret_cast<const char*>([centerObj bytes]) + 1, sizeof(CGPoint));
}
} else {
center.x = 0;
center.y = 0;
}
PAUSE_ANIMATIONS();
[self setBounds:bounds];
[self setCenter:center];
[self setNeedsDisplay];
if ([coder containsValueForKey:@"UIAlpha"]) {
float val = [coder decodeFloatForKey:@"UIAlpha"];
[self setAlpha:val];
}
if ([coder containsValueForKey:@"UIContentStretch"]) {
CGRect rect;
id obj = [coder decodeObjectForKey:@"UIContentStretch"];
if ([obj isKindOfClass:[NSString class]]) {
rect = CGRectFromString(obj);
} else {
memcpy(&rect, (char*)[obj bytes] + 1, sizeof(CGRect));
}
[self setContentStretch:rect];
}
CONTINUE_ANIMATIONS();
if ([coder decodeInt32ForKey:@"UIUserInteractionDisabled"]) {
[self setUserInteractionEnabled:NO];
}
self.contentMode = (UIViewContentMode)[coder decodeInt32ForKey:@"UIContentMode"];
id uiDelegate = [coder decodeObjectForKey:@"UIDelegate"];
if (uiDelegate != nil) {
if ([self respondsToSelector:@selector(setDelegate:)]) {
[self performSelector:@selector(setDelegate:) withObject:uiDelegate];
} else {
TraceWarning(TAG, L"UIDelegate decoded but %hs(0x%p) doesn't support setDelegate!", object_getClassName(self), self);
}
}
NSArray* subviewsObj = [coder decodeObjectForKey:@"UISubviews"];
if (subviewsObj != nil) {
int count = [subviewsObj count];
for (int i = 0; i < count; i++) {
UIView* subView = [subviewsObj objectAtIndex:i];
[self addSubview:subView];
}
}
if ([coder containsValueForKey:@"UIViewDoesNotTranslateAutoresizingMaskIntoConstraints"]) {
priv->translatesAutoresizingMaskIntoConstraints =
![coder decodeInt32ForKey:@"UIViewDoesNotTranslateAutoresizingMaskIntoConstraints"];
}
if ([coder containsValueForKey:@"UIViewHorizontalHuggingPriority"]) {
priv->_contentHuggingPriority.width = [coder decodeFloatForKey:@"UIViewHorizontalHuggingPriority"];
}
if ([coder containsValueForKey:@"UIViewVerticalHuggingPriority"]) {
priv->_contentHuggingPriority.height = [coder decodeFloatForKey:@"UIViewVerticalHuggingPriority"];
}
if ([coder containsValueForKey:@"UIViewHorizontalCompressionResistancePriority"]) {
priv->_contentCompressionResistancePriority.width = [coder decodeFloatForKey:@"UIViewHorizontalCompressionResistancePriority"];
}
if ([coder containsValueForKey:@"UIViewVerticalCompressionResistancePriority"]) {
priv->_contentCompressionResistancePriority.height = [coder decodeFloatForKey:@"UIViewVerticalCompressionResistancePriority"];
}
if ([coder containsValueForKey:@"UIViewAutolayoutConstraints"]) {
NSArray* constraints = [coder decodeObjectForKey:@"UIViewAutolayoutConstraints"];
NSArray* removeConstraints = [coder decodeObjectForKey:@"_UILayoutGuideConstraintsToRemove"];
int count = [constraints count];
for (int i = 0; i < count; i++) {
NSLayoutConstraint* constraint = [constraints objectAtIndex:i];
if ([constraint isKindOfClass:[NSLayoutConstraint class]]) {
bool remove = false;
for (int i = 0; i < [removeConstraints count]; i++) {
NSLayoutConstraint* wayward = [removeConstraints objectAtIndex:i];
if (wayward == constraint) {
if (DEBUG_LAYOUT) {
NSTraceVerbose(TAG, @"Removing constraint (%@)", [wayward description]);
[wayward _printConstraint];
}
remove = true;
break;
}
}
if (![priv->constraints containsObject:constraint] && !remove) {
[priv->constraints addObject:constraint];
[constraint autoLayoutConstraintAddedToView:self];
}
} else {
NSTraceVerbose(TAG, @"Skipping unsupported constraint type: %@", [constraint description]);
}
}
}
if (DEBUG_LAYOUT) {
[NSLayoutConstraint _printConstraints:self.constraints];
}
[self setHidden:[coder decodeInt32ForKey:@"UIHidden"]];
priv->autoresizesSubviews = [coder decodeInt32ForKey:@"UIAutoresizeSubviews"];
priv->autoresizingMask = (UIViewAutoresizing)[coder decodeInt32ForKey:@"UIAutoresizingMask"];
priv->tag = [coder decodeInt32ForKey:@"UITag"];
priv->multipleTouchEnabled = [coder decodeInt32ForKey:@"UIMultipleTouchEnabled"];
[self setOpaque:[coder decodeInt32ForKey:@"UIOpaque"]];
[self setClipsToBounds:[coder decodeInt32ForKey:@"UIClipsToBounds"]];
UIColor* backgroundColor = [coder decodeObjectForKey:@"UIBackgroundColor"];
if (backgroundColor != nil) {
self.backgroundColor = backgroundColor;
}
NSArray* gestures = [coder decodeObjectForKey:@"gestureRecognizers"];
if (gestures != nil) {
TraceVerbose(TAG, L"UIView initWithCoder adding gesture recognizers");
[self setGestureRecognizers:gestures];
}
return self;
}
/**
@Status Interoperable
*/
- (void)encodeWithCoder:(NSCoder*)coder {
TraceWarning(TAG, L"Unsupported attempt to encode a UIView");
}
/**
@Status Interoperable
*/
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer*)gestureRecognizer {
return YES;
}
/**
@Status Interoperable
*/
- (NSArray*)layoutGuides {
return [[priv->_layoutGuides copy] autorelease];
}
/**
@Status Interoperable
*/
- (void)addLayoutGuide:(UILayoutGuide*)layoutGuide {
if (layoutGuide == nil) {
@throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"Cannot add nil UILayoutGuide!" userInfo:nil];
}
if (layoutGuide.owningView != self) {
[layoutGuide.owningView removeLayoutGuide:layoutGuide];
[priv->_layoutGuides addObject:layoutGuide];
layoutGuide.owningView = self;
}
}
/**
@Status Interoperable
*/
- (void)removeLayoutGuide:(UILayoutGuide*)layoutGuide {
if (layoutGuide == nil) {
@throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"Cannot remove nil UILayoutGuide!" userInfo:nil];
}
if (![priv->_layoutGuides containsObject:layoutGuide]) {
@throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"Cannot remove nil UILayoutGuide!" userInfo:nil];
}
layoutGuide.owningView = nil;
[priv->_layoutGuides removeObject:layoutGuide];
}
/**
@Status Interoperable
*/
- (CGRect)bounds {
return [layer bounds];
}
/**
@Status Interoperable
*/
- (CGPoint)center {
return [layer position];
}
/**
@Status Interoperable
*/
- (CGAffineTransform)transform {
return [layer affineTransform];
}
/**
@Status Interoperable
*/
- (CGRect)frame {
return CGRectStandardize([layer frame]);
}
/**
@Status Interoperable
*/
- (void)setCenter:(CGPoint)center {
[layer setPosition:center];
}
/**
@Status Interoperable
*/
- (void)layoutSublayersOfLayer:(CALayer*)forLayer {
if (forLayer == layer) {
UIViewController* controller = [UIViewController controllerForView:self];
if (controller != nil) {
[controller viewWillLayoutSubviews];
}
[self updateConstraintsIfNeeded];
[self autoLayoutUpdateConstraints];
[self layoutSubviews];
[self __didLayout];
if (controller != nil) {
[controller viewDidLayoutSubviews];
}
}
}
/**
@Status Caveat
@Notes Questionable impl re: AutoLayout.
*/
- (void)layoutSubviews {
if (priv->autoresizesSubviews) {
[self autoLayoutLayoutSubviews];
}
}
/**
@Status Interoperable
*/
- (void)layoutIfNeeded {
[layer layoutIfNeeded];
}
- (void)__didLayout {
}
/**
@Status Interoperable
*/
- (void)setNeedsLayout {
[layer setNeedsLayout];
}
- (void)_setShouldLayout {
[layer _setShouldLayout];