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 pathnsXULPopupManager.cpp
2679 lines (2305 loc) · 95.6 KB
/
nsXULPopupManager.cpp
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: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=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 "nsGkAtoms.h"
#include "nsXULPopupManager.h"
#include "nsMenuFrame.h"
#include "nsMenuPopupFrame.h"
#include "nsMenuBarFrame.h"
#include "nsMenuBarListener.h"
#include "nsContentUtils.h"
#include "nsXULElement.h"
#include "nsIDOMXULCommandDispatcher.h"
#include "nsCSSFrameConstructor.h"
#include "nsGlobalWindow.h"
#include "nsIContentInlines.h"
#include "nsLayoutUtils.h"
#include "nsViewManager.h"
#include "nsITimer.h"
#include "nsFocusManager.h"
#include "nsIDocShell.h"
#include "nsPIDOMWindow.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsIBaseWindow.h"
#include "nsCaret.h"
#include "mozilla/dom/Document.h"
#include "nsPIWindowRoot.h"
#include "nsFrameManager.h"
#include "nsIObserverService.h"
#include "mozilla/AnimationUtils.h"
#include "mozilla/dom/DocumentInlines.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/Event.h" // for Event
#include "mozilla/dom/HTMLSlotElement.h"
#include "mozilla/dom/KeyboardEvent.h"
#include "mozilla/dom/KeyboardEventBinding.h"
#include "mozilla/dom/MouseEvent.h"
#include "mozilla/dom/UIEvent.h"
#include "mozilla/dom/UserActivation.h"
#include "mozilla/EventDispatcher.h"
#include "mozilla/LookAndFeel.h"
#include "mozilla/MouseEvents.h"
#include "mozilla/PresShell.h"
#include "mozilla/Services.h"
#include "mozilla/StaticPrefs_ui.h"
#include "mozilla/StaticPrefs_xul.h"
#include "mozilla/widget/nsAutoRollup.h"
using namespace mozilla;
using namespace mozilla::dom;
static_assert(KeyboardEvent_Binding::DOM_VK_HOME ==
KeyboardEvent_Binding::DOM_VK_END + 1 &&
KeyboardEvent_Binding::DOM_VK_LEFT ==
KeyboardEvent_Binding::DOM_VK_END + 2 &&
KeyboardEvent_Binding::DOM_VK_UP ==
KeyboardEvent_Binding::DOM_VK_END + 3 &&
KeyboardEvent_Binding::DOM_VK_RIGHT ==
KeyboardEvent_Binding::DOM_VK_END + 4 &&
KeyboardEvent_Binding::DOM_VK_DOWN ==
KeyboardEvent_Binding::DOM_VK_END + 5,
"nsXULPopupManager assumes some keyCode values are consecutive");
const nsNavigationDirection DirectionFromKeyCodeTable[2][6] = {
{
eNavigationDirection_Last, // KeyboardEvent_Binding::DOM_VK_END
eNavigationDirection_First, // KeyboardEvent_Binding::DOM_VK_HOME
eNavigationDirection_Start, // KeyboardEvent_Binding::DOM_VK_LEFT
eNavigationDirection_Before, // KeyboardEvent_Binding::DOM_VK_UP
eNavigationDirection_End, // KeyboardEvent_Binding::DOM_VK_RIGHT
eNavigationDirection_After // KeyboardEvent_Binding::DOM_VK_DOWN
},
{
eNavigationDirection_Last, // KeyboardEvent_Binding::DOM_VK_END
eNavigationDirection_First, // KeyboardEvent_Binding::DOM_VK_HOME
eNavigationDirection_End, // KeyboardEvent_Binding::DOM_VK_LEFT
eNavigationDirection_Before, // KeyboardEvent_Binding::DOM_VK_UP
eNavigationDirection_Start, // KeyboardEvent_Binding::DOM_VK_RIGHT
eNavigationDirection_After // KeyboardEvent_Binding::DOM_VK_DOWN
}};
nsXULPopupManager* nsXULPopupManager::sInstance = nullptr;
nsIContent* nsMenuChainItem::Content() { return mFrame->GetContent(); }
void nsMenuChainItem::SetParent(nsMenuChainItem* aParent) {
if (mParent) {
NS_ASSERTION(mParent->mChild == this,
"Unexpected - parent's child not set to this");
mParent->mChild = nullptr;
}
mParent = aParent;
if (mParent) {
if (mParent->mChild) mParent->mChild->mParent = nullptr;
mParent->mChild = this;
}
}
void nsMenuChainItem::Detach(nsMenuChainItem** aRoot) {
// If the item has a child, set the child's parent to this item's parent,
// effectively removing the item from the chain. If the item has no child,
// just set the parent to null.
if (mChild) {
NS_ASSERTION(this != *aRoot,
"Unexpected - popup with child at end of chain");
mChild->SetParent(mParent);
} else {
// An item without a child should be the first item in the chain, so set
// the first item pointer, pointed to by aRoot, to the parent.
NS_ASSERTION(this == *aRoot,
"Unexpected - popup with no child not at end of chain");
*aRoot = mParent;
SetParent(nullptr);
}
}
void nsMenuChainItem::UpdateFollowAnchor() {
mFollowAnchor = mFrame->ShouldFollowAnchor(mCurrentRect);
}
void nsMenuChainItem::CheckForAnchorChange() {
if (mFollowAnchor) {
mFrame->CheckForAnchorChange(mCurrentRect);
}
}
NS_IMPL_ISUPPORTS(nsXULPopupManager, nsIDOMEventListener, nsIObserver)
nsXULPopupManager::nsXULPopupManager()
: mRangeOffset(0),
mCachedMousePoint(0, 0),
mCachedModifiers(0),
mActiveMenuBar(nullptr),
mPopups(nullptr),
mTimerMenu(nullptr) {
nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
if (obs) {
obs->AddObserver(this, "xpcom-shutdown", false);
}
}
nsXULPopupManager::~nsXULPopupManager() {
NS_ASSERTION(!mPopups, "XUL popups still open");
}
nsresult nsXULPopupManager::Init() {
sInstance = new nsXULPopupManager();
NS_ENSURE_TRUE(sInstance, NS_ERROR_OUT_OF_MEMORY);
NS_ADDREF(sInstance);
return NS_OK;
}
void nsXULPopupManager::Shutdown() { NS_IF_RELEASE(sInstance); }
NS_IMETHODIMP
nsXULPopupManager::Observe(nsISupports* aSubject, const char* aTopic,
const char16_t* aData) {
if (!nsCRT::strcmp(aTopic, "xpcom-shutdown")) {
if (mKeyListener) {
mKeyListener->RemoveEventListener(NS_LITERAL_STRING("keypress"), this,
true);
mKeyListener->RemoveEventListener(NS_LITERAL_STRING("keydown"), this,
true);
mKeyListener->RemoveEventListener(NS_LITERAL_STRING("keyup"), this, true);
mKeyListener = nullptr;
}
mRangeParentContent = nullptr;
// mOpeningPopup is cleared explicitly soon after using it.
nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
if (obs) {
obs->RemoveObserver(this, "xpcom-shutdown");
}
}
return NS_OK;
}
nsXULPopupManager* nsXULPopupManager::GetInstance() {
MOZ_ASSERT(sInstance);
return sInstance;
}
bool nsXULPopupManager::Rollup(uint32_t aCount, bool aFlush,
const nsIntPoint* pos,
nsIContent** aLastRolledUp) {
if (aLastRolledUp) {
*aLastRolledUp = nullptr;
}
// We can disable the autohide behavior via a pref to ease debugging.
if (StaticPrefs::ui_popup_disable_autohide()) {
// Required on linux to allow events to work on other targets.
if (mWidget) {
mWidget->CaptureRollupEvents(nullptr, false);
}
return false;
}
bool consume = false;
nsMenuChainItem* item = GetTopVisibleMenu();
if (item) {
if (aLastRolledUp) {
// We need to get the popup that will be closed last, so that widget can
// keep track of it so it doesn't reopen if a mousedown event is going to
// processed. Keep going up the menu chain to get the first level menu of
// the same type. If a different type is encountered it means we have,
// for example, a menulist or context menu inside a panel, and we want to
// treat these as distinct. It's possible that this menu doesn't end up
// closing because the popuphiding event was cancelled, but in that case
// we don't need to deal with the menu reopening as it will already still
// be open.
nsMenuChainItem* first = item;
while (first->GetParent()) {
nsMenuChainItem* parent = first->GetParent();
if (first->Frame()->PopupType() != parent->Frame()->PopupType() ||
first->IsContextMenu() != parent->IsContextMenu()) {
break;
}
first = parent;
}
*aLastRolledUp = first->Content();
}
ConsumeOutsideClicksResult consumeResult =
item->Frame()->ConsumeOutsideClicks();
consume = (consumeResult == ConsumeOutsideClicks_True);
bool rollup = true;
// If norolluponanchor is true, then don't rollup when clicking the anchor.
// This would be used to allow adjusting the caret position in an
// autocomplete field without hiding the popup for example.
bool noRollupOnAnchor =
(!consume && pos &&
item->Frame()->GetContent()->AsElement()->AttrValueIs(
kNameSpaceID_None, nsGkAtoms::norolluponanchor, nsGkAtoms::_true,
eCaseMatters));
// When ConsumeOutsideClicks_ParentOnly is used, always consume the click
// when the click was over the anchor. This way, clicking on a menu doesn't
// reopen the menu.
if ((consumeResult == ConsumeOutsideClicks_ParentOnly ||
noRollupOnAnchor) &&
pos) {
nsMenuPopupFrame* popupFrame = item->Frame();
CSSIntRect anchorRect;
if (popupFrame->IsAnchored()) {
// Check if the popup has a screen anchor rectangle. If not, get the
// rectangle from the anchor element.
anchorRect =
CSSIntRect::FromUnknownRect(popupFrame->GetScreenAnchorRect());
if (anchorRect.x == -1 || anchorRect.y == -1) {
nsCOMPtr<nsIContent> anchor = popupFrame->GetAnchor();
// Check if the anchor has indicated another node to use for checking
// for roll-up. That way, we can anchor a popup on anonymous content
// or an individual icon, while clicking elsewhere within a button or
// other container doesn't result in us re-opening the popup.
if (anchor && anchor->IsElement()) {
nsAutoString consumeAnchor;
anchor->AsElement()->GetAttr(
kNameSpaceID_None, nsGkAtoms::consumeanchor, consumeAnchor);
if (!consumeAnchor.IsEmpty()) {
Document* doc = anchor->GetOwnerDocument();
nsIContent* newAnchor = doc->GetElementById(consumeAnchor);
if (newAnchor) {
anchor = newAnchor;
}
}
}
if (anchor && anchor->GetPrimaryFrame()) {
anchorRect = anchor->GetPrimaryFrame()->GetScreenRect();
}
}
}
// It's possible that some other element is above the anchor at the same
// position, but the only thing that would happen is that the mouse
// event will get consumed, so here only a quick coordinates check is
// done rather than a slower complete check of what is at that location.
nsPresContext* presContext = item->Frame()->PresContext();
CSSIntPoint posCSSPixels(presContext->DevPixelsToIntCSSPixels(pos->x),
presContext->DevPixelsToIntCSSPixels(pos->y));
if (anchorRect.Contains(posCSSPixels)) {
if (consumeResult == ConsumeOutsideClicks_ParentOnly) {
consume = true;
}
if (noRollupOnAnchor) {
rollup = false;
}
}
}
if (rollup) {
// if a number of popups to close has been specified, determine the last
// popup to close
nsIContent* lastPopup = nullptr;
if (aCount != UINT32_MAX) {
nsMenuChainItem* last = item;
while (--aCount && last->GetParent()) {
last = last->GetParent();
}
if (last) {
lastPopup = last->Content();
}
}
nsPresContext* presContext = item->Frame()->PresContext();
RefPtr<nsViewManager> viewManager =
presContext->PresShell()->GetViewManager();
HidePopup(item->Content(), true, true, false, true, lastPopup);
if (aFlush) {
// The popup's visibility doesn't update until the minimize animation
// has finished, so call UpdateWidgetGeometry to update it right away.
viewManager->UpdateWidgetGeometry();
}
}
}
return consume;
}
////////////////////////////////////////////////////////////////////////
bool nsXULPopupManager::ShouldRollupOnMouseWheelEvent() {
// should rollup only for autocomplete widgets
// XXXndeakin this should really be something the popup has more control over
nsMenuChainItem* item = GetTopVisibleMenu();
if (!item) return false;
nsIContent* content = item->Frame()->GetContent();
if (!content || !content->IsElement()) return false;
Element* element = content->AsElement();
if (element->AttrValueIs(kNameSpaceID_None, nsGkAtoms::rolluponmousewheel,
nsGkAtoms::_true, eCaseMatters))
return true;
if (element->AttrValueIs(kNameSpaceID_None, nsGkAtoms::rolluponmousewheel,
nsGkAtoms::_false, eCaseMatters))
return false;
nsAutoString value;
element->GetAttr(kNameSpaceID_None, nsGkAtoms::type, value);
return StringBeginsWith(value, NS_LITERAL_STRING("autocomplete"));
}
bool nsXULPopupManager::ShouldConsumeOnMouseWheelEvent() {
nsMenuChainItem* item = GetTopVisibleMenu();
if (!item) return false;
nsMenuPopupFrame* frame = item->Frame();
if (frame->PopupType() != ePopupTypePanel) return true;
return !frame->GetContent()->AsElement()->AttrValueIs(
kNameSpaceID_None, nsGkAtoms::type, nsGkAtoms::arrow, eCaseMatters);
}
// a menu should not roll up if activated by a mouse activate message (eg.
// X-mouse)
bool nsXULPopupManager::ShouldRollupOnMouseActivate() { return false; }
uint32_t nsXULPopupManager::GetSubmenuWidgetChain(
nsTArray<nsIWidget*>* aWidgetChain) {
// this method is used by the widget code to determine the list of popups
// that are open. If a mouse click occurs outside one of these popups, the
// panels will roll up. If the click is inside a popup, they will not roll up
uint32_t count = 0, sameTypeCount = 0;
NS_ASSERTION(aWidgetChain, "null parameter");
nsMenuChainItem* item = GetTopVisibleMenu();
while (item) {
nsMenuChainItem* parent = item->GetParent();
if (!item->IsNoAutoHide()) {
nsCOMPtr<nsIWidget> widget = item->Frame()->GetWidget();
NS_ASSERTION(widget, "open popup has no widget");
aWidgetChain->AppendElement(widget.get());
// In the case when a menulist inside a panel is open, clicking in the
// panel should still roll up the menu, so if a different type is found,
// stop scanning.
if (!sameTypeCount) {
count++;
if (!parent ||
item->Frame()->PopupType() != parent->Frame()->PopupType() ||
item->IsContextMenu() != parent->IsContextMenu()) {
sameTypeCount = count;
}
}
}
item = parent;
}
return sameTypeCount;
}
nsIWidget* nsXULPopupManager::GetRollupWidget() {
nsMenuChainItem* item = GetTopVisibleMenu();
return item ? item->Frame()->GetWidget() : nullptr;
}
void nsXULPopupManager::AdjustPopupsOnWindowChange(
nsPIDOMWindowOuter* aWindow) {
// When the parent window is moved, adjust any child popups. Dismissable
// menus and panels are expected to roll up when a window is moved, so there
// is no need to check these popups, only the noautohide popups.
// The items are added to a list so that they can be adjusted bottom to top.
nsTArray<nsMenuPopupFrame*> list;
nsMenuChainItem* item = mPopups;
while (item) {
// only move popups that are within the same window and where auto
// positioning has not been disabled
nsMenuPopupFrame* frame = item->Frame();
if (item->IsNoAutoHide() && frame->GetAutoPosition()) {
nsIContent* popup = frame->GetContent();
if (popup) {
Document* document = popup->GetUncomposedDoc();
if (document) {
if (nsPIDOMWindowOuter* window = document->GetWindow()) {
window = window->GetPrivateRoot();
if (window == aWindow) {
list.AppendElement(frame);
}
}
}
}
}
item = item->GetParent();
}
for (int32_t l = list.Length() - 1; l >= 0; l--) {
list[l]->SetPopupPosition(nullptr, true, false, true);
}
}
void nsXULPopupManager::AdjustPopupsOnWindowChange(PresShell* aPresShell) {
if (aPresShell->GetDocument()) {
AdjustPopupsOnWindowChange(aPresShell->GetDocument()->GetWindow());
}
}
static nsMenuPopupFrame* GetPopupToMoveOrResize(nsIFrame* aFrame) {
nsMenuPopupFrame* menuPopupFrame = do_QueryFrame(aFrame);
if (!menuPopupFrame) return nullptr;
// no point moving or resizing hidden popups
if (!menuPopupFrame->IsVisible()) return nullptr;
nsIWidget* widget = menuPopupFrame->GetWidget();
if (widget && !widget->IsVisible()) return nullptr;
return menuPopupFrame;
}
void nsXULPopupManager::PopupMoved(nsIFrame* aFrame, nsIntPoint aPnt) {
nsMenuPopupFrame* menuPopupFrame = GetPopupToMoveOrResize(aFrame);
if (!menuPopupFrame) return;
nsView* view = menuPopupFrame->GetView();
if (!view) return;
// Don't do anything if the popup is already at the specified location. This
// prevents recursive calls when a popup is positioned.
LayoutDeviceIntRect curDevSize = view->CalcWidgetBounds(eWindowType_popup);
nsIWidget* widget = menuPopupFrame->GetWidget();
if (curDevSize.x == aPnt.x && curDevSize.y == aPnt.y &&
(!widget ||
widget->GetClientOffset() == menuPopupFrame->GetLastClientOffset())) {
return;
}
// Update the popup's position using SetPopupPosition if the popup is
// anchored and at the parent level as these maintain their position
// relative to the parent window. Otherwise, just update the popup to
// the specified screen coordinates.
if (menuPopupFrame->IsAnchored() &&
menuPopupFrame->PopupLevel() == ePopupLevelParent) {
menuPopupFrame->SetPopupPosition(nullptr, true, false, true);
} else {
CSSPoint cssPos = LayoutDeviceIntPoint::FromUnknownPoint(aPnt) /
menuPopupFrame->PresContext()->CSSToDevPixelScale();
menuPopupFrame->MoveTo(RoundedToInt(cssPos), false);
}
}
void nsXULPopupManager::PopupResized(nsIFrame* aFrame,
LayoutDeviceIntSize aSize) {
nsMenuPopupFrame* menuPopupFrame = GetPopupToMoveOrResize(aFrame);
if (!menuPopupFrame) return;
nsView* view = menuPopupFrame->GetView();
if (!view) return;
LayoutDeviceIntRect curDevSize = view->CalcWidgetBounds(eWindowType_popup);
// If the size is what we think it is, we have nothing to do.
if (curDevSize.width == aSize.width && curDevSize.height == aSize.height)
return;
Element* popup = menuPopupFrame->GetContent()->AsElement();
// Only set the width and height if the popup already has these attributes.
if (!popup->HasAttr(kNameSpaceID_None, nsGkAtoms::width) ||
!popup->HasAttr(kNameSpaceID_None, nsGkAtoms::height)) {
return;
}
// The size is different. Convert the actual size to css pixels and store it
// as 'width' and 'height' attributes on the popup.
nsPresContext* presContext = menuPopupFrame->PresContext();
CSSIntSize newCSS(presContext->DevPixelsToIntCSSPixels(aSize.width),
presContext->DevPixelsToIntCSSPixels(aSize.height));
nsAutoString width, height;
width.AppendInt(newCSS.width);
height.AppendInt(newCSS.height);
popup->SetAttr(kNameSpaceID_None, nsGkAtoms::width, width, false);
popup->SetAttr(kNameSpaceID_None, nsGkAtoms::height, height, true);
}
nsMenuPopupFrame* nsXULPopupManager::GetPopupFrameForContent(
nsIContent* aContent, bool aShouldFlush) {
if (aShouldFlush) {
Document* document = aContent->GetUncomposedDoc();
if (document) {
if (RefPtr<PresShell> presShell = document->GetPresShell()) {
presShell->FlushPendingNotifications(FlushType::Layout);
}
}
}
return do_QueryFrame(aContent->GetPrimaryFrame());
}
nsMenuChainItem* nsXULPopupManager::GetTopVisibleMenu() {
nsMenuChainItem* item = mPopups;
while (item) {
if (!item->IsNoAutoHide() &&
item->Frame()->PopupState() != ePopupInvisible) {
return item;
}
item = item->GetParent();
}
return nullptr;
}
void nsXULPopupManager::InitTriggerEvent(Event* aEvent, nsIContent* aPopup,
nsIContent** aTriggerContent) {
mCachedMousePoint = LayoutDeviceIntPoint(0, 0);
if (aTriggerContent) {
*aTriggerContent = nullptr;
if (aEvent) {
// get the trigger content from the event
nsCOMPtr<nsIContent> target = do_QueryInterface(aEvent->GetTarget());
target.forget(aTriggerContent);
}
}
mCachedModifiers = 0;
RefPtr<UIEvent> uiEvent = aEvent ? aEvent->AsUIEvent() : nullptr;
if (uiEvent) {
mRangeOffset = -1;
mRangeParentContent =
uiEvent->GetRangeParentContentAndOffset(&mRangeOffset);
// get the event coordinates relative to the root frame of the document
// containing the popup.
NS_ASSERTION(aPopup, "Expected a popup node");
WidgetEvent* event = aEvent->WidgetEventPtr();
if (event) {
WidgetInputEvent* inputEvent = event->AsInputEvent();
if (inputEvent) {
mCachedModifiers = inputEvent->mModifiers;
}
Document* doc = aPopup->GetUncomposedDoc();
if (doc) {
PresShell* presShell = doc->GetPresShell();
nsPresContext* presContext;
if (presShell && (presContext = presShell->GetPresContext())) {
nsPresContext* rootDocPresContext = presContext->GetRootPresContext();
if (!rootDocPresContext) return;
nsIFrame* rootDocumentRootFrame =
rootDocPresContext->PresShell()->GetRootFrame();
if ((event->mClass == eMouseEventClass ||
event->mClass == eMouseScrollEventClass ||
event->mClass == eWheelEventClass) &&
!event->AsGUIEvent()->mWidget) {
// no widget, so just use the client point if available
MouseEvent* mouseEvent = aEvent->AsMouseEvent();
nsIntPoint clientPt(mouseEvent->ClientX(), mouseEvent->ClientY());
// XXX this doesn't handle IFRAMEs in transforms
nsPoint thisDocToRootDocOffset =
presShell->GetRootFrame()->GetOffsetToCrossDoc(
rootDocumentRootFrame);
// convert to device pixels
mCachedMousePoint.x = presContext->AppUnitsToDevPixels(
nsPresContext::CSSPixelsToAppUnits(clientPt.x) +
thisDocToRootDocOffset.x);
mCachedMousePoint.y = presContext->AppUnitsToDevPixels(
nsPresContext::CSSPixelsToAppUnits(clientPt.y) +
thisDocToRootDocOffset.y);
} else if (rootDocumentRootFrame) {
nsPoint pnt = nsLayoutUtils::GetEventCoordinatesRelativeTo(
event, rootDocumentRootFrame);
mCachedMousePoint = LayoutDeviceIntPoint(
rootDocPresContext->AppUnitsToDevPixels(pnt.x),
rootDocPresContext->AppUnitsToDevPixels(pnt.y));
}
}
}
}
} else {
mRangeParentContent = nullptr;
mRangeOffset = 0;
}
}
void nsXULPopupManager::SetActiveMenuBar(nsMenuBarFrame* aMenuBar,
bool aActivate) {
if (aActivate)
mActiveMenuBar = aMenuBar;
else if (mActiveMenuBar == aMenuBar)
mActiveMenuBar = nullptr;
UpdateKeyboardListeners();
}
void nsXULPopupManager::ShowMenu(nsIContent* aMenu, bool aSelectFirstItem,
bool aAsynchronous) {
nsMenuFrame* menuFrame = do_QueryFrame(aMenu->GetPrimaryFrame());
if (!menuFrame || !menuFrame->IsMenu()) return;
nsMenuPopupFrame* popupFrame = menuFrame->GetPopup();
if (!popupFrame || !MayShowPopup(popupFrame)) return;
// inherit whether or not we're a context menu from the parent
bool parentIsContextMenu = false;
bool onMenuBar = false;
bool onmenu = menuFrame->IsOnMenu();
nsMenuParent* parent = menuFrame->GetMenuParent();
if (parent && onmenu) {
parentIsContextMenu = parent->IsContextMenu();
onMenuBar = parent->IsMenuBar();
}
nsAutoString position;
#ifdef XP_MACOSX
if (aMenu->IsXULElement(nsGkAtoms::menulist)) {
position.AssignLiteral("selection");
} else
#endif
if (onMenuBar || !onmenu)
position.AssignLiteral("after_start");
else
position.AssignLiteral("end_before");
// there is no trigger event for menus
InitTriggerEvent(nullptr, nullptr, nullptr);
popupFrame->InitializePopup(aMenu, nullptr, position, 0, 0,
MenuPopupAnchorType_Node, true);
if (aAsynchronous) {
nsCOMPtr<nsIRunnable> event = new nsXULPopupShowingEvent(
popupFrame->GetContent(), parentIsContextMenu, aSelectFirstItem);
aMenu->OwnerDoc()->Dispatch(TaskCategory::Other, event.forget());
} else {
nsCOMPtr<nsIContent> popupContent = popupFrame->GetContent();
FirePopupShowingEvent(popupContent, parentIsContextMenu, aSelectFirstItem,
nullptr);
}
}
void nsXULPopupManager::ShowPopup(nsIContent* aPopup,
nsIContent* aAnchorContent,
const nsAString& aPosition, int32_t aXPos,
int32_t aYPos, bool aIsContextMenu,
bool aAttributesOverride,
bool aSelectFirstItem, Event* aTriggerEvent) {
nsMenuPopupFrame* popupFrame = GetPopupFrameForContent(aPopup, true);
if (!popupFrame || !MayShowPopup(popupFrame)) return;
nsCOMPtr<nsIContent> triggerContent;
InitTriggerEvent(aTriggerEvent, aPopup, getter_AddRefs(triggerContent));
popupFrame->InitializePopup(aAnchorContent, triggerContent, aPosition, aXPos,
aYPos, MenuPopupAnchorType_Node,
aAttributesOverride);
FirePopupShowingEvent(aPopup, aIsContextMenu, aSelectFirstItem,
aTriggerEvent);
}
void nsXULPopupManager::ShowPopupAtScreen(nsIContent* aPopup, int32_t aXPos,
int32_t aYPos, bool aIsContextMenu,
Event* aTriggerEvent) {
nsMenuPopupFrame* popupFrame = GetPopupFrameForContent(aPopup, true);
if (!popupFrame || !MayShowPopup(popupFrame)) return;
nsCOMPtr<nsIContent> triggerContent;
InitTriggerEvent(aTriggerEvent, aPopup, getter_AddRefs(triggerContent));
popupFrame->InitializePopupAtScreen(triggerContent, aXPos, aYPos,
aIsContextMenu);
FirePopupShowingEvent(aPopup, aIsContextMenu, false, aTriggerEvent);
}
void nsXULPopupManager::ShowPopupAtScreenRect(
nsIContent* aPopup, const nsAString& aPosition, const nsIntRect& aRect,
bool aIsContextMenu, bool aAttributesOverride, Event* aTriggerEvent) {
nsMenuPopupFrame* popupFrame = GetPopupFrameForContent(aPopup, true);
if (!popupFrame || !MayShowPopup(popupFrame)) return;
nsCOMPtr<nsIContent> triggerContent;
InitTriggerEvent(aTriggerEvent, aPopup, getter_AddRefs(triggerContent));
popupFrame->InitializePopupAtRect(triggerContent, aPosition, aRect,
aAttributesOverride);
FirePopupShowingEvent(aPopup, aIsContextMenu, false, aTriggerEvent);
}
void nsXULPopupManager::ShowTooltipAtScreen(nsIContent* aPopup,
nsIContent* aTriggerContent,
int32_t aXPos, int32_t aYPos) {
nsMenuPopupFrame* popupFrame = GetPopupFrameForContent(aPopup, true);
if (!popupFrame || !MayShowPopup(popupFrame)) return;
InitTriggerEvent(nullptr, nullptr, nullptr);
nsPresContext* pc = popupFrame->PresContext();
mCachedMousePoint = LayoutDeviceIntPoint(pc->CSSPixelsToDevPixels(aXPos),
pc->CSSPixelsToDevPixels(aYPos));
// coordinates are relative to the root widget
nsPresContext* rootPresContext = pc->GetRootPresContext();
if (rootPresContext) {
nsIWidget* rootWidget = rootPresContext->GetRootWidget();
if (rootWidget) {
mCachedMousePoint -= rootWidget->WidgetToScreenOffset();
}
}
popupFrame->InitializePopupAtScreen(aTriggerContent, aXPos, aYPos, false);
FirePopupShowingEvent(aPopup, false, false, nullptr);
}
static void CheckCaretDrawingState() {
// There is 1 caret per document, we need to find the focused
// document and erase its caret.
nsIFocusManager* fm = nsFocusManager::GetFocusManager();
if (fm) {
nsCOMPtr<mozIDOMWindowProxy> window;
fm->GetFocusedWindow(getter_AddRefs(window));
if (!window) return;
auto* piWindow = nsPIDOMWindowOuter::From(window);
MOZ_ASSERT(piWindow);
nsCOMPtr<Document> focusedDoc = piWindow->GetDoc();
if (!focusedDoc) return;
PresShell* presShell = focusedDoc->GetPresShell();
if (!presShell) {
return;
}
RefPtr<nsCaret> caret = presShell->GetCaret();
if (!caret) return;
caret->SchedulePaint();
}
}
void nsXULPopupManager::ShowPopupCallback(nsIContent* aPopup,
nsMenuPopupFrame* aPopupFrame,
bool aIsContextMenu,
bool aSelectFirstItem) {
nsPopupType popupType = aPopupFrame->PopupType();
bool ismenu = (popupType == ePopupTypeMenu);
// Popups normally hide when an outside click occurs. Panels may use
// the noautohide attribute to disable this behaviour. It is expected
// that the application will hide these popups manually. The tooltip
// listener will handle closing the tooltip also.
bool isNoAutoHide =
aPopupFrame->IsNoAutoHide() || popupType == ePopupTypeTooltip;
nsMenuChainItem* item =
new nsMenuChainItem(aPopupFrame, isNoAutoHide, aIsContextMenu, popupType);
if (!item) return;
// install keyboard event listeners for navigating menus. For panels, the
// escape key may be used to close the panel. However, the ignorekeys
// attribute may be used to disable adding these event listeners for popups
// that want to handle their own keyboard events.
nsAutoString ignorekeys;
if (aPopup->IsElement()) {
aPopup->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::ignorekeys,
ignorekeys);
}
if (ignorekeys.EqualsLiteral("true")) {
item->SetIgnoreKeys(eIgnoreKeys_True);
} else if (ignorekeys.EqualsLiteral("shortcuts")) {
item->SetIgnoreKeys(eIgnoreKeys_Shortcuts);
}
if (ismenu) {
// if the menu is on a menubar, use the menubar's listener instead
nsMenuFrame* menuFrame = do_QueryFrame(aPopupFrame->GetParent());
if (menuFrame) {
item->SetOnMenuBar(menuFrame->IsOnMenuBar());
}
}
// use a weak frame as the popup will set an open attribute if it is a menu
AutoWeakFrame weakFrame(aPopupFrame);
aPopupFrame->ShowPopup(aIsContextMenu);
NS_ENSURE_TRUE_VOID(weakFrame.IsAlive());
item->UpdateFollowAnchor();
// popups normally hide when an outside click occurs. Panels may use
// the noautohide attribute to disable this behaviour. It is expected
// that the application will hide these popups manually. The tooltip
// listener will handle closing the tooltip also.
nsIContent* oldmenu = nullptr;
if (mPopups) {
oldmenu = mPopups->Content();
}
item->SetParent(mPopups);
mPopups = item;
SetCaptureState(oldmenu);
NS_ENSURE_TRUE_VOID(weakFrame.IsAlive());
if (aSelectFirstItem) {
nsMenuFrame* next = GetNextMenuItem(aPopupFrame, nullptr, true, false);
aPopupFrame->SetCurrentMenuItem(next);
}
if (ismenu) UpdateMenuItems(aPopup);
// Caret visibility may have been affected, ensure that
// the caret isn't now drawn when it shouldn't be.
CheckCaretDrawingState();
}
void nsXULPopupManager::HidePopup(nsIContent* aPopup, bool aHideChain,
bool aDeselectMenu, bool aAsynchronous,
bool aIsCancel, nsIContent* aLastPopup) {
nsMenuPopupFrame* popupFrame = do_QueryFrame(aPopup->GetPrimaryFrame());
if (!popupFrame) {
return;
}
nsMenuChainItem* foundPopup = mPopups;
while (foundPopup) {
if (foundPopup->Content() == aPopup) {
break;
}
foundPopup = foundPopup->GetParent();
}
bool deselectMenu = false;
nsCOMPtr<nsIContent> popupToHide, nextPopup, lastPopup;
if (foundPopup) {
if (foundPopup->IsNoAutoHide()) {
// If this is a noautohide panel, remove it but don't close any other
// panels.
popupToHide = aPopup;
} else {
// At this point, foundPopup will be set to the found item in the list. If
// foundPopup is the topmost menu, the one to remove, then there are no
// other popups to hide. If foundPopup is not the topmost menu, then there
// may be open submenus below it. In this case, we need to make sure that
// those submenus are closed up first. To do this, we scan up the menu
// list to find the topmost popup with only menus between it and
// foundPopup and close that menu first. In synchronous mode, the
// FirePopupHidingEvent method will be called which in turn calls
// HidePopupCallback to close up the next popup in the chain. These two
// methods will be called in sequence recursively to close up all the
// necessary popups. In asynchronous mode, a similar process occurs except
// that the FirePopupHidingEvent method is called asynchronously. In
// either case, nextPopup is set to the content node of the next popup to
// close, and lastPopup is set to the last popup in the chain to close,
// which will be aPopup, or null to close up all menus.
nsMenuChainItem* topMenu = foundPopup;
// Use IsMenu to ensure that foundPopup is a menu and scan down the child
// list until a non-menu is found. If foundPopup isn't a menu at all,
// don't scan and just close up this menu.
if (foundPopup->IsMenu()) {
nsMenuChainItem* child = foundPopup->GetChild();
while (child && child->IsMenu()) {
topMenu = child;
child = child->GetChild();
}
}
deselectMenu = aDeselectMenu;
popupToHide = topMenu->Content();
popupFrame = topMenu->Frame();
// Close up another popup if there is one, and we are either hiding the
// entire chain or the item to hide isn't the topmost popup.
nsMenuChainItem* parent = topMenu->GetParent();
if (parent && (aHideChain || topMenu != foundPopup)) {
while (parent && parent->IsNoAutoHide()) {
parent = parent->GetParent();
}
if (parent) {
nextPopup = parent->Content();
}
}
lastPopup = aLastPopup ? aLastPopup : (aHideChain ? nullptr : aPopup);
}
} else if (popupFrame->PopupState() == ePopupPositioning) {
// When the popup is in the popuppositioning state, it will not be in the
// mPopups list. We need another way to find it and make sure it does not
// continue the popup showing process.
deselectMenu = aDeselectMenu;
popupToHide = aPopup;
}
if (popupToHide) {
nsPopupState state = popupFrame->PopupState();
// If the popup is already being hidden, don't attempt to hide it again
if (state == ePopupHiding) {
return;
}
// Change the popup state to hiding. Don't set the hiding state if the
// popup is invisible, otherwise nsMenuPopupFrame::HidePopup will
// run again. In the invisible state, we just want the events to fire.
if (state != ePopupInvisible) {
popupFrame->SetPopupState(ePopupHiding);
}
// For menus, popupToHide is always the frontmost item in the list to hide.
if (aAsynchronous) {
nsCOMPtr<nsIRunnable> event = new nsXULPopupHidingEvent(
popupToHide, nextPopup, lastPopup, popupFrame->PopupType(),
deselectMenu, aIsCancel);
aPopup->OwnerDoc()->Dispatch(TaskCategory::Other, event.forget());
} else {
RefPtr<nsPresContext> presContext = popupFrame->PresContext();
FirePopupHidingEvent(popupToHide, nextPopup, lastPopup, presContext,
popupFrame->PopupType(), deselectMenu, aIsCancel);
}
}
}
// This is used to hide the popup after a transition finishes.
class TransitionEnder final : public nsIDOMEventListener {
protected:
virtual ~TransitionEnder() {}
public:
nsCOMPtr<nsIContent> mContent;
bool mDeselectMenu;
NS_DECL_CYCLE_COLLECTING_ISUPPORTS
NS_DECL_CYCLE_COLLECTION_CLASS(TransitionEnder)
TransitionEnder(nsIContent* aContent, bool aDeselectMenu)
: mContent(aContent), mDeselectMenu(aDeselectMenu) {}
NS_IMETHOD HandleEvent(Event* aEvent) override {
mContent->RemoveSystemEventListener(NS_LITERAL_STRING("transitionend"),
this, false);
nsMenuPopupFrame* popupFrame = do_QueryFrame(mContent->GetPrimaryFrame());
// Now hide the popup. There could be other properties transitioning, but
// we'll assume they all end at the same time and just hide the popup upon
// the first one ending.
nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
if (pm && popupFrame) {
pm->HidePopupCallback(mContent, popupFrame, nullptr, nullptr,
popupFrame->PopupType(), mDeselectMenu);