1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim:set ts=2 sw=2 sts=2 et cindent: */
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 "DocumentL10n.h"
8 #include "nsIContentSink.h"
9 #include "nsContentUtils.h"
10 #include "mozilla/dom/AutoEntryScript.h"
11 #include "mozilla/dom/Document.h"
12 #include "mozilla/dom/DocumentL10nBinding.h"
13 #include "mozilla/Telemetry.h"
14 
15 using namespace mozilla::dom;
16 
17 NS_IMPL_CYCLE_COLLECTION_CLASS(DocumentL10n)
18 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(DocumentL10n, DOMLocalization)
19   NS_IMPL_CYCLE_COLLECTION_UNLINK(mDocument)
20   NS_IMPL_CYCLE_COLLECTION_UNLINK(mReady)
21   NS_IMPL_CYCLE_COLLECTION_UNLINK(mContentSink)
22   NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
23 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
24 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(DocumentL10n, DOMLocalization)
25   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDocument)
26   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mReady)
27   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mContentSink)
28 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
29 
30 NS_IMPL_ADDREF_INHERITED(DocumentL10n, DOMLocalization)
31 NS_IMPL_RELEASE_INHERITED(DocumentL10n, DOMLocalization)
32 
33 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(DocumentL10n)
34 NS_INTERFACE_MAP_END_INHERITING(DOMLocalization)
35 
36 bool DocumentL10n::mIsFirstBrowserWindow = true;
37 
38 /* static */
Create(Document * aDocument,const bool aSync)39 RefPtr<DocumentL10n> DocumentL10n::Create(Document* aDocument,
40                                           const bool aSync) {
41   RefPtr<DocumentL10n> l10n = new DocumentL10n(aDocument, aSync);
42 
43   if (!l10n->Init()) {
44     return nullptr;
45   }
46   return l10n.forget();
47 }
48 
DocumentL10n(Document * aDocument,const bool aSync)49 DocumentL10n::DocumentL10n(Document* aDocument, const bool aSync)
50     : DOMLocalization(aDocument->GetScopeObject(), aSync, {}),
51       mDocument(aDocument),
52       mState(DocumentL10nState::Constructed) {
53   mContentSink = do_QueryInterface(aDocument->GetCurrentContentSink());
54 }
55 
Init()56 bool DocumentL10n::Init() {
57   DOMLocalization::Init();
58   ErrorResult rv;
59   mReady = Promise::Create(mGlobal, rv);
60   if (NS_WARN_IF(rv.Failed())) {
61     return false;
62   }
63   return true;
64 }
65 
WrapObject(JSContext * aCx,JS::Handle<JSObject * > aGivenProto)66 JSObject* DocumentL10n::WrapObject(JSContext* aCx,
67                                    JS::Handle<JSObject*> aGivenProto) {
68   return DocumentL10n_Binding::Wrap(aCx, this, aGivenProto);
69 }
70 
71 class L10nReadyHandler final : public PromiseNativeHandler {
72  public:
73   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
NS_DECL_CYCLE_COLLECTION_CLASS(L10nReadyHandler)74   NS_DECL_CYCLE_COLLECTION_CLASS(L10nReadyHandler)
75 
76   explicit L10nReadyHandler(Promise* aPromise, DocumentL10n* aDocumentL10n)
77       : mPromise(aPromise), mDocumentL10n(aDocumentL10n) {}
78 
ResolvedCallback(JSContext * aCx,JS::Handle<JS::Value> aValue)79   void ResolvedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override {
80     mDocumentL10n->InitialTranslationCompleted(true);
81     mPromise->MaybeResolveWithUndefined();
82   }
83 
RejectedCallback(JSContext * aCx,JS::Handle<JS::Value> aValue)84   void RejectedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override {
85     mDocumentL10n->InitialTranslationCompleted(false);
86     mPromise->MaybeRejectWithUndefined();
87   }
88 
89  private:
90   ~L10nReadyHandler() = default;
91 
92   RefPtr<Promise> mPromise;
93   RefPtr<DocumentL10n> mDocumentL10n;
94 };
95 
NS_IMPL_CYCLE_COLLECTION(L10nReadyHandler,mPromise,mDocumentL10n)96 NS_IMPL_CYCLE_COLLECTION(L10nReadyHandler, mPromise, mDocumentL10n)
97 
98 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(L10nReadyHandler)
99   NS_INTERFACE_MAP_ENTRY(nsISupports)
100 NS_INTERFACE_MAP_END
101 
102 NS_IMPL_CYCLE_COLLECTING_ADDREF(L10nReadyHandler)
103 NS_IMPL_CYCLE_COLLECTING_RELEASE(L10nReadyHandler)
104 
105 void DocumentL10n::TriggerInitialTranslation() {
106   MOZ_ASSERT(nsContentUtils::IsSafeToRunScript());
107   if (mState >= DocumentL10nState::InitialTranslationTriggered) {
108     return;
109   }
110   if (!mReady) {
111     // If we don't have `mReady` it means that we are in shutdown mode.
112     // See bug 1687118 for details.
113     InitialTranslationCompleted(false);
114     return;
115   }
116 
117   mInitialTranslationStart = mozilla::TimeStamp::NowUnfuzzed();
118 
119   AutoAllowLegacyScriptExecution exemption;
120 
121   nsTArray<RefPtr<Promise>> promises;
122 
123   ErrorResult rv;
124   promises.AppendElement(TranslateDocument(rv));
125   if (NS_WARN_IF(rv.Failed())) {
126     InitialTranslationCompleted(false);
127     mReady->MaybeRejectWithUndefined();
128     return;
129   }
130   promises.AppendElement(TranslateRoots(rv));
131   Element* documentElement = mDocument->GetDocumentElement();
132   if (!documentElement) {
133     InitialTranslationCompleted(false);
134     mReady->MaybeRejectWithUndefined();
135     return;
136   }
137 
138   DOMLocalization::ConnectRoot(*documentElement, rv);
139   if (NS_WARN_IF(rv.Failed())) {
140     InitialTranslationCompleted(false);
141     mReady->MaybeRejectWithUndefined();
142     return;
143   }
144 
145   AutoEntryScript aes(mGlobal, "DocumentL10n InitialTranslation");
146   RefPtr<Promise> promise = Promise::All(aes.cx(), promises, rv);
147 
148   if (promise->State() == Promise::PromiseState::Resolved) {
149     // If the promise is already resolved, we can fast-track
150     // to initial translation completed.
151     InitialTranslationCompleted(true);
152     mReady->MaybeResolveWithUndefined();
153   } else {
154     RefPtr<PromiseNativeHandler> l10nReadyHandler =
155         new L10nReadyHandler(mReady, this);
156     promise->AppendNativeHandler(l10nReadyHandler);
157 
158     mState = DocumentL10nState::InitialTranslationTriggered;
159   }
160 }
161 
TranslateDocument(ErrorResult & aRv)162 already_AddRefed<Promise> DocumentL10n::TranslateDocument(ErrorResult& aRv) {
163   MOZ_ASSERT(mState == DocumentL10nState::Constructed,
164              "This method should be called only from Constructed state.");
165   RefPtr<Promise> promise = Promise::Create(mGlobal, aRv);
166 
167   Element* elem = mDocument->GetDocumentElement();
168   if (!elem) {
169     promise->MaybeRejectWithUndefined();
170     return promise.forget();
171   }
172 
173   // 1. Collect all localizable elements.
174   Sequence<OwningNonNull<Element>> elements;
175   GetTranslatables(*elem, elements, aRv);
176   if (NS_WARN_IF(aRv.Failed())) {
177     promise->MaybeRejectWithUndefined();
178     return promise.forget();
179   }
180 
181   RefPtr<nsXULPrototypeDocument> proto = mDocument->GetPrototype();
182 
183   // 2. Check if the document has a prototype that may cache
184   //    translated elements.
185   if (proto) {
186     // 2.1. Handle the case when we have proto.
187 
188     // 2.1.1. Move elements that are not in the proto to a separate
189     //        array.
190     Sequence<OwningNonNull<Element>> nonProtoElements;
191 
192     uint32_t i = elements.Length();
193     while (i > 0) {
194       Element* elem = elements.ElementAt(i - 1);
195       MOZ_RELEASE_ASSERT(elem->HasAttr(nsGkAtoms::datal10nid));
196       if (!elem->HasElementCreatedFromPrototypeAndHasUnmodifiedL10n()) {
197         if (NS_WARN_IF(!nonProtoElements.AppendElement(*elem, fallible))) {
198           promise->MaybeRejectWithUndefined();
199           return promise.forget();
200         }
201         elements.RemoveElement(elem);
202       }
203       i--;
204     }
205 
206     // We populate the sequence in reverse order. Let's bring it
207     // back to top->bottom one.
208     nonProtoElements.Reverse();
209 
210     AutoAllowLegacyScriptExecution exemption;
211 
212     nsTArray<RefPtr<Promise>> promises;
213 
214     // 2.1.2. If we're not loading from cache, push the elements that
215     //        are in the prototype to be translated and cached.
216     if (!proto->WasL10nCached() && !elements.IsEmpty()) {
217       RefPtr<Promise> translatePromise =
218           TranslateElements(elements, proto, aRv);
219       if (NS_WARN_IF(!translatePromise || aRv.Failed())) {
220         promise->MaybeRejectWithUndefined();
221         return promise.forget();
222       }
223       promises.AppendElement(translatePromise);
224     }
225 
226     // 2.1.3. If there are elements that are not in the prototype,
227     //        localize them without attempting to cache and
228     //        independently of if we're loading from cache.
229     if (!nonProtoElements.IsEmpty()) {
230       RefPtr<Promise> nonProtoTranslatePromise =
231           TranslateElements(nonProtoElements, nullptr, aRv);
232       if (NS_WARN_IF(!nonProtoTranslatePromise || aRv.Failed())) {
233         promise->MaybeRejectWithUndefined();
234         return promise.forget();
235       }
236       promises.AppendElement(nonProtoTranslatePromise);
237     }
238 
239     // 2.1.4. Collect promises with Promise::All (maybe empty).
240     AutoEntryScript aes(mGlobal, "DocumentL10n InitialTranslationCompleted");
241     promise = Promise::All(aes.cx(), promises, aRv);
242   } else {
243     // 2.2. Handle the case when we don't have proto.
244 
245     // 2.2.1. Otherwise, translate all available elements,
246     //        without attempting to cache them.
247     promise = TranslateElements(elements, nullptr, aRv);
248   }
249 
250   if (NS_WARN_IF(!promise || aRv.Failed())) {
251     promise->MaybeRejectWithUndefined();
252     return promise.forget();
253   }
254 
255   return promise.forget();
256 }
257 
MaybeRecordTelemetry()258 void DocumentL10n::MaybeRecordTelemetry() {
259   mozilla::TimeStamp initialTranslationEnd = mozilla::TimeStamp::NowUnfuzzed();
260 
261   nsAutoString documentURI;
262   ErrorResult rv;
263   rv = mDocument->GetDocumentURI(documentURI);
264   if (rv.Failed()) {
265     return;
266   }
267 
268   nsCString key;
269 
270   if (documentURI.Find("chrome://browser/content/browser.xhtml") == 0) {
271     if (mIsFirstBrowserWindow) {
272       key = "browser_first_window";
273       mIsFirstBrowserWindow = false;
274     } else {
275       key = "browser_new_window";
276     }
277   } else if (documentURI.Find("about:home") == 0) {
278     key = "about:home";
279   } else if (documentURI.Find("about:newtab") == 0) {
280     key = "about:newtab";
281   } else if (documentURI.Find("about:preferences") == 0) {
282     key = "about:preferences";
283   } else {
284     return;
285   }
286 
287   mozilla::TimeDuration totalTime(initialTranslationEnd -
288                                   mInitialTranslationStart);
289   Accumulate(Telemetry::L10N_DOCUMENT_INITIAL_TRANSLATION_TIME_US, key,
290              totalTime.ToMicroseconds());
291 }
292 
InitialTranslationCompleted(bool aL10nCached)293 void DocumentL10n::InitialTranslationCompleted(bool aL10nCached) {
294   if (mState >= DocumentL10nState::Ready) {
295     return;
296   }
297 
298   Element* documentElement = mDocument->GetDocumentElement();
299   if (documentElement) {
300     SetRootInfo(documentElement);
301   }
302 
303   mState = DocumentL10nState::Ready;
304 
305   MaybeRecordTelemetry();
306 
307   mDocument->InitialTranslationCompleted(aL10nCached);
308 
309   // In XUL scenario contentSink is nullptr.
310   if (mContentSink) {
311     mContentSink->InitialTranslationCompleted();
312   }
313 
314   // From now on, the state of Localization is unconditionally
315   // async.
316   SetIsSync(false);
317 }
318 
ConnectRoot(nsINode & aNode,bool aTranslate,ErrorResult & aRv)319 void DocumentL10n::ConnectRoot(nsINode& aNode, bool aTranslate,
320                                ErrorResult& aRv) {
321   if (aTranslate) {
322     if (mState >= DocumentL10nState::InitialTranslationTriggered) {
323       RefPtr<Promise> promise = TranslateFragment(aNode, aRv);
324     }
325   }
326   DOMLocalization::ConnectRoot(aNode, aRv);
327 }
328 
Ready()329 Promise* DocumentL10n::Ready() { return mReady; }
330 
OnCreatePresShell()331 void DocumentL10n::OnCreatePresShell() { mMutations->OnCreatePresShell(); }
332