forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 2
/
nsFocusManager.cpp
3431 lines (2961 loc) · 118 KB
/
nsFocusManager.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: 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/dom/TabParent.h"
#include "nsFocusManager.h"
#include "nsIInterfaceRequestor.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsIServiceManager.h"
#include "nsGkAtoms.h"
#include "nsContentUtils.h"
#include "nsIDocument.h"
#include "nsIDOMWindow.h"
#include "nsPIDOMWindow.h"
#include "nsIDOMElement.h"
#include "nsIDOMXULElement.h"
#include "nsIDOMHTMLFrameElement.h"
#include "nsIDOMHTMLInputElement.h"
#include "nsIDOMHTMLMapElement.h"
#include "nsIDOMDocument.h"
#include "nsIDOMRange.h"
#include "nsIHTMLDocument.h"
#include "nsIDocShell.h"
#include "nsIDocShellTreeOwner.h"
#include "nsLayoutUtils.h"
#include "nsIPresShell.h"
#include "nsIContentViewer.h"
#include "nsFrameTraversal.h"
#include "nsObjectFrame.h"
#include "nsEventDispatcher.h"
#include "nsEventStateManager.h"
#include "nsIMEStateManager.h"
#include "nsIWebNavigation.h"
#include "nsCaret.h"
#include "nsIBaseWindow.h"
#include "nsViewManager.h"
#include "nsFrameSelection.h"
#include "mozilla/Selection.h"
#include "nsXULPopupManager.h"
#include "nsIDOMNodeFilter.h"
#include "nsIScriptObjectPrincipal.h"
#include "nsIPrincipal.h"
#include "mozAutoDocUpdate.h"
#include "nsFrameLoader.h"
#include "nsIObserverService.h"
#include "nsIScriptError.h"
#include "mozilla/dom/Element.h"
#include "mozilla/LookAndFeel.h"
#include "mozilla/Preferences.h"
#include <algorithm>
#ifdef MOZ_XUL
#include "nsIDOMXULTextboxElement.h"
#include "nsIDOMXULMenuListElement.h"
#endif
#ifdef ACCESSIBILITY
#include "nsAccessibilityService.h"
#endif
using namespace mozilla;
using namespace mozilla::dom;
using namespace mozilla::widget;
#ifdef PR_LOGGING
// Two types of focus pr logging are available:
// 'Focus' for normal focus manager calls
// 'FocusNavigation' for tab and document navigation
PRLogModuleInfo* gFocusLog;
PRLogModuleInfo* gFocusNavigationLog;
#define LOGFOCUS(args) PR_LOG(gFocusLog, 4, args)
#define LOGFOCUSNAVIGATION(args) PR_LOG(gFocusNavigationLog, 4, args)
#define LOGTAG(log, format, content) \
{ \
nsAutoCString tag(NS_LITERAL_CSTRING("(none)")); \
if (content) { \
content->Tag()->ToUTF8String(tag); \
} \
PR_LOG(log, 4, (format, tag.get())); \
}
#define LOGCONTENT(format, content) LOGTAG(gFocusLog, format, content)
#define LOGCONTENTNAVIGATION(format, content) LOGTAG(gFocusNavigationLog, format, content)
#else
#define LOGFOCUS(args)
#define LOGFOCUSNAVIGATION(args)
#define LOGCONTENT(format, content)
#define LOGCONTENTNAVIGATION(format, content)
#endif
struct nsDelayedBlurOrFocusEvent
{
nsDelayedBlurOrFocusEvent(uint32_t aType,
nsIPresShell* aPresShell,
nsIDocument* aDocument,
EventTarget* aTarget)
: mType(aType),
mPresShell(aPresShell),
mDocument(aDocument),
mTarget(aTarget) { }
nsDelayedBlurOrFocusEvent(const nsDelayedBlurOrFocusEvent& aOther)
: mType(aOther.mType),
mPresShell(aOther.mPresShell),
mDocument(aOther.mDocument),
mTarget(aOther.mTarget) { }
uint32_t mType;
nsCOMPtr<nsIPresShell> mPresShell;
nsCOMPtr<nsIDocument> mDocument;
nsCOMPtr<EventTarget> mTarget;
};
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsFocusManager)
NS_INTERFACE_MAP_ENTRY(nsIFocusManager)
NS_INTERFACE_MAP_ENTRY(nsIObserver)
NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIFocusManager)
NS_INTERFACE_MAP_END
NS_IMPL_CYCLE_COLLECTING_ADDREF(nsFocusManager)
NS_IMPL_CYCLE_COLLECTING_RELEASE(nsFocusManager)
NS_IMPL_CYCLE_COLLECTION_6(nsFocusManager,
mActiveWindow,
mFocusedWindow,
mFocusedContent,
mFirstBlurEvent,
mFirstFocusEvent,
mWindowBeingLowered)
nsFocusManager* nsFocusManager::sInstance = nullptr;
bool nsFocusManager::sMouseFocusesFormControl = false;
bool nsFocusManager::sTestMode = false;
static const char* kObservedPrefs[] = {
"accessibility.browsewithcaret",
"accessibility.tabfocus_applies_to_xul",
"accessibility.mouse_focuses_formcontrol",
"focusmanager.testmode",
NULL
};
nsFocusManager::nsFocusManager()
{ }
nsFocusManager::~nsFocusManager()
{
Preferences::RemoveObservers(this, kObservedPrefs);
nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
if (obs) {
obs->RemoveObserver(this, "xpcom-shutdown");
}
}
// static
nsresult
nsFocusManager::Init()
{
nsFocusManager* fm = new nsFocusManager();
NS_ENSURE_TRUE(fm, NS_ERROR_OUT_OF_MEMORY);
NS_ADDREF(fm);
sInstance = fm;
#ifdef PR_LOGGING
gFocusLog = PR_NewLogModule("Focus");
gFocusNavigationLog = PR_NewLogModule("FocusNavigation");
#endif
nsIContent::sTabFocusModelAppliesToXUL =
Preferences::GetBool("accessibility.tabfocus_applies_to_xul",
nsIContent::sTabFocusModelAppliesToXUL);
sMouseFocusesFormControl =
Preferences::GetBool("accessibility.mouse_focuses_formcontrol", false);
sTestMode = Preferences::GetBool("focusmanager.testmode", false);
Preferences::AddWeakObservers(fm, kObservedPrefs);
nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
if (obs) {
obs->AddObserver(fm, "xpcom-shutdown", true);
}
return NS_OK;
}
// static
void
nsFocusManager::Shutdown()
{
NS_IF_RELEASE(sInstance);
}
NS_IMETHODIMP
nsFocusManager::Observe(nsISupports *aSubject,
const char *aTopic,
const PRUnichar *aData)
{
if (!nsCRT::strcmp(aTopic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID)) {
nsDependentString data(aData);
if (data.EqualsLiteral("accessibility.browsewithcaret")) {
UpdateCaretForCaretBrowsingMode();
}
else if (data.EqualsLiteral("accessibility.tabfocus_applies_to_xul")) {
nsIContent::sTabFocusModelAppliesToXUL =
Preferences::GetBool("accessibility.tabfocus_applies_to_xul",
nsIContent::sTabFocusModelAppliesToXUL);
}
else if (data.EqualsLiteral("accessibility.mouse_focuses_formcontrol")) {
sMouseFocusesFormControl =
Preferences::GetBool("accessibility.mouse_focuses_formcontrol",
false);
}
else if (data.EqualsLiteral("focusmanager.testmode")) {
sTestMode = Preferences::GetBool("focusmanager.testmode", false);
}
} else if (!nsCRT::strcmp(aTopic, "xpcom-shutdown")) {
mActiveWindow = nullptr;
mFocusedWindow = nullptr;
mFocusedContent = nullptr;
mFirstBlurEvent = nullptr;
mFirstFocusEvent = nullptr;
mWindowBeingLowered = nullptr;
mDelayedBlurFocusEvents.Clear();
mMouseDownEventHandlingDocument = nullptr;
}
return NS_OK;
}
// given a frame content node, retrieve the nsIDOMWindow displayed in it
static nsPIDOMWindow*
GetContentWindow(nsIContent* aContent)
{
nsIDocument* doc = aContent->GetCurrentDoc();
if (doc) {
nsIDocument* subdoc = doc->GetSubDocumentFor(aContent);
if (subdoc)
return subdoc->GetWindow();
}
return nullptr;
}
// get the current window for the given content node
static nsPIDOMWindow*
GetCurrentWindow(nsIContent* aContent)
{
nsIDocument *doc = aContent->GetCurrentDoc();
return doc ? doc->GetWindow() : nullptr;
}
// static
nsIContent*
nsFocusManager::GetFocusedDescendant(nsPIDOMWindow* aWindow, bool aDeep,
nsPIDOMWindow** aFocusedWindow)
{
NS_ENSURE_TRUE(aWindow, nullptr);
*aFocusedWindow = nullptr;
nsIContent* currentContent = nullptr;
nsPIDOMWindow* window = aWindow->GetOuterWindow();
while (window) {
*aFocusedWindow = window;
currentContent = window->GetFocusedNode();
if (!currentContent || !aDeep)
break;
window = GetContentWindow(currentContent);
}
NS_IF_ADDREF(*aFocusedWindow);
return currentContent;
}
// static
nsIContent*
nsFocusManager::GetRedirectedFocus(nsIContent* aContent)
{
#ifdef MOZ_XUL
if (aContent->IsXUL()) {
nsCOMPtr<nsIDOMNode> inputField;
nsCOMPtr<nsIDOMXULTextBoxElement> textbox = do_QueryInterface(aContent);
if (textbox) {
textbox->GetInputField(getter_AddRefs(inputField));
}
else {
nsCOMPtr<nsIDOMXULMenuListElement> menulist = do_QueryInterface(aContent);
if (menulist) {
menulist->GetInputField(getter_AddRefs(inputField));
}
else if (aContent->Tag() == nsGkAtoms::scale) {
nsCOMPtr<nsIDocument> doc = aContent->GetCurrentDoc();
if (!doc)
return nullptr;
nsINodeList* children = doc->BindingManager()->GetAnonymousNodesFor(aContent);
if (children) {
nsIContent* child = children->Item(0);
if (child && child->Tag() == nsGkAtoms::slider)
return child;
}
}
}
if (inputField) {
nsCOMPtr<nsIContent> retval = do_QueryInterface(inputField);
return retval;
}
}
#endif
return nullptr;
}
// static
InputContextAction::Cause
nsFocusManager::GetFocusMoveActionCause(uint32_t aFlags)
{
if (aFlags & nsIFocusManager::FLAG_BYMOUSE) {
return InputContextAction::CAUSE_MOUSE;
} else if (aFlags & nsIFocusManager::FLAG_BYKEY) {
return InputContextAction::CAUSE_KEY;
}
return InputContextAction::CAUSE_UNKNOWN;
}
NS_IMETHODIMP
nsFocusManager::GetActiveWindow(nsIDOMWindow** aWindow)
{
NS_IF_ADDREF(*aWindow = mActiveWindow);
return NS_OK;
}
NS_IMETHODIMP
nsFocusManager::SetActiveWindow(nsIDOMWindow* aWindow)
{
// only top-level windows can be made active
nsCOMPtr<nsPIDOMWindow> piWindow = do_QueryInterface(aWindow);
if (piWindow)
piWindow = piWindow->GetOuterWindow();
NS_ENSURE_TRUE(piWindow && (piWindow == piWindow->GetPrivateRoot()),
NS_ERROR_INVALID_ARG);
RaiseWindow(piWindow);
return NS_OK;
}
NS_IMETHODIMP
nsFocusManager::GetFocusedWindow(nsIDOMWindow** aFocusedWindow)
{
NS_IF_ADDREF(*aFocusedWindow = mFocusedWindow);
return NS_OK;
}
NS_IMETHODIMP nsFocusManager::SetFocusedWindow(nsIDOMWindow* aWindowToFocus)
{
LOGFOCUS(("<<SetFocusedWindow begin>>"));
nsCOMPtr<nsPIDOMWindow> windowToFocus(do_QueryInterface(aWindowToFocus));
NS_ENSURE_TRUE(windowToFocus, NS_ERROR_FAILURE);
windowToFocus = windowToFocus->GetOuterWindow();
nsCOMPtr<nsIContent> frameContent =
do_QueryInterface(windowToFocus->GetFrameElementInternal());
if (frameContent) {
// pass false for aFocusChanged so that the caret does not get updated
// and scrolling does not occur.
SetFocusInner(frameContent, 0, false, true);
}
else {
// this is a top-level window. If the window has a child frame focused,
// clear the focus. Otherwise, focus should already be in this frame, or
// already cleared. This ensures that focus will be in this frame and not
// in a child.
nsIContent* content = windowToFocus->GetFocusedNode();
if (content) {
nsCOMPtr<nsIDOMWindow> childWindow = GetContentWindow(content);
if (childWindow)
ClearFocus(windowToFocus);
}
}
nsCOMPtr<nsPIDOMWindow> rootWindow = windowToFocus->GetPrivateRoot();
if (rootWindow)
RaiseWindow(rootWindow);
LOGFOCUS(("<<SetFocusedWindow end>>"));
return NS_OK;
}
NS_IMETHODIMP
nsFocusManager::GetFocusedElement(nsIDOMElement** aFocusedElement)
{
if (mFocusedContent)
CallQueryInterface(mFocusedContent, aFocusedElement);
else
*aFocusedElement = nullptr;
return NS_OK;
}
NS_IMETHODIMP
nsFocusManager::GetLastFocusMethod(nsIDOMWindow* aWindow, uint32_t* aLastFocusMethod)
{
// the focus method is stored on the inner window
nsCOMPtr<nsPIDOMWindow> window(do_QueryInterface(aWindow));
if (window)
window = window->GetCurrentInnerWindow();
if (!window)
window = mFocusedWindow;
*aLastFocusMethod = window ? window->GetFocusMethod() : 0;
NS_ASSERTION((*aLastFocusMethod & FOCUSMETHOD_MASK) == *aLastFocusMethod,
"invalid focus method");
return NS_OK;
}
NS_IMETHODIMP
nsFocusManager::SetFocus(nsIDOMElement* aElement, uint32_t aFlags)
{
LOGFOCUS(("<<SetFocus begin>>"));
nsCOMPtr<nsIContent> newFocus = do_QueryInterface(aElement);
NS_ENSURE_ARG(newFocus);
SetFocusInner(newFocus, aFlags, true, true);
LOGFOCUS(("<<SetFocus end>>"));
return NS_OK;
}
NS_IMETHODIMP
nsFocusManager::ElementIsFocusable(nsIDOMElement* aElement, uint32_t aFlags,
bool* aIsFocusable)
{
NS_ENSURE_TRUE(aElement, NS_ERROR_INVALID_ARG);
nsCOMPtr<nsIContent> aContent = do_QueryInterface(aElement);
*aIsFocusable = CheckIfFocusable(aContent, aFlags) != nullptr;
return NS_OK;
}
NS_IMETHODIMP
nsFocusManager::MoveFocus(nsIDOMWindow* aWindow, nsIDOMElement* aStartElement,
uint32_t aType, uint32_t aFlags, nsIDOMElement** aElement)
{
*aElement = nullptr;
#ifdef PR_LOGGING
LOGFOCUS(("<<MoveFocus begin Type: %d Flags: %x>>", aType, aFlags));
if (PR_LOG_TEST(gFocusLog, PR_LOG_DEBUG) && mFocusedWindow) {
nsIDocument* doc = mFocusedWindow->GetExtantDoc();
if (doc && doc->GetDocumentURI()) {
nsAutoCString spec;
doc->GetDocumentURI()->GetSpec(spec);
LOGFOCUS((" Focused Window: %p %s", mFocusedWindow.get(), spec.get()));
}
}
LOGCONTENT(" Current Focus: %s", mFocusedContent.get());
#endif
// use FLAG_BYMOVEFOCUS when switching focus with MoveFocus unless one of
// the other focus methods is already set, or we're just moving to the root
// or caret position.
if (aType != MOVEFOCUS_ROOT && aType != MOVEFOCUS_CARET &&
(aFlags & FOCUSMETHOD_MASK) == 0) {
aFlags |= FLAG_BYMOVEFOCUS;
}
nsCOMPtr<nsPIDOMWindow> window;
nsCOMPtr<nsIContent> startContent;
if (aStartElement) {
startContent = do_QueryInterface(aStartElement);
NS_ENSURE_TRUE(startContent, NS_ERROR_INVALID_ARG);
window = GetCurrentWindow(startContent);
}
else {
window = aWindow ? do_QueryInterface(aWindow) : mFocusedWindow;
NS_ENSURE_TRUE(window, NS_ERROR_FAILURE);
window = window->GetOuterWindow();
}
NS_ENSURE_TRUE(window, NS_ERROR_FAILURE);
bool noParentTraversal = aFlags & FLAG_NOPARENTFRAME;
nsCOMPtr<nsIContent> newFocus;
nsresult rv = DetermineElementToMoveFocus(window, startContent, aType, noParentTraversal,
getter_AddRefs(newFocus));
NS_ENSURE_SUCCESS(rv, rv);
LOGCONTENTNAVIGATION("Element to be focused: %s", newFocus.get());
if (newFocus) {
// for caret movement, pass false for the aFocusChanged argument,
// otherwise the caret will end up moving to the focus position. This
// would be a problem because the caret would move to the beginning of the
// focused link making it impossible to navigate the caret over a link.
SetFocusInner(newFocus, aFlags, aType != MOVEFOCUS_CARET, true);
CallQueryInterface(newFocus, aElement);
}
else if (aType == MOVEFOCUS_ROOT || aType == MOVEFOCUS_CARET) {
// no content was found, so clear the focus for these two types.
ClearFocus(window);
}
LOGFOCUS(("<<MoveFocus end>>"));
return NS_OK;
}
NS_IMETHODIMP
nsFocusManager::ClearFocus(nsIDOMWindow* aWindow)
{
LOGFOCUS(("<<ClearFocus begin>>"));
// if the window to clear is the focused window or an ancestor of the
// focused window, then blur the existing focused content. Otherwise, the
// focus is somewhere else so just update the current node.
nsCOMPtr<nsPIDOMWindow> window(do_QueryInterface(aWindow));
NS_ENSURE_TRUE(window, NS_ERROR_INVALID_ARG);
window = window->GetOuterWindow();
NS_ENSURE_TRUE(window, NS_ERROR_INVALID_ARG);
if (IsSameOrAncestor(window, mFocusedWindow)) {
bool isAncestor = (window != mFocusedWindow);
if (Blur(window, nullptr, isAncestor, true)) {
// if we are clearing the focus on an ancestor of the focused window,
// the ancestor will become the new focused window, so focus it
if (isAncestor)
Focus(window, nullptr, 0, true, false, false, true);
}
}
else {
window->SetFocusedNode(nullptr);
}
LOGFOCUS(("<<ClearFocus end>>"));
return NS_OK;
}
NS_IMETHODIMP
nsFocusManager::GetFocusedElementForWindow(nsIDOMWindow* aWindow,
bool aDeep,
nsIDOMWindow** aFocusedWindow,
nsIDOMElement** aElement)
{
*aElement = nullptr;
if (aFocusedWindow)
*aFocusedWindow = nullptr;
nsCOMPtr<nsPIDOMWindow> window(do_QueryInterface(aWindow));
NS_ENSURE_TRUE(window, NS_ERROR_INVALID_ARG);
window = window->GetOuterWindow();
NS_ENSURE_TRUE(window, NS_ERROR_INVALID_ARG);
nsCOMPtr<nsPIDOMWindow> focusedWindow;
nsCOMPtr<nsIContent> focusedContent =
GetFocusedDescendant(window, aDeep, getter_AddRefs(focusedWindow));
if (focusedContent)
CallQueryInterface(focusedContent, aElement);
if (aFocusedWindow)
NS_IF_ADDREF(*aFocusedWindow = focusedWindow);
return NS_OK;
}
NS_IMETHODIMP
nsFocusManager::MoveCaretToFocus(nsIDOMWindow* aWindow)
{
int32_t itemType = nsIDocShellTreeItem::typeChrome;
nsCOMPtr<nsIWebNavigation> webnav = do_GetInterface(aWindow);
nsCOMPtr<nsIDocShellTreeItem> dsti = do_QueryInterface(webnav);
if (dsti) {
dsti->GetItemType(&itemType);
if (itemType != nsIDocShellTreeItem::typeChrome) {
nsCOMPtr<nsIDocShell> docShell = do_QueryInterface(dsti);
NS_ENSURE_TRUE(docShell, NS_ERROR_FAILURE);
// don't move the caret for editable documents
bool isEditable;
docShell->GetEditable(&isEditable);
if (isEditable)
return NS_OK;
nsCOMPtr<nsIPresShell> presShell = docShell->GetPresShell();
NS_ENSURE_TRUE(presShell, NS_ERROR_FAILURE);
nsCOMPtr<nsPIDOMWindow> window(do_QueryInterface(aWindow));
nsCOMPtr<nsIContent> content = window->GetFocusedNode();
if (content)
MoveCaretToFocus(presShell, content);
}
}
return NS_OK;
}
NS_IMETHODIMP
nsFocusManager::WindowRaised(nsIDOMWindow* aWindow)
{
nsCOMPtr<nsPIDOMWindow> window = do_QueryInterface(aWindow);
NS_ENSURE_TRUE(window && window->IsOuterWindow(), NS_ERROR_INVALID_ARG);
#ifdef PR_LOGGING
if (PR_LOG_TEST(gFocusLog, PR_LOG_DEBUG)) {
LOGFOCUS(("Window %p Raised [Currently: %p %p]", aWindow, mActiveWindow.get(), mFocusedWindow.get()));
nsAutoCString spec;
nsIDocument* doc = window->GetExtantDoc();
if (doc && doc->GetDocumentURI()) {
doc->GetDocumentURI()->GetSpec(spec);
LOGFOCUS((" Raised Window: %p %s", aWindow, spec.get()));
}
if (mActiveWindow) {
doc = mActiveWindow->GetExtantDoc();
if (doc && doc->GetDocumentURI()) {
doc->GetDocumentURI()->GetSpec(spec);
LOGFOCUS((" Active Window: %p %s", mActiveWindow.get(), spec.get()));
}
}
}
#endif
if (mActiveWindow == window) {
// The window is already active, so there is no need to focus anything,
// but make sure that the right widget is focused. This is a special case
// for Windows because when restoring a minimized window, a second
// activation will occur and the top-level widget could be focused instead
// of the child we want. We solve this by calling SetFocus to ensure that
// what the focus manager thinks should be the current widget is actually
// focused.
EnsureCurrentWidgetFocused();
return NS_OK;
}
// lower the existing window, if any. This shouldn't happen usually.
if (mActiveWindow)
WindowLowered(mActiveWindow);
nsCOMPtr<nsIWebNavigation> webnav(do_GetInterface(aWindow));
nsCOMPtr<nsIDocShellTreeItem> docShellAsItem(do_QueryInterface(webnav));
// If there's no docShellAsItem, this window must have been closed,
// in that case there is no tree owner.
NS_ENSURE_TRUE(docShellAsItem, NS_OK);
// set this as the active window
mActiveWindow = window;
// ensure that the window is enabled and visible
nsCOMPtr<nsIDocShellTreeOwner> treeOwner;
docShellAsItem->GetTreeOwner(getter_AddRefs(treeOwner));
nsCOMPtr<nsIBaseWindow> baseWindow = do_QueryInterface(treeOwner);
if (baseWindow) {
bool isEnabled = true;
if (NS_SUCCEEDED(baseWindow->GetEnabled(&isEnabled)) && !isEnabled) {
return NS_ERROR_FAILURE;
}
if (!sTestMode) {
baseWindow->SetVisibility(true);
}
}
// inform the DOM window that it has activated, so that the active attribute
// is updated on the window
window->ActivateOrDeactivate(true);
// send activate event
nsContentUtils::DispatchTrustedEvent(window->GetExtantDoc(),
window,
NS_LITERAL_STRING("activate"),
true, true, nullptr);
// retrieve the last focused element within the window that was raised
nsCOMPtr<nsPIDOMWindow> currentWindow;
nsCOMPtr<nsIContent> currentFocus =
GetFocusedDescendant(window, true, getter_AddRefs(currentWindow));
NS_ASSERTION(currentWindow, "window raised with no window current");
if (!currentWindow)
return NS_OK;
nsCOMPtr<nsIDocShell> currentDocShell = currentWindow->GetDocShell();
nsCOMPtr<nsIPresShell> presShell = currentDocShell->GetPresShell();
if (presShell) {
// disable selection mousedown state on activation
// XXXndeakin P3 not sure if this is necessary, but it doesn't hurt
nsRefPtr<nsFrameSelection> frameSelection = presShell->FrameSelection();
frameSelection->SetMouseDownState(false);
}
Focus(currentWindow, currentFocus, 0, true, false, true, true);
return NS_OK;
}
NS_IMETHODIMP
nsFocusManager::WindowLowered(nsIDOMWindow* aWindow)
{
nsCOMPtr<nsPIDOMWindow> window = do_QueryInterface(aWindow);
NS_ENSURE_TRUE(window && window->IsOuterWindow(), NS_ERROR_INVALID_ARG);
#ifdef PR_LOGGING
if (PR_LOG_TEST(gFocusLog, PR_LOG_DEBUG)) {
LOGFOCUS(("Window %p Lowered [Currently: %p %p]", aWindow, mActiveWindow.get(), mFocusedWindow.get()));
nsAutoCString spec;
nsIDocument* doc = window->GetExtantDoc();
if (doc && doc->GetDocumentURI()) {
doc->GetDocumentURI()->GetSpec(spec);
LOGFOCUS((" Lowered Window: %s", spec.get()));
}
if (mActiveWindow) {
doc = mActiveWindow->GetExtantDoc();
if (doc && doc->GetDocumentURI()) {
doc->GetDocumentURI()->GetSpec(spec);
LOGFOCUS((" Active Window: %s", spec.get()));
}
}
}
#endif
if (mActiveWindow != window)
return NS_OK;
// clear the mouse capture as the active window has changed
nsIPresShell::SetCapturingContent(nullptr, 0);
// inform the DOM window that it has deactivated, so that the active
// attribute is updated on the window
window->ActivateOrDeactivate(false);
// send deactivate event
nsContentUtils::DispatchTrustedEvent(window->GetExtantDoc(),
window,
NS_LITERAL_STRING("deactivate"),
true, true, nullptr);
// keep track of the window being lowered, so that attempts to raise the
// window can be prevented until we return. Otherwise, focus can get into
// an unusual state.
mWindowBeingLowered = mActiveWindow;
mActiveWindow = nullptr;
if (mFocusedWindow)
Blur(nullptr, nullptr, true, true);
mWindowBeingLowered = nullptr;
return NS_OK;
}
nsresult
nsFocusManager::ContentRemoved(nsIDocument* aDocument, nsIContent* aContent)
{
NS_ENSURE_ARG(aDocument);
NS_ENSURE_ARG(aContent);
nsPIDOMWindow *window = aDocument->GetWindow();
if (!window)
return NS_OK;
// if the content is currently focused in the window, or is an ancestor
// of the currently focused element, reset the focus within that window.
nsIContent* content = window->GetFocusedNode();
if (content && nsContentUtils::ContentIsDescendantOf(content, aContent)) {
bool shouldShowFocusRing = window->ShouldShowFocusRing();
window->SetFocusedNode(nullptr);
// if this window is currently focused, clear the global focused
// element as well, but don't fire any events.
if (window == mFocusedWindow) {
mFocusedContent = nullptr;
}
else {
// Check if the node that was focused is an iframe or similar by looking
// if it has a subdocument. This would indicate that this focused iframe
// and its descendants will be going away. We will need to move the
// focus somewhere else, so just clear the focus in the toplevel window
// so that no element is focused.
nsIDocument* subdoc = aDocument->GetSubDocumentFor(content);
if (subdoc) {
nsCOMPtr<nsISupports> container = subdoc->GetContainer();
nsCOMPtr<nsPIDOMWindow> childWindow = do_GetInterface(container);
if (childWindow && IsSameOrAncestor(childWindow, mFocusedWindow)) {
ClearFocus(mActiveWindow);
}
}
}
NotifyFocusStateChange(content, shouldShowFocusRing, false);
}
return NS_OK;
}
NS_IMETHODIMP
nsFocusManager::WindowShown(nsIDOMWindow* aWindow, bool aNeedsFocus)
{
nsCOMPtr<nsPIDOMWindow> window = do_QueryInterface(aWindow);
NS_ENSURE_TRUE(window, NS_ERROR_INVALID_ARG);
window = window->GetOuterWindow();
#ifdef PR_LOGGING
if (PR_LOG_TEST(gFocusLog, PR_LOG_DEBUG)) {
LOGFOCUS(("Window %p Shown [Currently: %p %p]", window.get(), mActiveWindow.get(), mFocusedWindow.get()));
nsAutoCString spec;
nsIDocument* doc = window->GetExtantDoc();
if (doc && doc->GetDocumentURI()) {
doc->GetDocumentURI()->GetSpec(spec);
LOGFOCUS(("Shown Window: %s", spec.get()));
}
if (mFocusedWindow) {
doc = mFocusedWindow->GetExtantDoc();
if (doc && doc->GetDocumentURI()) {
doc->GetDocumentURI()->GetSpec(spec);
LOGFOCUS((" Focused Window: %s", spec.get()));
}
}
}
#endif
if (mFocusedWindow != window)
return NS_OK;
if (aNeedsFocus) {
nsCOMPtr<nsPIDOMWindow> currentWindow;
nsCOMPtr<nsIContent> currentFocus =
GetFocusedDescendant(window, true, getter_AddRefs(currentWindow));
if (currentWindow)
Focus(currentWindow, currentFocus, 0, true, false, false, true);
}
else {
// Sometimes, an element in a window can be focused before the window is
// visible, which would mean that the widget may not be properly focused.
// When the window becomes visible, make sure the right widget is focused.
EnsureCurrentWidgetFocused();
}
return NS_OK;
}
NS_IMETHODIMP
nsFocusManager::WindowHidden(nsIDOMWindow* aWindow)
{
// if there is no window or it is not the same or an ancestor of the
// currently focused window, just return, as the current focus will not
// be affected.
nsCOMPtr<nsPIDOMWindow> window = do_QueryInterface(aWindow);
NS_ENSURE_TRUE(window, NS_ERROR_INVALID_ARG);
window = window->GetOuterWindow();
#ifdef PR_LOGGING
if (PR_LOG_TEST(gFocusLog, PR_LOG_DEBUG)) {
LOGFOCUS(("Window %p Hidden [Currently: %p %p]", window.get(), mActiveWindow.get(), mFocusedWindow.get()));
nsAutoCString spec;
nsIDocument* doc = window->GetExtantDoc();
if (doc && doc->GetDocumentURI()) {
doc->GetDocumentURI()->GetSpec(spec);
LOGFOCUS((" Hide Window: %s", spec.get()));
}
if (mFocusedWindow) {
doc = mFocusedWindow->GetExtantDoc();
if (doc && doc->GetDocumentURI()) {
doc->GetDocumentURI()->GetSpec(spec);
LOGFOCUS((" Focused Window: %s", spec.get()));
}
}
if (mActiveWindow) {
doc = mActiveWindow->GetExtantDoc();
if (doc && doc->GetDocumentURI()) {
doc->GetDocumentURI()->GetSpec(spec);
LOGFOCUS((" Active Window: %s", spec.get()));
}
}
}
#endif
if (!IsSameOrAncestor(window, mFocusedWindow))
return NS_OK;
// at this point, we know that the window being hidden is either the focused
// window, or an ancestor of the focused window. Either way, the focus is no
// longer valid, so it needs to be updated.
nsCOMPtr<nsIContent> oldFocusedContent = mFocusedContent.forget();
nsCOMPtr<nsIDocShell> focusedDocShell = mFocusedWindow->GetDocShell();
nsCOMPtr<nsIPresShell> presShell = focusedDocShell->GetPresShell();
if (oldFocusedContent && oldFocusedContent->IsInDoc()) {
NotifyFocusStateChange(oldFocusedContent,
mFocusedWindow->ShouldShowFocusRing(),
false);
window->UpdateCommands(NS_LITERAL_STRING("focus"));
if (presShell) {
SendFocusOrBlurEvent(NS_BLUR_CONTENT, presShell,
oldFocusedContent->GetCurrentDoc(),
oldFocusedContent, 1, false);
}
}
nsPresContext* focusedPresContext =
presShell ? presShell->GetPresContext() : nullptr;
nsIMEStateManager::OnChangeFocus(focusedPresContext, nullptr,
GetFocusMoveActionCause(0));
if (presShell) {
SetCaretVisible(presShell, false, nullptr);
}
// if the docshell being hidden is being destroyed, then we want to move
// focus somewhere else. Call ClearFocus on the toplevel window, which
// will have the effect of clearing the focus and moving the focused window
// to the toplevel window. But if the window isn't being destroyed, we are
// likely just loading a new document in it, so we want to maintain the
// focused window so that the new document gets properly focused.
bool beingDestroyed;
nsCOMPtr<nsIDocShell> docShellBeingHidden = window->GetDocShell();
docShellBeingHidden->IsBeingDestroyed(&beingDestroyed);
if (beingDestroyed) {
// There is usually no need to do anything if a toplevel window is going
// away, as we assume that WindowLowered will be called. However, this may
// not happen if nsIAppStartup::eForceQuit is used to quit, and can cause
// a leak. So if the active window is being destroyed, call WindowLowered
// directly.
NS_ASSERTION(mFocusedWindow->IsOuterWindow(), "outer window expected");
if (mActiveWindow == mFocusedWindow || mActiveWindow == window)
WindowLowered(mActiveWindow);
else
ClearFocus(mActiveWindow);
return NS_OK;
}
// if the window being hidden is an ancestor of the focused window, adjust
// the focused window so that it points to the one being hidden. This
// ensures that the focused window isn't in a chain of frames that doesn't
// exist any more.
if (window != mFocusedWindow) {
nsCOMPtr<nsIWebNavigation> webnav(do_GetInterface(mFocusedWindow));
nsCOMPtr<nsIDocShellTreeItem> dsti = do_QueryInterface(webnav);
if (dsti) {
nsCOMPtr<nsIDocShellTreeItem> parentDsti;
dsti->GetParent(getter_AddRefs(parentDsti));
nsCOMPtr<nsPIDOMWindow> parentWindow = do_GetInterface(parentDsti);
if (parentWindow)
parentWindow->SetFocusedNode(nullptr);
}
SetFocusedWindowInternal(window);
}
return NS_OK;
}
NS_IMETHODIMP
nsFocusManager::FireDelayedEvents(nsIDocument* aDocument)
{
NS_ENSURE_ARG(aDocument);
// fire any delayed focus and blur events in the same order that they were added
for (uint32_t i = 0; i < mDelayedBlurFocusEvents.Length(); i++)
{
if (mDelayedBlurFocusEvents[i].mDocument == aDocument &&