Bug 1635702 [wpt PR 23413] - Move some internal scroll anchoring tests to wpt, a...
[gecko.git] / layout / style / PreloadedStyleSheet.cpp
blob6f5896933e8806260b5056b12bdf65b7efb217c0
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/. */
7 /* a CSS style sheet returned from nsIStyleSheetService.preloadSheet */
9 #include "PreloadedStyleSheet.h"
11 #include "mozilla/css/Loader.h"
12 #include "mozilla/dom/Promise.h"
13 #include "nsICSSLoaderObserver.h"
14 #include "nsLayoutUtils.h"
16 namespace mozilla {
18 PreloadedStyleSheet::PreloadedStyleSheet(nsIURI* aURI,
19 css::SheetParsingMode aParsingMode)
20 : mLoaded(false), mURI(aURI), mParsingMode(aParsingMode) {}
22 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(PreloadedStyleSheet)
23 NS_INTERFACE_MAP_ENTRY(nsIPreloadedStyleSheet)
24 NS_INTERFACE_MAP_ENTRY(nsISupports)
25 NS_INTERFACE_MAP_END
27 NS_IMPL_CYCLE_COLLECTING_ADDREF(PreloadedStyleSheet)
28 NS_IMPL_CYCLE_COLLECTING_RELEASE(PreloadedStyleSheet)
30 NS_IMPL_CYCLE_COLLECTION(PreloadedStyleSheet, mSheet)
32 nsresult PreloadedStyleSheet::GetSheet(StyleSheet** aResult) {
33 *aResult = nullptr;
35 MOZ_DIAGNOSTIC_ASSERT(mLoaded);
37 if (!mSheet) {
38 RefPtr<css::Loader> loader = new css::Loader;
39 auto result = loader->LoadSheetSync(mURI, mParsingMode,
40 css::Loader::UseSystemPrincipal::Yes);
41 if (result.isErr()) {
42 return result.unwrapErr();
44 mSheet = result.unwrap();
47 *aResult = mSheet;
48 return NS_OK;
51 nsresult PreloadedStyleSheet::Preload() {
52 MOZ_DIAGNOSTIC_ASSERT(!mLoaded);
53 mLoaded = true;
54 StyleSheet* sheet;
55 return GetSheet(&sheet);
58 NS_IMPL_ISUPPORTS(PreloadedStyleSheet::StylesheetPreloadObserver,
59 nsICSSLoaderObserver)
61 NS_IMETHODIMP
62 PreloadedStyleSheet::StylesheetPreloadObserver::StyleSheetLoaded(
63 StyleSheet* aSheet, bool aWasDeferred, nsresult aStatus) {
64 MOZ_DIAGNOSTIC_ASSERT(!mPreloadedSheet->mLoaded);
65 mPreloadedSheet->mLoaded = true;
67 if (NS_FAILED(aStatus)) {
68 mPromise->MaybeReject(aStatus);
69 } else {
70 mPromise->MaybeResolve(mPreloadedSheet);
73 return NS_OK;
76 // Note: After calling this method, the preloaded sheet *must not* be used
77 // until the observer is notified that the sheet has finished loading.
78 nsresult PreloadedStyleSheet::PreloadAsync(NotNull<dom::Promise*> aPromise) {
79 MOZ_DIAGNOSTIC_ASSERT(!mLoaded);
81 RefPtr<css::Loader> loader = new css::Loader;
82 RefPtr<StylesheetPreloadObserver> obs =
83 new StylesheetPreloadObserver(aPromise, this);
84 auto result = loader->LoadSheet(mURI, mParsingMode,
85 css::Loader::UseSystemPrincipal::No, obs);
86 if (result.isErr()) {
87 return result.unwrapErr();
89 mSheet = result.unwrap();
90 return NS_OK;
93 } // namespace mozilla