forked from Floorp-Projects/Floorp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnsChildView.mm
4926 lines (3985 loc) · 167 KB
/
nsChildView.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
/* -*- Mode: objc; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "mozilla/ArrayUtils.h"
#include "mozilla/Logging.h"
#include "mozilla/Unused.h"
#include <unistd.h>
#include <math.h>
#include "nsChildView.h"
#include "nsCocoaWindow.h"
#include "mozilla/Maybe.h"
#include "mozilla/MiscEvents.h"
#include "mozilla/MouseEvents.h"
#include "mozilla/NativeKeyBindingsType.h"
#include "mozilla/PresShell.h"
#include "mozilla/SwipeTracker.h"
#include "mozilla/TextEventDispatcher.h"
#include "mozilla/TextEvents.h"
#include "mozilla/TouchEvents.h"
#include "mozilla/WheelHandlingHelper.h" // for WheelDeltaAdjustmentStrategy
#include "mozilla/WritingModes.h"
#include "mozilla/dom/DataTransfer.h"
#include "mozilla/dom/MouseEventBinding.h"
#include "mozilla/dom/SimpleGestureEventBinding.h"
#include "mozilla/dom/WheelEventBinding.h"
#include "nsArrayUtils.h"
#include "nsExceptionHandler.h"
#include "nsObjCExceptions.h"
#include "nsCOMPtr.h"
#include "nsThreadUtils.h"
#include "nsToolkit.h"
#include "nsCRT.h"
#include "nsFontMetrics.h"
#include "nsIRollupListener.h"
#include "nsViewManager.h"
#include "nsIFile.h"
#include "nsILocalFileMac.h"
#include "nsGfxCIID.h"
#include "nsStyleConsts.h"
#include "nsIWidgetListener.h"
#include "nsIScreen.h"
#include "nsDragService.h"
#include "nsClipboard.h"
#include "nsCursorManager.h"
#include "nsWindowMap.h"
#include "nsCocoaFeatures.h"
#include "nsCocoaUtils.h"
#include "nsMenuUtilsX.h"
#include "nsMenuBarX.h"
#include "NativeKeyBindings.h"
#include "MacThemeGeometryType.h"
#include "gfxContext.h"
#include "gfxQuartzSurface.h"
#include "gfxUtils.h"
#include "nsRegion.h"
#include "GfxTexturesReporter.h"
#include "GLTextureImage.h"
#include "GLContextProvider.h"
#include "GLContextCGL.h"
#include "OGLShaderProgram.h"
#include "ScopedGLHelpers.h"
#include "HeapCopyOfStackArray.h"
#include "mozilla/layers/IAPZCTreeManager.h"
#include "mozilla/layers/APZInputBridge.h"
#include "mozilla/layers/APZThreadUtils.h"
#include "mozilla/layers/CompositorOGL.h"
#include "mozilla/layers/CompositorBridgeParent.h"
#include "mozilla/layers/InputAPZContext.h"
#include "mozilla/layers/IpcResourceUpdateQueue.h"
#include "mozilla/layers/NativeLayerCA.h"
#include "mozilla/layers/WebRenderBridgeChild.h"
#include "mozilla/layers/WebRenderLayerManager.h"
#include "mozilla/webrender/WebRenderAPI.h"
#include "mozilla/widget/CompositorWidget.h"
#include "mozilla/widget/Screen.h"
#include "gfxUtils.h"
#include "mozilla/gfx/2D.h"
#include "mozilla/gfx/BorrowedContext.h"
#ifdef ACCESSIBILITY
# include "nsAccessibilityService.h"
# include "mozilla/a11y/Platform.h"
#endif
#include "mozilla/Preferences.h"
#include "mozilla/StaticPrefs_apz.h"
#include "mozilla/StaticPrefs_browser.h"
#include "mozilla/StaticPrefs_general.h"
#include "mozilla/StaticPrefs_gfx.h"
#include "mozilla/StaticPrefs_ui.h"
#include <dlfcn.h>
#include <ApplicationServices/ApplicationServices.h>
#include "GeckoProfiler.h"
#include "mozilla/layers/ChromeProcessController.h"
#include "nsLayoutUtils.h"
#include "InputData.h"
#include "VibrancyManager.h"
#include "nsNativeThemeCocoa.h"
#include "nsIDOMWindowUtils.h"
#include "Units.h"
#include "UnitTransforms.h"
#include "mozilla/UniquePtrExtensions.h"
#include "CustomCocoaEvents.h"
#include "NativeMenuSupport.h"
using namespace mozilla;
using namespace mozilla::layers;
using namespace mozilla::gl;
using namespace mozilla::widget;
using mozilla::gfx::Matrix4x4;
#undef DEBUG_UPDATE
#undef INVALIDATE_DEBUGGING // flash areas as they are invalidated
// Don't put more than this many rects in the dirty region, just fluff
// out to the bounding-box if there are more
#define MAX_RECTS_IN_REGION 100
LazyLogModule sCocoaLog("nsCocoaWidgets");
extern "C" {
CG_EXTERN void CGContextResetCTM(CGContextRef);
CG_EXTERN void CGContextSetCTM(CGContextRef, CGAffineTransform);
CG_EXTERN void CGContextResetClip(CGContextRef);
typedef CFTypeRef CGSRegionObj;
CGError CGSNewRegionWithRect(const CGRect* rect, CGSRegionObj* outRegion);
CGError CGSNewRegionWithRectList(const CGRect* rects, int rectCount, CGSRegionObj* outRegion);
}
// defined in nsMenuBarX.mm
extern NSMenu* sApplicationMenu; // Application menu shared by all menubars
extern nsIArray* gDraggedTransferables;
ChildView* ChildViewMouseTracker::sLastMouseEventView = nil;
NSEvent* ChildViewMouseTracker::sLastMouseMoveEvent = nil;
NSWindow* ChildViewMouseTracker::sWindowUnderMouse = nil;
NSPoint ChildViewMouseTracker::sLastScrollEventScreenLocation = NSZeroPoint;
#ifdef INVALIDATE_DEBUGGING
static void blinkRect(Rect* r);
static void blinkRgn(RgnHandle rgn);
#endif
bool gUserCancelledDrag = false;
uint32_t nsChildView::sLastInputEventCount = 0;
static bool sIsTabletPointerActivated = false;
static uint32_t sUniqueKeyEventId = 0;
// The view that will do our drawing or host our NSOpenGLContext or Core Animation layer.
@interface PixelHostingView : NSView {
}
@end
@interface ChildView (Private)
// sets up our view, attaching it to its owning gecko view
- (id)initWithFrame:(NSRect)inFrame geckoChild:(nsChildView*)inChild;
// set up a gecko mouse event based on a cocoa mouse event
- (void)convertCocoaMouseWheelEvent:(NSEvent*)aMouseEvent
toGeckoEvent:(WidgetWheelEvent*)outWheelEvent;
- (void)convertCocoaMouseEvent:(NSEvent*)aMouseEvent toGeckoEvent:(WidgetInputEvent*)outGeckoEvent;
- (void)convertCocoaTabletPointerEvent:(NSEvent*)aMouseEvent
toGeckoEvent:(WidgetMouseEvent*)outGeckoEvent;
- (NSMenu*)contextMenu;
- (void)markLayerForDisplay;
- (CALayer*)rootCALayer;
- (void)updateRootCALayer;
#ifdef ACCESSIBILITY
- (id<mozAccessible>)accessible;
#endif
- (LayoutDeviceIntPoint)convertWindowCoordinates:(NSPoint)aPoint;
- (LayoutDeviceIntPoint)convertWindowCoordinatesRoundDown:(NSPoint)aPoint;
- (BOOL)inactiveWindowAcceptsMouseEvent:(NSEvent*)aEvent;
- (void)updateWindowDraggableState;
- (bool)beginOrEndGestureForEventPhase:(NSEvent*)aEvent;
@end
#pragma mark -
// Flips a screen coordinate from a point in the cocoa coordinate system (bottom-left rect) to a
// point that is a "flipped" cocoa coordinate system (starts in the top-left).
static inline void FlipCocoaScreenCoordinate(NSPoint& inPoint) {
inPoint.y = nsCocoaUtils::FlippedScreenY(inPoint.y);
}
#pragma mark -
nsChildView::nsChildView()
: nsBaseWidget(),
mView(nullptr),
mParentView(nil),
mParentWidget(nullptr),
mCompositingLock("ChildViewCompositing"),
mBackingScaleFactor(0.0),
mVisible(false),
mSizeMode(nsSizeMode_Normal),
mDrawing(false),
mIsDispatchPaint(false) {}
nsChildView::~nsChildView() {
// Notify the children that we're gone. childView->ResetParent() can change
// our list of children while it's being iterated, so the way we iterate the
// list must allow for this.
for (nsIWidget* kid = mLastChild; kid;) {
nsChildView* childView = static_cast<nsChildView*>(kid);
kid = kid->GetPrevSibling();
childView->ResetParent();
}
NS_WARNING_ASSERTION(mOnDestroyCalled, "nsChildView object destroyed without calling Destroy()");
if (mContentLayer) {
mNativeLayerRoot->RemoveLayer(mContentLayer); // safe if already removed
}
DestroyCompositor();
// An nsChildView object that was in use can be destroyed without Destroy()
// ever being called on it. So we also need to do a quick, safe cleanup
// here (it's too late to just call Destroy(), which can cause crashes).
// It's particularly important to make sure widgetDestroyed is called on our
// mView -- this method NULLs mView's mGeckoChild, and NULL checks on
// mGeckoChild are used throughout the ChildView class to tell if it's safe
// to use a ChildView object.
[mView widgetDestroyed]; // Safe if mView is nil.
mParentWidget = nil;
TearDownView(); // Safe if called twice.
}
nsresult nsChildView::Create(nsIWidget* aParent, nsNativeWidget aNativeParent,
const LayoutDeviceIntRect& aRect, widget::InitData* aInitData) {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
// Because the hidden window is created outside of an event loop,
// we need to provide an autorelease pool to avoid leaking cocoa objects
// (see bug 559075).
nsAutoreleasePool localPool;
mBounds = aRect;
// Ensure that the toolkit is created.
nsToolkit::GetToolkit();
BaseCreate(aParent, aInitData);
mParentView = nil;
if (aParent) {
// This is the popup window case. aParent is the nsCocoaWindow for the
// popup window, and mParentView will be its content view.
mParentView = (NSView*)aParent->GetNativeData(NS_NATIVE_WIDGET);
mParentWidget = aParent;
} else {
// This is the top-level window case.
// aNativeParent will be the contentView of our window, since that's what
// nsCocoaWindow returns when asked for an NS_NATIVE_VIEW.
// We do not have a direct "parent widget" association with the top level
// window's nsCocoaWindow object.
mParentView = reinterpret_cast<NSView*>(aNativeParent);
}
// create our parallel NSView and hook it up to our parent. Recall
// that NS_NATIVE_WIDGET is the NSView.
CGFloat scaleFactor = nsCocoaUtils::GetBackingScaleFactor(mParentView);
NSRect r = nsCocoaUtils::DevPixelsToCocoaPoints(mBounds, scaleFactor);
mView = [[ChildView alloc] initWithFrame:r geckoChild:this];
mNativeLayerRoot = NativeLayerRootCA::CreateForCALayer([mView rootCALayer]);
mNativeLayerRoot->SetBackingScale(scaleFactor);
// If this view was created in a Gecko view hierarchy, the initial state
// is hidden. If the view is attached only to a native NSView but has
// no Gecko parent (as in embedding), the initial state is visible.
if (mParentWidget)
[mView setHidden:YES];
else
mVisible = true;
// Hook it up in the NSView hierarchy.
if (mParentView) {
[mParentView addSubview:mView];
}
// if this is a ChildView, make sure that our per-window data
// is set up
if ([mView isKindOfClass:[ChildView class]])
[[WindowDataMap sharedWindowDataMap] ensureDataForWindow:[mView window]];
NS_ASSERTION(!mTextInputHandler, "mTextInputHandler has already existed");
mTextInputHandler = new TextInputHandler(this, mView);
return NS_OK;
NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
}
void nsChildView::TearDownView() {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
if (!mView) return;
NSWindow* win = [mView window];
NSResponder* responder = [win firstResponder];
// We're being unhooked from the view hierarchy, don't leave our view
// or a child view as the window first responder.
if (responder && [responder isKindOfClass:[NSView class]] &&
[(NSView*)responder isDescendantOf:mView]) {
[win makeFirstResponder:[mView superview]];
}
// If mView is win's contentView, win (mView's NSWindow) "owns" mView --
// win has retained mView, and will detach it from the view hierarchy and
// release it when necessary (when win is itself destroyed (in a call to
// [win dealloc])). So all we need to do here is call [mView release] (to
// match the call to [mView retain] in nsChildView::StandardCreate()).
// Also calling [mView removeFromSuperviewWithoutNeedingDisplay] causes
// mView to be released again and dealloced, while remaining win's
// contentView. So if we do that here, win will (for a short while) have
// an invalid contentView (for the consequences see bmo bugs 381087 and
// 374260).
if ([mView isEqual:[win contentView]]) {
[mView release];
} else {
// Stop NSView hierarchy being changed during [ChildView drawRect:]
[mView performSelectorOnMainThread:@selector(delayedTearDown)
withObject:nil
waitUntilDone:false];
}
mView = nil;
NS_OBJC_END_TRY_IGNORE_BLOCK;
}
nsCocoaWindow* nsChildView::GetAppWindowWidget() const {
id windowDelegate = [[mView window] delegate];
if (windowDelegate && [windowDelegate isKindOfClass:[WindowDelegate class]]) {
return [(WindowDelegate*)windowDelegate geckoWidget];
}
return nullptr;
}
void nsChildView::Destroy() {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
if (mOnDestroyCalled) return;
mOnDestroyCalled = true;
// Stuff below may delete the last ref to this
nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
{
// Make sure that no composition is in progress while disconnecting
// ourselves from the view.
MutexAutoLock lock(mCompositingLock);
[mView widgetDestroyed];
}
nsBaseWidget::Destroy();
NotifyWindowDestroyed();
mParentWidget = nil;
TearDownView();
nsBaseWidget::OnDestroy();
NS_OBJC_END_TRY_IGNORE_BLOCK;
}
#pragma mark -
#if 0
static void PrintViewHierarchy(NSView *view)
{
while (view) {
NSLog(@" view is %x, frame %@", view, NSStringFromRect([view frame]));
view = [view superview];
}
}
#endif
// Return native data according to aDataType
void* nsChildView::GetNativeData(uint32_t aDataType) {
NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
void* retVal = nullptr;
switch (aDataType) {
case NS_NATIVE_WIDGET:
retVal = (void*)mView;
break;
case NS_NATIVE_WINDOW:
retVal = [mView window];
break;
case NS_NATIVE_GRAPHIC:
NS_ERROR("Requesting NS_NATIVE_GRAPHIC on a Mac OS X child view!");
retVal = nullptr;
break;
case NS_NATIVE_OFFSETX:
retVal = 0;
break;
case NS_NATIVE_OFFSETY:
retVal = 0;
break;
case NS_RAW_NATIVE_IME_CONTEXT:
retVal = GetPseudoIMEContext();
if (retVal) {
break;
}
retVal = [mView inputContext];
// If input context isn't available on this widget, we should set |this|
// instead of nullptr since if this returns nullptr, IMEStateManager
// cannot manage composition with TextComposition instance. Although,
// this case shouldn't occur.
if (NS_WARN_IF(!retVal)) {
retVal = this;
}
break;
case NS_NATIVE_WINDOW_WEBRTC_DEVICE_ID: {
NSWindow* win = [mView window];
if (win) {
retVal = (void*)[win windowNumber];
}
break;
}
}
return retVal;
NS_OBJC_END_TRY_BLOCK_RETURN(nullptr);
}
#pragma mark -
void nsChildView::SuppressAnimation(bool aSuppress) {
GetAppWindowWidget()->SuppressAnimation(aSuppress);
}
bool nsChildView::IsVisible() const {
NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
if (!mVisible) {
return mVisible;
}
if (!GetAppWindowWidget()->IsVisible()) {
return false;
}
// mVisible does not accurately reflect the state of a hidden tabbed view
// so verify that the view has a window as well
// then check native widget hierarchy visibility
return ([mView window] != nil) && !NSIsEmptyRect([mView visibleRect]);
NS_OBJC_END_TRY_BLOCK_RETURN(false);
}
// Some NSView methods (e.g. setFrame and setHidden) invalidate the view's
// bounds in our window. However, we don't want these invalidations because
// they are unnecessary and because they actually slow us down since we
// block on the compositor inside drawRect.
// When we actually need something invalidated, there will be an explicit call
// to Invalidate from Gecko, so turning these automatic invalidations off
// won't hurt us in the non-OMTC case.
// The invalidations inside these NSView methods happen via a call to the
// private method -[NSWindow _setNeedsDisplayInRect:]. Our BaseWindow
// implementation of that method is augmented to let us ignore those calls
// using -[BaseWindow disable/enableSetNeedsDisplay].
static void ManipulateViewWithoutNeedingDisplay(NSView* aView, void (^aCallback)()) {
BaseWindow* win = nil;
if ([[aView window] isKindOfClass:[BaseWindow class]]) {
win = (BaseWindow*)[aView window];
}
[win disableSetNeedsDisplay];
aCallback();
[win enableSetNeedsDisplay];
}
// Hide or show this component
void nsChildView::Show(bool aState) {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
if (aState != mVisible) {
// Provide an autorelease pool because this gets called during startup
// on the "hidden window", resulting in cocoa object leakage if there's
// no pool in place.
nsAutoreleasePool localPool;
ManipulateViewWithoutNeedingDisplay(mView, ^{
[mView setHidden:!aState];
});
mVisible = aState;
}
NS_OBJC_END_TRY_IGNORE_BLOCK;
}
// Change the parent of this widget
void nsChildView::SetParent(nsIWidget* aNewParent) {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
if (mOnDestroyCalled) return;
nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
if (mParentWidget) {
mParentWidget->RemoveChild(this);
}
if (aNewParent) {
ReparentNativeWidget(aNewParent);
} else {
[mView removeFromSuperview];
mParentView = nil;
}
mParentWidget = aNewParent;
if (mParentWidget) {
mParentWidget->AddChild(this);
}
NS_OBJC_END_TRY_IGNORE_BLOCK;
}
void nsChildView::ReparentNativeWidget(nsIWidget* aNewParent) {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
MOZ_ASSERT(aNewParent, "null widget");
if (mOnDestroyCalled) return;
NSView<mozView>* newParentView = (NSView<mozView>*)aNewParent->GetNativeData(NS_NATIVE_WIDGET);
NS_ENSURE_TRUE_VOID(newParentView);
// we hold a ref to mView, so this is safe
[mView removeFromSuperview];
mParentView = newParentView;
[mParentView addSubview:mView];
NS_OBJC_END_TRY_IGNORE_BLOCK;
}
void nsChildView::ResetParent() {
if (!mOnDestroyCalled) {
if (mParentWidget) mParentWidget->RemoveChild(this);
if (mView) [mView removeFromSuperview];
}
mParentWidget = nullptr;
}
nsIWidget* nsChildView::GetParent() { return mParentWidget; }
float nsChildView::GetDPI() {
float dpi = 96.0;
nsCOMPtr<nsIScreen> screen = GetWidgetScreen();
if (screen) {
screen->GetDpi(&dpi);
}
return dpi;
}
void nsChildView::Enable(bool aState) {}
bool nsChildView::IsEnabled() const { return true; }
void nsChildView::SetFocus(Raise, mozilla::dom::CallerType aCallerType) {
NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
NSWindow* window = [mView window];
if (window) [window makeFirstResponder:mView];
NS_OBJC_END_TRY_IGNORE_BLOCK;
}
// Override to set the cursor on the mac
void nsChildView::SetCursor(const Cursor& aCursor) {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
if ([mView isDragInProgress]) {
return; // Don't change the cursor during dragging.
}
nsBaseWidget::SetCursor(aCursor);
if (NS_SUCCEEDED([[nsCursorManager sharedInstance] setCustomCursor:aCursor
widgetScaleFactor:BackingScaleFactor()])) {
return;
}
[[nsCursorManager sharedInstance] setNonCustomCursor:aCursor];
NS_OBJC_END_TRY_IGNORE_BLOCK;
}
#pragma mark -
// Get this component dimension
LayoutDeviceIntRect nsChildView::GetBounds() {
return !mView ? mBounds : CocoaPointsToDevPixels([mView frame]);
}
LayoutDeviceIntRect nsChildView::GetClientBounds() {
LayoutDeviceIntRect rect = GetBounds();
if (!mParentWidget) {
// For top level widgets we want the position on screen, not the position
// of this view inside the window.
rect.MoveTo(WidgetToScreenOffset());
}
return rect;
}
LayoutDeviceIntRect nsChildView::GetScreenBounds() {
LayoutDeviceIntRect rect = GetBounds();
rect.MoveTo(WidgetToScreenOffset());
return rect;
}
double nsChildView::GetDefaultScaleInternal() { return BackingScaleFactor(); }
CGFloat nsChildView::BackingScaleFactor() const {
if (mBackingScaleFactor > 0.0) {
return mBackingScaleFactor;
}
if (!mView) {
return 1.0;
}
mBackingScaleFactor = nsCocoaUtils::GetBackingScaleFactor(mView);
return mBackingScaleFactor;
}
void nsChildView::BackingScaleFactorChanged() {
CGFloat newScale = nsCocoaUtils::GetBackingScaleFactor(mView);
// ignore notification if it hasn't really changed (or maybe we have
// disabled HiDPI mode via prefs)
if (mBackingScaleFactor == newScale) {
return;
}
SuspendAsyncCATransactions();
mBackingScaleFactor = newScale;
NSRect frame = [mView frame];
mBounds = nsCocoaUtils::CocoaRectToGeckoRectDevPix(frame, newScale);
mNativeLayerRoot->SetBackingScale(mBackingScaleFactor);
if (mWidgetListener && !mWidgetListener->GetAppWindow()) {
if (PresShell* presShell = mWidgetListener->GetPresShell()) {
presShell->BackingScaleFactorChanged();
}
}
}
int32_t nsChildView::RoundsWidgetCoordinatesTo() {
if (BackingScaleFactor() == 2.0) {
return 2;
}
return 1;
}
// Move this component, aX and aY are in the parent widget coordinate system
void nsChildView::Move(double aX, double aY) {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
int32_t x = NSToIntRound(aX);
int32_t y = NSToIntRound(aY);
if (!mView || (mBounds.x == x && mBounds.y == y)) return;
mBounds.x = x;
mBounds.y = y;
ManipulateViewWithoutNeedingDisplay(mView, ^{
[mView setFrame:DevPixelsToCocoaPoints(mBounds)];
});
ReportMoveEvent();
NS_OBJC_END_TRY_IGNORE_BLOCK;
}
void nsChildView::Resize(double aWidth, double aHeight, bool aRepaint) {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
int32_t width = NSToIntRound(aWidth);
int32_t height = NSToIntRound(aHeight);
if (!mView || (mBounds.width == width && mBounds.height == height)) return;
SuspendAsyncCATransactions();
mBounds.width = width;
mBounds.height = height;
ManipulateViewWithoutNeedingDisplay(mView, ^{
[mView setFrame:DevPixelsToCocoaPoints(mBounds)];
});
if (mVisible && aRepaint) {
[[mView pixelHostingView] setNeedsDisplay:YES];
}
ReportSizeEvent();
NS_OBJC_END_TRY_IGNORE_BLOCK;
}
void nsChildView::Resize(double aX, double aY, double aWidth, double aHeight, bool aRepaint) {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
int32_t x = NSToIntRound(aX);
int32_t y = NSToIntRound(aY);
int32_t width = NSToIntRound(aWidth);
int32_t height = NSToIntRound(aHeight);
BOOL isMoving = (mBounds.x != x || mBounds.y != y);
BOOL isResizing = (mBounds.width != width || mBounds.height != height);
if (!mView || (!isMoving && !isResizing)) return;
if (isMoving) {
mBounds.x = x;
mBounds.y = y;
}
if (isResizing) {
SuspendAsyncCATransactions();
mBounds.width = width;
mBounds.height = height;
CALayer* layer = [mView rootCALayer];
double scale = BackingScaleFactor();
layer.bounds = CGRectMake(0, 0, width / scale, height / scale);
}
ManipulateViewWithoutNeedingDisplay(mView, ^{
[mView setFrame:DevPixelsToCocoaPoints(mBounds)];
});
if (mVisible && aRepaint) {
[[mView pixelHostingView] setNeedsDisplay:YES];
}
if (isMoving) {
ReportMoveEvent();
if (mOnDestroyCalled) return;
}
if (isResizing) ReportSizeEvent();
NS_OBJC_END_TRY_IGNORE_BLOCK;
}
// The following three methods are primarily an attempt to avoid glitches during
// window resizing.
// Here's some background on how these glitches come to be:
// CoreAnimation transactions are per-thread. They don't nest across threads.
// If you submit a transaction on the main thread and a transaction on a
// different thread, the two will race to the window server and show up on the
// screen in the order that they happen to arrive in at the window server.
// When the window size changes, there's another event that needs to be
// synchronized with: the window "shape" change. Cocoa has built-in synchronization
// mechanics that make sure that *main thread* window paints during window resizes
// are synchronized properly with the window shape change. But no such built-in
// synchronization exists for CATransactions that are triggered on a non-main
// thread.
// To cope with this, we define a "danger zone" during which we simply avoid
// triggering any CATransactions on a non-main thread (called "async" CATransactions
// here). This danger zone starts at the earliest opportunity at which we know
// about the size change, which is nsChildView::Resize, and ends at a point at
// which we know for sure that the paint has been handled completely, which is
// when we return to the event loop after layer display.
void nsChildView::SuspendAsyncCATransactions() {
if (mUnsuspendAsyncCATransactionsRunnable) {
mUnsuspendAsyncCATransactionsRunnable->Cancel();
mUnsuspendAsyncCATransactionsRunnable = nullptr;
}
// Make sure that there actually will be a CATransaction on the main thread
// during which we get a chance to schedule unsuspension. Otherwise we might
// accidentally stay suspended indefinitely.
[mView markLayerForDisplay];
mNativeLayerRoot->SuspendOffMainThreadCommits();
}
void nsChildView::MaybeScheduleUnsuspendAsyncCATransactions() {
if (mNativeLayerRoot->AreOffMainThreadCommitsSuspended() &&
!mUnsuspendAsyncCATransactionsRunnable) {
mUnsuspendAsyncCATransactionsRunnable =
NewCancelableRunnableMethod("nsChildView::MaybeScheduleUnsuspendAsyncCATransactions", this,
&nsChildView::UnsuspendAsyncCATransactions);
NS_DispatchToMainThread(mUnsuspendAsyncCATransactionsRunnable);
}
}
void nsChildView::UnsuspendAsyncCATransactions() {
mUnsuspendAsyncCATransactionsRunnable = nullptr;
if (mNativeLayerRoot->UnsuspendOffMainThreadCommits()) {
// We need to call mNativeLayerRoot->CommitToScreen() at the next available
// opportunity.
// The easiest way to handle this request is to mark the layer as needing
// display, because this will schedule a main thread CATransaction, during
// which HandleMainThreadCATransaction will call CommitToScreen().
[mView markLayerForDisplay];
}
}
void nsChildView::UpdateFullscreen(bool aFullscreen) {
if (mNativeLayerRoot) {
mNativeLayerRoot->SetWindowIsFullscreen(aFullscreen);
}
}
nsresult nsChildView::SynthesizeNativeKeyEvent(int32_t aNativeKeyboardLayout,
int32_t aNativeKeyCode, uint32_t aModifierFlags,
const nsAString& aCharacters,
const nsAString& aUnmodifiedCharacters,
nsIObserver* aObserver) {
AutoObserverNotifier notifier(aObserver, "keyevent");
return mTextInputHandler->SynthesizeNativeKeyEvent(
aNativeKeyboardLayout, aNativeKeyCode, aModifierFlags, aCharacters, aUnmodifiedCharacters);
}
nsresult nsChildView::SynthesizeNativeMouseEvent(LayoutDeviceIntPoint aPoint,
NativeMouseMessage aNativeMessage,
MouseButton aButton,
nsIWidget::Modifiers aModifierFlags,
nsIObserver* aObserver) {
NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
AutoObserverNotifier notifier(aObserver, "mouseevent");
NSPoint pt = nsCocoaUtils::DevPixelsToCocoaPoints(aPoint, BackingScaleFactor());
// Move the mouse cursor to the requested position and reconnect it to the mouse.
CGWarpMouseCursorPosition(NSPointToCGPoint(pt));
CGAssociateMouseAndMouseCursorPosition(true);
// aPoint is given with the origin on the top left, but convertScreenToBase
// expects a point in a coordinate system that has its origin on the bottom left.
NSPoint screenPoint = NSMakePoint(pt.x, nsCocoaUtils::FlippedScreenY(pt.y));
NSPoint windowPoint = nsCocoaUtils::ConvertPointFromScreen([mView window], screenPoint);
NSEventModifierFlags modifierFlags =
nsCocoaUtils::ConvertWidgetModifiersToMacModifierFlags(aModifierFlags);
if (aButton == MouseButton::eX1 || aButton == MouseButton::eX2) {
// NSEvent has `buttonNumber` for `NSEventTypeOther*`. However, it seems that
// there is no way to specify it. Therefore, we should return error for now.
return NS_ERROR_INVALID_ARG;
}
NSEventType nativeEventType;
switch (aNativeMessage) {
case NativeMouseMessage::ButtonDown:
case NativeMouseMessage::ButtonUp: {
switch (aButton) {
case MouseButton::ePrimary:
nativeEventType = aNativeMessage == NativeMouseMessage::ButtonDown
? NSEventTypeLeftMouseDown
: NSEventTypeLeftMouseUp;
break;
case MouseButton::eMiddle:
nativeEventType = aNativeMessage == NativeMouseMessage::ButtonDown
? NSEventTypeOtherMouseDown
: NSEventTypeOtherMouseUp;
break;
case MouseButton::eSecondary:
nativeEventType = aNativeMessage == NativeMouseMessage::ButtonDown
? NSEventTypeRightMouseDown
: NSEventTypeRightMouseUp;
break;
default:
return NS_ERROR_INVALID_ARG;
}
break;
}
case NativeMouseMessage::Move:
nativeEventType = NSEventTypeMouseMoved;
break;
case NativeMouseMessage::EnterWindow:
nativeEventType = NSEventTypeMouseEntered;
break;
case NativeMouseMessage::LeaveWindow:
nativeEventType = NSEventTypeMouseExited;
break;
}
NSEvent* event = [NSEvent mouseEventWithType:nativeEventType
location:windowPoint
modifierFlags:modifierFlags
timestamp:[[NSProcessInfo processInfo] systemUptime]
windowNumber:[[mView window] windowNumber]
context:nil
eventNumber:0
clickCount:1
pressure:0.0];
if (!event) return NS_ERROR_FAILURE;
if ([[mView window] isKindOfClass:[BaseWindow class]]) {
// Tracking area events don't end up in their tracking areas when sent
// through [NSApp sendEvent:], so pass them directly to the right methods.
BaseWindow* window = (BaseWindow*)[mView window];
if (nativeEventType == NSEventTypeMouseEntered) {
[window mouseEntered:event];
return NS_OK;
}
if (nativeEventType == NSEventTypeMouseExited) {
[window mouseExited:event];
return NS_OK;
}
if (nativeEventType == NSEventTypeMouseMoved) {
[window mouseMoved:event];
return NS_OK;
}
}
[NSApp sendEvent:event];
return NS_OK;
NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
}
nsresult nsChildView::SynthesizeNativeMouseScrollEvent(
mozilla::LayoutDeviceIntPoint aPoint, uint32_t aNativeMessage, double aDeltaX, double aDeltaY,
double aDeltaZ, uint32_t aModifierFlags, uint32_t aAdditionalFlags, nsIObserver* aObserver) {
NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
AutoObserverNotifier notifier(aObserver, "mousescrollevent");
NSPoint pt = nsCocoaUtils::DevPixelsToCocoaPoints(aPoint, BackingScaleFactor());
// Move the mouse cursor to the requested position and reconnect it to the mouse.
CGWarpMouseCursorPosition(NSPointToCGPoint(pt));
CGAssociateMouseAndMouseCursorPosition(true);
// Mostly copied from http://stackoverflow.com/a/6130349
CGScrollEventUnit units = (aAdditionalFlags & nsIDOMWindowUtils::MOUSESCROLL_SCROLL_LINES)
? kCGScrollEventUnitLine
: kCGScrollEventUnitPixel;
CGEventRef cgEvent = CGEventCreateScrollWheelEvent(NULL, units, 3, (int32_t)aDeltaY,
(int32_t)aDeltaX, (int32_t)aDeltaZ);
if (!cgEvent) {
return NS_ERROR_FAILURE;
}
if (aNativeMessage) {
CGEventSetIntegerValueField(cgEvent, kCGScrollWheelEventScrollPhase, aNativeMessage);
}
// On macOS 10.14 and up CGEventPost won't work because of changes in macOS
// to improve security. This code makes an NSEvent corresponding to the
// wheel event and dispatches it directly to the scrollWheel handler. Some
// fiddling is needed with the coordinates in order to simulate what macOS
// would do; this code adapted from the Chromium equivalent function at
// https://chromium.googlesource.com/chromium/src.git/+/62.0.3178.1/ui/events/test/cocoa_test_event_utils.mm#38
CGPoint location = CGEventGetLocation(cgEvent);
location.y += NSMinY([[mView window] frame]);
location.x -= NSMinX([[mView window] frame]);
CGEventSetLocation(cgEvent, location);
uint64_t kNanosPerSec = 1000000000L;
CGEventSetTimestamp(cgEvent, [[NSProcessInfo processInfo] systemUptime] * kNanosPerSec);
NSEvent* event = [NSEvent eventWithCGEvent:cgEvent];
[event setValue:[mView window] forKey:@"_window"];
[mView scrollWheel:event];