This repository has been archived by the owner on Aug 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathnsCocoaWindow.mm
3566 lines (2935 loc) · 123 KB
/
nsCocoaWindow.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: Objective-C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/* 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 "nsCocoaWindow.h"
#include "NativeKeyBindings.h"
#include "ScreenHelperCocoa.h"
#include "TextInputHandler.h"
#include "nsObjCExceptions.h"
#include "nsCOMPtr.h"
#include "nsWidgetsCID.h"
#include "nsIRollupListener.h"
#include "nsChildView.h"
#include "nsWindowMap.h"
#include "nsAppShell.h"
#include "nsIAppShellService.h"
#include "nsIBaseWindow.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsIXULWindow.h"
#include "nsToolkit.h"
#include "nsIDOMWindow.h"
#include "nsPIDOMWindow.h"
#include "nsThreadUtils.h"
#include "nsMenuBarX.h"
#include "nsMenuUtilsX.h"
#include "nsStyleConsts.h"
#include "nsNativeThemeColors.h"
#include "nsNativeThemeCocoa.h"
#include "nsChildView.h"
#include "nsCocoaFeatures.h"
#include "nsIScreenManager.h"
#include "nsIWidgetListener.h"
#include "VibrancyManager.h"
#include "gfxPlatform.h"
#include "gfxPrefs.h"
#include "qcms.h"
#include "mozilla/AutoRestore.h"
#include "mozilla/BasicEvents.h"
#include "mozilla/Preferences.h"
#include "mozilla/PresShell.h"
#include <algorithm>
namespace mozilla {
namespace layers {
class LayerManager;
} // namespace layers
} // namespace mozilla
using namespace mozilla::layers;
using namespace mozilla::widget;
using namespace mozilla;
int32_t gXULModalLevel = 0;
// In principle there should be only one app-modal window at any given time.
// But sometimes, despite our best efforts, another window appears above the
// current app-modal window. So we need to keep a linked list of app-modal
// windows. (A non-sheet window that appears above an app-modal window is
// also made app-modal.) See nsCocoaWindow::SetModal().
nsCocoaWindowList* gGeckoAppModalWindowList = NULL;
// defined in nsMenuBarX.mm
extern NSMenu* sApplicationMenu; // Application menu shared by all menubars
// defined in nsChildView.mm
extern BOOL gSomeMenuBarPainted;
#if !defined(MAC_OS_X_VERSION_10_9) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_9
enum NSWindowOcclusionState { NSWindowOcclusionStateVisible = 0x1 << 1 };
@interface NSWindow (OcclusionState)
- (NSWindowOcclusionState)occlusionState;
@end
#endif
#if !defined(MAC_OS_X_VERSION_10_10) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_10
enum NSWindowTitleVisibility { NSWindowTitleVisible = 0, NSWindowTitleHidden = 1 };
@interface NSWindow (TitleVisibility)
- (void)setTitleVisibility:(NSWindowTitleVisibility)visibility;
- (void)setTitlebarAppearsTransparent:(BOOL)isTitlebarTransparent;
@end
#endif
#if !defined(MAC_OS_X_VERSION_10_12) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_12
@interface NSWindow (AutomaticWindowTabbing)
+ (void)setAllowsAutomaticWindowTabbing:(BOOL)allow;
@end
#endif
extern "C" {
// CGSPrivate.h
typedef NSInteger CGSConnection;
typedef NSInteger CGSWindow;
typedef NSUInteger CGSWindowFilterRef;
extern CGSConnection _CGSDefaultConnection(void);
extern CGError CGSSetWindowShadowAndRimParameters(const CGSConnection cid, CGSWindow wid,
float standardDeviation, float density,
int offsetX, int offsetY, unsigned int flags);
extern CGError CGSSetWindowBackgroundBlurRadius(CGSConnection cid, CGSWindow wid, NSUInteger blur);
extern CGError CGSSetWindowTransform(CGSConnection cid, CGSWindow wid, CGAffineTransform transform);
}
#define NS_APPSHELLSERVICE_CONTRACTID "@mozilla.org/appshell/appShellService;1"
NS_IMPL_ISUPPORTS_INHERITED(nsCocoaWindow, Inherited, nsPIWidgetCocoa)
// A note on testing to see if your object is a sheet...
// |mWindowType == eWindowType_sheet| is true if your gecko nsIWidget is a sheet
// widget - whether or not the sheet is showing. |[mWindow isSheet]| will return
// true *only when the sheet is actually showing*. Choose your test wisely.
static void RollUpPopups() {
nsIRollupListener* rollupListener = nsBaseWidget::GetActiveRollupListener();
NS_ENSURE_TRUE_VOID(rollupListener);
nsCOMPtr<nsIWidget> rollupWidget = rollupListener->GetRollupWidget();
if (!rollupWidget) return;
rollupListener->Rollup(0, true, nullptr, nullptr);
}
nsCocoaWindow::nsCocoaWindow()
: mParent(nullptr),
mAncestorLink(nullptr),
mWindow(nil),
mDelegate(nil),
mSheetWindowParent(nil),
mPopupContentView(nil),
mFullscreenTransitionAnimation(nil),
mShadowStyle(NS_STYLE_WINDOW_SHADOW_DEFAULT),
mBackingScaleFactor(0.0),
mAnimationType(nsIWidget::eGenericWindowAnimation),
mWindowMadeHere(false),
mSheetNeedsShow(false),
mInFullScreenMode(false),
mInFullScreenTransition(false),
mModal(false),
mFakeModal(false),
mSupportsNativeFullScreen(false),
mInNativeFullScreenMode(false),
mIsAnimationSuppressed(false),
mInReportMoveEvent(false),
mInResize(false),
mWindowTransformIsIdentity(true),
mNumModalDescendents(0),
mWindowAnimationBehavior(NSWindowAnimationBehaviorDefault) {
if ([NSWindow respondsToSelector:@selector(setAllowsAutomaticWindowTabbing:)]) {
// Disable automatic tabbing on 10.12. We need to do this before we
// orderFront any of our windows.
[NSWindow setAllowsAutomaticWindowTabbing:NO];
}
}
void nsCocoaWindow::DestroyNativeWindow() {
NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
if (!mWindow) return;
[mWindow releaseJSObjects];
// We want to unhook the delegate here because we don't want events
// sent to it after this object has been destroyed.
[mWindow setDelegate:nil];
[mWindow close];
mWindow = nil;
[mDelegate autorelease];
NS_OBJC_END_TRY_ABORT_BLOCK;
}
nsCocoaWindow::~nsCocoaWindow() {
NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
// Notify the children that we're gone. Popup windows (e.g. tooltips) can
// have nsChildView children. 'kid' is an nsChildView object if and only if
// its 'type' is 'eWindowType_child'.
// 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;) {
nsWindowType kidType = kid->WindowType();
if (kidType == eWindowType_child) {
nsChildView* childView = static_cast<nsChildView*>(kid);
kid = kid->GetPrevSibling();
childView->ResetParent();
} else {
nsCocoaWindow* childWindow = static_cast<nsCocoaWindow*>(kid);
childWindow->mParent = nullptr;
childWindow->mAncestorLink = mAncestorLink;
kid = kid->GetPrevSibling();
}
}
if (mWindow && mWindowMadeHere) {
DestroyNativeWindow();
}
NS_IF_RELEASE(mPopupContentView);
// Deal with the possiblity that we're being destroyed while running modal.
if (mModal) {
NS_WARNING("Widget destroyed while running modal!");
--gXULModalLevel;
NS_ASSERTION(gXULModalLevel >= 0, "Weirdness setting modality!");
}
NS_OBJC_END_TRY_ABORT_BLOCK;
}
// Find the screen that overlaps aRect the most,
// if none are found default to the mainScreen.
static NSScreen* FindTargetScreenForRect(const DesktopIntRect& aRect) {
NSScreen* targetScreen = [NSScreen mainScreen];
NSEnumerator* screenEnum = [[NSScreen screens] objectEnumerator];
int largestIntersectArea = 0;
while (NSScreen* screen = [screenEnum nextObject]) {
DesktopIntRect screenRect = nsCocoaUtils::CocoaRectToGeckoRect([screen visibleFrame]);
screenRect = screenRect.Intersect(aRect);
int area = screenRect.width * screenRect.height;
if (area > largestIntersectArea) {
largestIntersectArea = area;
targetScreen = screen;
}
}
return targetScreen;
}
// fits the rect to the screen that contains the largest area of it,
// or to aScreen if a screen is passed in
// NB: this operates with aRect in desktop pixels
static void FitRectToVisibleAreaForScreen(DesktopIntRect& aRect, NSScreen* aScreen) {
if (!aScreen) {
aScreen = FindTargetScreenForRect(aRect);
}
DesktopIntRect screenBounds = nsCocoaUtils::CocoaRectToGeckoRect([aScreen visibleFrame]);
if (aRect.width > screenBounds.width) {
aRect.width = screenBounds.width;
}
if (aRect.height > screenBounds.height) {
aRect.height = screenBounds.height;
}
if (aRect.x - screenBounds.x + aRect.width > screenBounds.width) {
aRect.x += screenBounds.width - (aRect.x - screenBounds.x + aRect.width);
}
if (aRect.y - screenBounds.y + aRect.height > screenBounds.height) {
aRect.y += screenBounds.height - (aRect.y - screenBounds.y + aRect.height);
}
// If the left/top edge of the window is off the screen in either direction,
// then set the window to start at the left/top edge of the screen.
if (aRect.x < screenBounds.x || aRect.x > (screenBounds.x + screenBounds.width)) {
aRect.x = screenBounds.x;
}
if (aRect.y < screenBounds.y || aRect.y > (screenBounds.y + screenBounds.height)) {
aRect.y = screenBounds.y;
}
}
// Some applications use native popup windows
// (native context menus, native tooltips)
static bool UseNativePopupWindows() {
#ifdef MOZ_USE_NATIVE_POPUP_WINDOWS
return true;
#else
return false;
#endif /* MOZ_USE_NATIVE_POPUP_WINDOWS */
}
// aRect here is specified in desktop pixels
nsresult nsCocoaWindow::Create(nsIWidget* aParent, nsNativeWidget aNativeParent,
const DesktopIntRect& aRect, nsWidgetInitData* aInitData) {
NS_OBJC_BEGIN_TRY_ABORT_BLOCK_NSRESULT;
// Because the hidden window is created outside of an event loop,
// we have to provide an autorelease pool (see bug 559075).
nsAutoreleasePool localPool;
DesktopIntRect newBounds = aRect;
FitRectToVisibleAreaForScreen(newBounds, nullptr);
// Set defaults which can be overriden from aInitData in BaseCreate
mWindowType = eWindowType_toplevel;
mBorderStyle = eBorderStyle_default;
// Ensure that the toolkit is created.
nsToolkit::GetToolkit();
Inherited::BaseCreate(aParent, aInitData);
mParent = aParent;
mAncestorLink = aParent;
// Applications that use native popups don't want us to create popup windows.
if ((mWindowType == eWindowType_popup) && UseNativePopupWindows()) return NS_OK;
nsresult rv =
CreateNativeWindow(nsCocoaUtils::GeckoRectToCocoaRect(newBounds), mBorderStyle, false);
NS_ENSURE_SUCCESS(rv, rv);
if (mWindowType == eWindowType_popup) {
if (aInitData->mMouseTransparent) {
[mWindow setIgnoresMouseEvents:YES];
}
// now we can convert newBounds to device pixels for the window we created,
// as the child view expects a rect expressed in the dev pix of its parent
LayoutDeviceIntRect devRect = RoundedToInt(newBounds * GetDesktopToDeviceScale());
return CreatePopupContentView(devRect, aInitData);
}
mIsAnimationSuppressed = aInitData->mIsAnimationSuppressed;
return NS_OK;
NS_OBJC_END_TRY_ABORT_BLOCK_NSRESULT;
}
nsresult nsCocoaWindow::Create(nsIWidget* aParent, nsNativeWidget aNativeParent,
const LayoutDeviceIntRect& aRect, nsWidgetInitData* aInitData) {
DesktopIntRect desktopRect = RoundedToInt(aRect / GetDesktopToDeviceScale());
return Create(aParent, aNativeParent, desktopRect, aInitData);
}
static unsigned int WindowMaskForBorderStyle(nsBorderStyle aBorderStyle) {
bool allOrDefault = (aBorderStyle == eBorderStyle_all || aBorderStyle == eBorderStyle_default);
/* Apple's docs on NSWindow styles say that "a window's style mask should
* include NSTitledWindowMask if it includes any of the others [besides
* NSBorderlessWindowMask]". This implies that a borderless window
* shouldn't have any other styles than NSBorderlessWindowMask.
*/
if (!allOrDefault && !(aBorderStyle & eBorderStyle_title)) return NSBorderlessWindowMask;
unsigned int mask = NSTitledWindowMask;
if (allOrDefault || aBorderStyle & eBorderStyle_close) mask |= NSClosableWindowMask;
if (allOrDefault || aBorderStyle & eBorderStyle_minimize) mask |= NSMiniaturizableWindowMask;
if (allOrDefault || aBorderStyle & eBorderStyle_resizeh) mask |= NSResizableWindowMask;
return mask;
}
// If aRectIsFrameRect, aRect specifies the frame rect of the new window.
// Otherwise, aRect.x/y specify the position of the window's frame relative to
// the bottom of the menubar and aRect.width/height specify the size of the
// content rect.
nsresult nsCocoaWindow::CreateNativeWindow(const NSRect& aRect, nsBorderStyle aBorderStyle,
bool aRectIsFrameRect) {
NS_OBJC_BEGIN_TRY_ABORT_BLOCK_NSRESULT;
// We default to NSBorderlessWindowMask, add features if needed.
unsigned int features = NSBorderlessWindowMask;
// Configure the window we will create based on the window type.
switch (mWindowType) {
case eWindowType_invisible:
case eWindowType_child:
case eWindowType_plugin:
break;
case eWindowType_popup:
if (aBorderStyle != eBorderStyle_default && mBorderStyle & eBorderStyle_title) {
features |= NSTitledWindowMask;
if (aBorderStyle & eBorderStyle_close) {
features |= NSClosableWindowMask;
}
}
break;
case eWindowType_toplevel:
case eWindowType_dialog:
features = WindowMaskForBorderStyle(aBorderStyle);
break;
case eWindowType_sheet:
if (mParent->WindowType() != eWindowType_invisible && aBorderStyle & eBorderStyle_resizeh) {
features = NSResizableWindowMask;
} else {
features = NSMiniaturizableWindowMask;
}
features |= NSTitledWindowMask;
break;
default:
NS_ERROR("Unhandled window type!");
return NS_ERROR_FAILURE;
}
NSRect contentRect;
if (aRectIsFrameRect) {
contentRect = [NSWindow contentRectForFrameRect:aRect styleMask:features];
} else {
/*
* We pass a content area rect to initialize the native Cocoa window. The
* content rect we give is the same size as the size we're given by gecko.
* The origin we're given for non-popup windows is moved down by the height
* of the menu bar so that an origin of (0,100) from gecko puts the window
* 100 pixels below the top of the available desktop area. We also move the
* origin down by the height of a title bar if it exists. This is so the
* origin that gecko gives us for the top-left of the window turns out to
* be the top-left of the window we create. This is how it was done in
* Carbon. If it ought to be different we'll probably need to look at all
* the callers.
*
* Note: This means that if you put a secondary screen on top of your main
* screen and open a window in the top screen, it'll be incorrectly shifted
* down by the height of the menu bar. Same thing would happen in Carbon.
*
* Note: If you pass a rect with 0,0 for an origin, the window ends up in a
* weird place for some reason. This stops that without breaking popups.
*/
// Compensate for difference between frame and content area height (e.g. title bar).
NSRect newWindowFrame = [NSWindow frameRectForContentRect:aRect styleMask:features];
contentRect = aRect;
contentRect.origin.y -= (newWindowFrame.size.height - aRect.size.height);
if (mWindowType != eWindowType_popup) contentRect.origin.y -= [[NSApp mainMenu] menuBarHeight];
}
// NSLog(@"Top-level window being created at Cocoa rect: %f, %f, %f, %f\n",
// rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
Class windowClass = [BaseWindow class];
// If we have a titlebar on a top-level window, we want to be able to control the
// titlebar color (for unified windows), so use the special ToolbarWindow class.
// Note that we need to check the window type because we mark sheets as
// having titlebars.
if ((mWindowType == eWindowType_toplevel || mWindowType == eWindowType_dialog) &&
(features & NSTitledWindowMask))
windowClass = [ToolbarWindow class];
// If we're a popup window we need to use the PopupWindow class.
else if (mWindowType == eWindowType_popup)
windowClass = [PopupWindow class];
// If we're a non-popup borderless window we need to use the
// BorderlessWindow class.
else if (features == NSBorderlessWindowMask)
windowClass = [BorderlessWindow class];
// Create the window
mWindow = [[windowClass alloc] initWithContentRect:contentRect
styleMask:features
backing:NSBackingStoreBuffered
defer:YES];
// Make sure that window titles don't leak to disk in private browsing mode
// due to macOS' resume feature.
[mWindow setRestorable:NO];
[mWindow disableSnapshotRestoration];
// setup our notification delegate. Note that setDelegate: does NOT retain.
mDelegate = [[WindowDelegate alloc] initWithGeckoWindow:this];
[mWindow setDelegate:mDelegate];
// Make sure that the content rect we gave has been honored.
NSRect wantedFrame = [mWindow frameRectForChildViewRect:contentRect];
if (!NSEqualRects([mWindow frame], wantedFrame)) {
// This can happen when the window is not on the primary screen.
[mWindow setFrame:wantedFrame display:NO];
}
UpdateBounds();
if (mWindowType == eWindowType_invisible) {
[mWindow setLevel:kCGDesktopWindowLevelKey];
}
if (mWindowType == eWindowType_popup) {
SetPopupWindowLevel();
[mWindow setBackgroundColor:[NSColor clearColor]];
[mWindow setOpaque:NO];
} else {
// Make sure that regular windows are opaque from the start, so that
// nsChildView::WidgetTypeSupportsAcceleration returns true for them.
[mWindow setOpaque:YES];
}
[mWindow setContentMinSize:NSMakeSize(60, 60)];
[mWindow disableCursorRects];
// Make sure the window starts out not draggable by the background.
// We will turn it on as necessary.
[mWindow setMovableByWindowBackground:NO];
[[WindowDataMap sharedWindowDataMap] ensureDataForWindow:mWindow];
mWindowMadeHere = true;
return NS_OK;
NS_OBJC_END_TRY_ABORT_BLOCK_NSRESULT;
}
nsresult nsCocoaWindow::CreatePopupContentView(const LayoutDeviceIntRect& aRect,
nsWidgetInitData* aInitData) {
NS_OBJC_BEGIN_TRY_ABORT_BLOCK_NSRESULT;
// We need to make our content view a ChildView.
mPopupContentView = new nsChildView();
if (!mPopupContentView) return NS_ERROR_FAILURE;
NS_ADDREF(mPopupContentView);
nsIWidget* thisAsWidget = static_cast<nsIWidget*>(this);
nsresult rv = mPopupContentView->Create(thisAsWidget, nullptr, aRect, aInitData);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
NSView* contentView = [mWindow contentView];
ChildView* childView = (ChildView*)mPopupContentView->GetNativeData(NS_NATIVE_WIDGET);
[childView setFrame:[contentView bounds]];
[childView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
[contentView addSubview:childView];
return NS_OK;
NS_OBJC_END_TRY_ABORT_BLOCK_NSRESULT;
}
void nsCocoaWindow::Destroy() {
if (mOnDestroyCalled) return;
mOnDestroyCalled = true;
// SetFakeModal(true) is called for non-modal window opened by modal window.
// On Cocoa, it needs corresponding SetFakeModal(false) on destroy to restore
// ancestor windows' state.
if (mFakeModal) {
SetFakeModal(false);
}
// If we don't hide here we run into problems with panels, this is not ideal.
// (Bug 891424)
Show(false);
if (mPopupContentView) mPopupContentView->Destroy();
if (mFullscreenTransitionAnimation) {
[mFullscreenTransitionAnimation stopAnimation];
ReleaseFullscreenTransitionAnimation();
}
nsBaseWidget::Destroy();
// nsBaseWidget::Destroy() calls GetParent()->RemoveChild(this). But we
// don't implement GetParent(), so we need to do the equivalent here.
if (mParent) {
mParent->RemoveChild(this);
}
nsBaseWidget::OnDestroy();
if (mInFullScreenMode) {
// On Lion we don't have to mess with the OS chrome when in Full Screen
// mode. But we do have to destroy the native window here (and not wait
// for that to happen in our destructor). We don't switch away from the
// native window's space until the window is destroyed, and otherwise this
// might not happen for several seconds (because at least one object
// holding a reference to ourselves is usually waiting to be garbage-
// collected). See bug 757618.
if (mInNativeFullScreenMode) {
DestroyNativeWindow();
} else if (mWindow) {
nsCocoaUtils::HideOSChromeOnScreen(false);
}
}
}
nsIWidget* nsCocoaWindow::GetSheetWindowParent(void) {
if (mWindowType != eWindowType_sheet) return nullptr;
nsCocoaWindow* parent = static_cast<nsCocoaWindow*>(mParent);
while (parent && (parent->mWindowType == eWindowType_sheet))
parent = static_cast<nsCocoaWindow*>(parent->mParent);
return parent;
}
void* nsCocoaWindow::GetNativeData(uint32_t aDataType) {
NS_OBJC_BEGIN_TRY_ABORT_BLOCK_NSNULL;
void* retVal = nullptr;
switch (aDataType) {
// to emulate how windows works, we always have to return a NSView
// for NS_NATIVE_WIDGET
case NS_NATIVE_WIDGET:
case NS_NATIVE_DISPLAY:
retVal = [mWindow contentView];
break;
case NS_NATIVE_WINDOW:
retVal = mWindow;
break;
case NS_NATIVE_GRAPHIC:
// There isn't anything that makes sense to return here,
// and it doesn't matter so just return nullptr.
NS_ERROR("Requesting NS_NATIVE_GRAPHIC on a top-level window!");
break;
case NS_RAW_NATIVE_IME_CONTEXT: {
retVal = GetPseudoIMEContext();
if (retVal) {
break;
}
NSView* view = mWindow ? [mWindow contentView] : nil;
if (view) {
retVal = [view inputContext];
}
// If inputContext isn't available on this window, return this window's
// pointer 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;
}
}
return retVal;
NS_OBJC_END_TRY_ABORT_BLOCK_NSNULL;
}
bool nsCocoaWindow::IsVisible() const {
NS_OBJC_BEGIN_TRY_ABORT_BLOCK_RETURN;
return (mWindow && ([mWindow isVisibleOrBeingShown] || mSheetNeedsShow));
NS_OBJC_END_TRY_ABORT_BLOCK_RETURN(false);
}
void nsCocoaWindow::SetModal(bool aState) {
NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
if (!mWindow) return;
// This is used during startup (outside the event loop) when creating
// the add-ons compatibility checking dialog and the profile manager UI;
// therefore, it needs to provide an autorelease pool to avoid cocoa
// objects leaking.
nsAutoreleasePool localPool;
mModal = aState;
nsCocoaWindow* ancestor = static_cast<nsCocoaWindow*>(mAncestorLink);
if (aState) {
++gXULModalLevel;
// When a non-sheet window gets "set modal", make the window(s) that it
// appears over behave as they should. We can't rely on native methods to
// do this, for the following reason: The OS runs modal non-sheet windows
// in an event loop (using [NSApplication runModalForWindow:] or similar
// methods) that's incompatible with the modal event loop in nsXULWindow::
// ShowModal() (each of these event loops is "exclusive", and can't run at
// the same time as other (similar) event loops).
if (mWindowType != eWindowType_sheet) {
while (ancestor) {
if (ancestor->mNumModalDescendents++ == 0) {
NSWindow* aWindow = ancestor->GetCocoaWindow();
if (ancestor->mWindowType != eWindowType_invisible) {
[[aWindow standardWindowButton:NSWindowCloseButton] setEnabled:NO];
[[aWindow standardWindowButton:NSWindowMiniaturizeButton] setEnabled:NO];
[[aWindow standardWindowButton:NSWindowZoomButton] setEnabled:NO];
}
}
ancestor = static_cast<nsCocoaWindow*>(ancestor->mParent);
}
[mWindow setLevel:NSModalPanelWindowLevel];
nsCocoaWindowList* windowList = new nsCocoaWindowList;
if (windowList) {
windowList->window = this; // Don't ADDREF
windowList->prev = gGeckoAppModalWindowList;
gGeckoAppModalWindowList = windowList;
}
}
} else {
--gXULModalLevel;
NS_ASSERTION(gXULModalLevel >= 0, "Mismatched call to nsCocoaWindow::SetModal(false)!");
if (mWindowType != eWindowType_sheet) {
while (ancestor) {
if (--ancestor->mNumModalDescendents == 0) {
NSWindow* aWindow = ancestor->GetCocoaWindow();
if (ancestor->mWindowType != eWindowType_invisible) {
[[aWindow standardWindowButton:NSWindowCloseButton] setEnabled:YES];
[[aWindow standardWindowButton:NSWindowMiniaturizeButton] setEnabled:YES];
[[aWindow standardWindowButton:NSWindowZoomButton] setEnabled:YES];
}
}
NS_ASSERTION(ancestor->mNumModalDescendents >= 0, "Widget hierarchy changed while modal!");
ancestor = static_cast<nsCocoaWindow*>(ancestor->mParent);
}
if (gGeckoAppModalWindowList) {
NS_ASSERTION(gGeckoAppModalWindowList->window == this,
"Widget hierarchy changed while modal!");
nsCocoaWindowList* saved = gGeckoAppModalWindowList;
gGeckoAppModalWindowList = gGeckoAppModalWindowList->prev;
delete saved; // "window" not ADDREFed
}
if (mWindowType == eWindowType_popup)
SetPopupWindowLevel();
else
[mWindow setLevel:NSNormalWindowLevel];
}
}
NS_OBJC_END_TRY_ABORT_BLOCK;
}
void nsCocoaWindow::SetFakeModal(bool aState) {
mFakeModal = aState;
SetModal(aState);
}
bool nsCocoaWindow::IsRunningAppModal() { return [NSApp _isRunningAppModal]; }
// Hide or show this window
void nsCocoaWindow::Show(bool bState) {
NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
if (!mWindow) return;
// We need to re-execute sometimes in order to bring already-visible
// windows forward.
if (!mSheetNeedsShow && !bState && ![mWindow isVisible]) return;
// Protect against re-entering.
if (bState && [mWindow isBeingShown]) return;
[mWindow setBeingShown:bState];
nsIWidget* parentWidget = mParent;
nsCOMPtr<nsPIWidgetCocoa> piParentWidget(do_QueryInterface(parentWidget));
NSWindow* nativeParentWindow =
(parentWidget) ? (NSWindow*)parentWidget->GetNativeData(NS_NATIVE_WINDOW) : nil;
if (bState && !mBounds.IsEmpty()) {
// Don't try to show a popup when the parent isn't visible or is minimized.
if (mWindowType == eWindowType_popup && nativeParentWindow) {
if (![nativeParentWindow isVisible] || [nativeParentWindow isMiniaturized]) {
return;
}
}
if (mPopupContentView) {
// Ensure our content view is visible. We never need to hide it.
mPopupContentView->Show(true);
}
if (mWindowType == eWindowType_sheet) {
// bail if no parent window (its basically what we do in Carbon)
if (!nativeParentWindow || !piParentWidget) return;
NSWindow* topNonSheetWindow = nativeParentWindow;
// If this sheet is the child of another sheet, hide the parent so that
// this sheet can be displayed. Leave the parent mSheetNeedsShow alone,
// that is only used to handle sibling sheet contention. The parent will
// return once there are no more child sheets.
bool parentIsSheet = false;
if (NS_SUCCEEDED(piParentWidget->GetIsSheet(&parentIsSheet)) && parentIsSheet) {
piParentWidget->GetSheetWindowParent(&topNonSheetWindow);
[NSApp endSheet:nativeParentWindow];
}
nsCOMPtr<nsIWidget> sheetShown;
if (NS_SUCCEEDED(piParentWidget->GetChildSheet(true, getter_AddRefs(sheetShown))) &&
(!sheetShown || sheetShown == this)) {
// If this sheet is already the sheet actually being shown, don't
// tell it to show again. Otherwise the number of calls to
// [NSApp beginSheet...] won't match up with [NSApp endSheet...].
if (![mWindow isVisible]) {
mSheetNeedsShow = false;
mSheetWindowParent = topNonSheetWindow;
// Only set contextInfo if our parent isn't a sheet.
NSWindow* contextInfo = parentIsSheet ? nil : mSheetWindowParent;
[TopLevelWindowData deactivateInWindow:mSheetWindowParent];
[NSApp beginSheet:mWindow
modalForWindow:mSheetWindowParent
modalDelegate:mDelegate
didEndSelector:@selector(didEndSheet:returnCode:contextInfo:)
contextInfo:contextInfo];
[TopLevelWindowData activateInWindow:mWindow];
SendSetZLevelEvent();
}
} else {
// A sibling of this sheet is active, don't show this sheet yet.
// When the active sheet hides, its brothers and sisters that have
// mSheetNeedsShow set will have their opportunities to display.
mSheetNeedsShow = true;
}
} else if (mWindowType == eWindowType_popup) {
// For reasons that aren't yet clear, calls to [NSWindow orderFront:] or
// [NSWindow makeKeyAndOrderFront:] can sometimes trigger "Error (1000)
// creating CGSWindow", which in turn triggers an internal inconsistency
// NSException. These errors shouldn't be fatal. So we need to wrap
// calls to ...orderFront: in TRY blocks. See bmo bug 470864.
NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
[[mWindow contentView] setNeedsDisplay:YES];
[mWindow orderFront:nil];
NS_OBJC_END_TRY_ABORT_BLOCK;
SendSetZLevelEvent();
AdjustWindowShadow();
SetWindowBackgroundBlur();
// If our popup window is a non-native context menu, tell the OS (and
// other programs) that a menu has opened. This is how the OS knows to
// close other programs' context menus when ours open.
if ([mWindow isKindOfClass:[PopupWindow class]] && [(PopupWindow*)mWindow isContextMenu]) {
[[NSDistributedNotificationCenter defaultCenter]
postNotificationName:@"com.apple.HIToolbox.beginMenuTrackingNotification"
object:@"org.mozilla.gecko.PopupWindow"];
}
// If a parent window was supplied and this is a popup at the parent
// level, set its child window. This will cause the child window to
// appear above the parent and move when the parent does. Setting this
// needs to happen after the _setWindowNumber calls above, otherwise the
// window doesn't focus properly.
if (nativeParentWindow && mPopupLevel == ePopupLevelParent)
[nativeParentWindow addChildWindow:mWindow ordered:NSWindowAbove];
} else {
NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
if (mWindowType == eWindowType_toplevel &&
[mWindow respondsToSelector:@selector(setAnimationBehavior:)]) {
NSWindowAnimationBehavior behavior;
if (mIsAnimationSuppressed) {
behavior = NSWindowAnimationBehaviorNone;
} else {
switch (mAnimationType) {
case nsIWidget::eDocumentWindowAnimation:
behavior = NSWindowAnimationBehaviorDocumentWindow;
break;
default:
MOZ_ASSERT_UNREACHABLE("unexpected mAnimationType value");
// fall through
case nsIWidget::eGenericWindowAnimation:
behavior = NSWindowAnimationBehaviorDefault;
break;
}
}
[mWindow setAnimationBehavior:behavior];
mWindowAnimationBehavior = behavior;
}
[mWindow makeKeyAndOrderFront:nil];
NS_OBJC_END_TRY_ABORT_BLOCK;
SendSetZLevelEvent();
}
} else {
// roll up any popups if a top-level window is going away
if (mWindowType == eWindowType_toplevel || mWindowType == eWindowType_dialog) RollUpPopups();
// now get rid of the window/sheet
if (mWindowType == eWindowType_sheet) {
if (mSheetNeedsShow) {
// This is an attempt to hide a sheet that never had a chance to
// be shown. There's nothing to do other than make sure that it
// won't show.
mSheetNeedsShow = false;
} else {
// get sheet's parent *before* hiding the sheet (which breaks the linkage)
NSWindow* sheetParent = mSheetWindowParent;
// hide the sheet
[NSApp endSheet:mWindow];
[TopLevelWindowData deactivateInWindow:mWindow];
nsCOMPtr<nsIWidget> siblingSheetToShow;
bool parentIsSheet = false;
if (nativeParentWindow && piParentWidget &&
NS_SUCCEEDED(
piParentWidget->GetChildSheet(false, getter_AddRefs(siblingSheetToShow))) &&
siblingSheetToShow) {
// First, give sibling sheets an opportunity to show.
siblingSheetToShow->Show(true);
} else if (nativeParentWindow && piParentWidget &&
NS_SUCCEEDED(piParentWidget->GetIsSheet(&parentIsSheet)) && parentIsSheet) {
// Only set contextInfo if the parent of the parent sheet we're about
// to restore isn't itself a sheet.
NSWindow* contextInfo = sheetParent;
nsIWidget* grandparentWidget = nil;
if (NS_SUCCEEDED(piParentWidget->GetRealParent(&grandparentWidget)) &&
grandparentWidget) {
nsCOMPtr<nsPIWidgetCocoa> piGrandparentWidget(do_QueryInterface(grandparentWidget));
bool grandparentIsSheet = false;
if (piGrandparentWidget &&
NS_SUCCEEDED(piGrandparentWidget->GetIsSheet(&grandparentIsSheet)) &&
grandparentIsSheet) {
contextInfo = nil;
}
}
// If there are no sibling sheets, but the parent is a sheet, restore
// it. It wasn't sent any deactivate events when it was hidden, so
// don't call through Show, just let the OS put it back up.
[NSApp beginSheet:nativeParentWindow
modalForWindow:sheetParent
modalDelegate:[nativeParentWindow delegate]
didEndSelector:@selector(didEndSheet:returnCode:contextInfo:)
contextInfo:contextInfo];
} else {
// Sheet, that was hard. No more siblings or parents, going back
// to a real window.
NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
[sheetParent makeKeyAndOrderFront:nil];
NS_OBJC_END_TRY_ABORT_BLOCK;
}
SendSetZLevelEvent();
}
} else {
// If the window is a popup window with a parent window we need to
// unhook it here before ordering it out. When you order out the child
// of a window it hides the parent window.
if (mWindowType == eWindowType_popup && nativeParentWindow)
[nativeParentWindow removeChildWindow:mWindow];
[mWindow orderOut:nil];
// If our popup window is a non-native context menu, tell the OS (and
// other programs) that a menu has closed.
if ([mWindow isKindOfClass:[PopupWindow class]] && [(PopupWindow*)mWindow isContextMenu]) {
[[NSDistributedNotificationCenter defaultCenter]
postNotificationName:@"com.apple.HIToolbox.endMenuTrackingNotification"
object:@"org.mozilla.gecko.PopupWindow"];
}
}
}
[mWindow setBeingShown:NO];
NS_OBJC_END_TRY_ABORT_BLOCK;
}
struct ShadowParams {
float standardDeviation;
float density;
int offsetX;
int offsetY;
unsigned int flags;
};
// These numbers have been determined by looking at the results of
// CGSGetWindowShadowAndRimParameters for native window types.
static const ShadowParams kWindowShadowParametersPreYosemite[] = {
{0.0f, 0.0f, 0, 0, 0}, // none
{8.0f, 0.5f, 0, 6, 1}, // default
{10.0f, 0.44f, 0, 10, 512}, // menu
{8.0f, 0.5f, 0, 6, 1}, // tooltip
{4.0f, 0.6f, 0, 4, 512} // sheet
};
static const ShadowParams kWindowShadowParametersPostYosemite[] = {
{0.0f, 0.0f, 0, 0, 0}, // none
{8.0f, 0.5f, 0, 6, 1}, // default
{9.882353f, 0.3f, 0, 4, 0}, // menu
{3.294118f, 0.2f, 0, 1, 0}, // tooltip
{9.882353f, 0.3f, 0, 4, 0} // sheet
};
// This method will adjust the window shadow style for popup windows after
// they have been made visible. Before they're visible, their window number
// might be -1, which is not useful.
// We won't attempt to change the shadow for windows that can acquire key state
// since OS X will reset the shadow whenever that happens.
void nsCocoaWindow::AdjustWindowShadow() {
NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
if (!mWindow || ![mWindow isVisible] || ![mWindow hasShadow] || [mWindow canBecomeKeyWindow] ||
[mWindow windowNumber] == -1)
return;
const ShadowParams& params = nsCocoaFeatures::OnYosemiteOrLater()
? kWindowShadowParametersPostYosemite[mShadowStyle]
: kWindowShadowParametersPreYosemite[mShadowStyle];
CGSConnection cid = _CGSDefaultConnection();
CGSSetWindowShadowAndRimParameters(cid, [mWindow windowNumber], params.standardDeviation,
params.density, params.offsetX, params.offsetY, params.flags);
NS_OBJC_END_TRY_ABORT_BLOCK;
}
static const NSUInteger kWindowBackgroundBlurRadius = 4;
void nsCocoaWindow::SetWindowBackgroundBlur() {
NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
if (!mWindow || ![mWindow isVisible] || [mWindow windowNumber] == -1) return;
// Only blur the background of menus and fake sheets.
if (mShadowStyle != NS_STYLE_WINDOW_SHADOW_MENU && mShadowStyle != NS_STYLE_WINDOW_SHADOW_SHEET)
return;
CGSConnection cid = _CGSDefaultConnection();
CGSSetWindowBackgroundBlurRadius(cid, [mWindow windowNumber], kWindowBackgroundBlurRadius);
NS_OBJC_END_TRY_ABORT_BLOCK;
}
nsresult nsCocoaWindow::ConfigureChildren(const nsTArray<Configuration>& aConfigurations) {
if (mPopupContentView) {
mPopupContentView->ConfigureChildren(aConfigurations);
}