1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #include "mozilla/dom/UIDirectionManager.h"
8 #include "mozilla/Preferences.h"
9 #include "nsIWindowMediator.h"
10 #include "nsDocShell.h"
11 #include "mozilla/dom/Document.h"
12 #include "mozilla/SimpleEnumerator.h"
13 
14 namespace mozilla {
15 namespace dom {
16 
17 /* static */
OnPrefChange(const char * aPrefName,void *)18 void OnPrefChange(const char* aPrefName, void*) {
19   // Iterate over all of the windows and notify them of the direction change.
20   nsCOMPtr<nsIWindowMediator> windowMediator =
21       do_GetService(NS_WINDOWMEDIATOR_CONTRACTID);
22   NS_ENSURE_TRUE_VOID(windowMediator);
23 
24   nsCOMPtr<nsISimpleEnumerator> windowEnumerator;
25   windowMediator->GetEnumerator(nullptr, getter_AddRefs(windowEnumerator));
26   NS_ENSURE_TRUE_VOID(windowEnumerator);
27 
28   for (auto& elements : SimpleEnumerator<nsISupports>(windowEnumerator)) {
29     nsCOMPtr<nsPIDOMWindowOuter> window = do_QueryInterface(elements);
30     if (window->Closed()) {
31       continue;
32     }
33 
34     nsCOMPtr<nsIDocShell> rootDocShell = window->GetDocShell();
35     nsTArray<RefPtr<nsIDocShell>> docShells;
36     rootDocShell->GetAllDocShellsInSubtree(
37         nsIDocShell::typeAll, nsIDocShell::ENUMERATE_FORWARDS, docShells);
38     for (auto& docShell : docShells) {
39       if (nsCOMPtr<nsPIDOMWindowOuter> win = do_GetInterface(docShell)) {
40         if (dom::Document* doc = win->GetExtantDoc()) {
41           doc->ResetDocumentDirection();
42         }
43       }
44     }
45   }
46 }
47 
48 /* static */
Initialize()49 void UIDirectionManager::Initialize() {
50   DebugOnly<nsresult> rv =
51       Preferences::RegisterCallback(OnPrefChange, "intl.uidirection");
52   MOZ_ASSERT(NS_SUCCEEDED(rv), "Failed to observe \"intl.uidirection\"");
53   rv = Preferences::RegisterCallback(OnPrefChange, "intl.l10n.pseudo");
54   MOZ_ASSERT(NS_SUCCEEDED(rv), "Failed to observe \"intl.l10n.pseudo\"");
55 }
56 
57 /* static */
Shutdown()58 void UIDirectionManager::Shutdown() {
59   Preferences::UnregisterCallback(OnPrefChange, "intl.uidirection");
60   Preferences::UnregisterCallback(OnPrefChange, "intl.l10n.pseudo");
61 }
62 
63 }  // namespace dom
64 }  // namespace mozilla
65