Files
palemoon27/layout/style/nsLayoutStylesheetCache.cpp
T
roytam1 55e2238bc1 import changes from `dev' branch of rmottola/Arctic-Fox:
- bug 1212906 - don't handle windows messages while waiting for a sync a11y ipc message r=billm (c9297e58f4)
- Bug 1183431 - Tests for hypothetical box computation (to determine static position of abspos element) where orthogonal writing modes are involved. r=dholbert (87b22c5cf5)
- Bug 1221112: When checking for ::before/::after while sorting flex items by DOM order, dig past placeholder to out-of-flow frame. r=mats (b2e252fa86)
- Bug 1169420: add crashtests. (no review) (f7484702a2)
- Bug 1183431 - Ensure hypothetical box has a writing mode with the same block direction as the absolute containing block. r=dholbert (9106e022d1)
- Partial - No bug - Various crashtest manifest cleanups. (f2d0568f2d)
- Bug 1221874 - Crashtest for overzealous writing-mode check (currently asserts). r=smontagu (ef6685f606)
- Bug 1221874 - Ignore the sideways-orientation flag when logical-coordinate classes are checking writing-mode compatibility. r=smontagu (9617a761d6)
- Bug 1193488 - patch 2 - Update the writing-mode representation printed by debugging code such as DumpFrameTree to reflect the new property values. r=dholbert (b6b3fdda58)
- Bug 1208593 - Make the WritingMode::DebugString() method available even in non-DEBUG compilation (needed by --enable-dump-painting builds, for example). r=mchang (d6b46fde86)
- Bug 1122918 - Part 1 - Add parsing for logical inline-start/end keywords to the 'float' and 'clear' properties. r=heycam (20f9dc4d11)
- Bug 1122918 - Part 2 - Provide accessors that return logical 'float' and 'clear' values resolved to their physical equivalents. r=heycam (9380f050d6)
- Bug 1108055 - Part 1: Add ComputedTimingProperties dictionary. r=smaug (ac88430cfe)
- Bug 1108055 - Part 2: Refine ComputedTiming. r=birtles (3c25124b5f)
- Bug 1108055 - Part 3: Implement GetComputedTiming method. r=birtles (d9fe931cc5)
- Bug 1108055 - Part 4: Add ComputedTiming mochitests. r=birtles (1687824926)
- Bug 1195180 part 1 - Add Animation::NeedsTicks; r=heycam (9ac3bbda87)
- Bug 1195180 part 2 - Make DocumentTimeline inherit from nsARefreshObserver; r=heycam (292f9d154d)
- Bug 1195180 part 3 - Add flag to record if DocumentTimeline is observing the refresh driver; r=heycam (3d90d3f149)
- Bug 1195180 part 4 - Unregister from refresh observer when there are no animations needing ticks; r=heycam (ad76c3ddd5)
- Bug 1195180 part 5 - Synchronize refresh driver observing with presshell creation/teardown; r=heycam (94b7d9176f)
- Bug 1195180 part 6 - Lazily remove animations from timelines; r=heycam (bb3beaa264)
- Bug 1195180 part 7 - Store animations in an array; r=heycam (199756e7d6)
- Bug 1195180 part 8 - Tick animations from their timeline; r=heycam (12942bdc45)
- Bug 1195180 part 9 - Add test for seeking finished -> paused; r=heycam (0b42afcd26)
- Bug 1195180 part 10 - Remove refresh driver observing machinery from CommonAnimationManager; r=heycam (bf233d32ac)
- Bug 1208938 part 1 - Rename AnimationCollection::mNeedsRefreshes to mStyleChanging; r=heycam (679bdf0770)
- Bug 1208938 part 2 - Remove Animation::HasEndEventToQueue; r=heycam (c75bdb64b7)
- Bug 1208938 part 3 - Update pending finishing handling; r=heycam (c9f4c1aace)
- Bug 1196379 - Fix incorrect assertion checking for sorted arrays in nsDocumentRuleResultCacheKey::Matches. r=dbaron (a12db544ef)
- Bug 978833 patch 3 - Make css::Declaration implement nsIStyleRule. r=heycam (3b79410f06)
- Bug 978833 patch 4 - Add pointer back from css::Declaration to css::Rule. r=heycam (2f86331573)
- Bug 978833 patch 5 - Rename ImportantRule to ImportantStyleData. r=heycam (e8471fc026)
- Bug 978833 patch 6 - Move ImportantStyleData from StyleRule.{h,cpp} to Declaration.{h,cpp} r=heycam (612875a128)
- Bug 978833 patch 7 - Fuse allocation of ImportantStyleData with Declaration. r=heycam (a8e9e99a35)
- Bug 978833 patch 8 - Call SetImmutable for declarations of @page and keyframe rules. r=heycam (6b04b5a81e)
- Bug 978833 patch 9 - Move keyframe !important data assertion to where it will continue to happen. r=heycam (862c6df232)
- Bug 978833 patch 10 - Raise consistent exceptions so that the exception doesn't depend on rule destruction timing. r=bzbarsky (8bd58857e9)
- Bug 978833 patch 11 - Add missing #includes in preparation for nsRuleWalker.h #include change in following patch. r=heycam (25a6357983)
- Bug 1180118 - Part 6: Return eRestyle_SomeDescendants from HasAttributeDependentStyle where appropriate. r=bzbarsky (21d88cc938)
- Bug 1202512 - Part 2: Make SelectorMatchesTree take a flags argument. r=bzbarsky (b660a417f8)
- Bug 978833 patch 12 - Use the css::Declaration instead of the css::StyleRule as the matching rule. r=heycam (dd6a7914a6)
- Bug 978833 patch 13 - Remove important rule creation from css::StyleRule. r=heycam (4766c9a635)
- Bug 978833 patch 14 - Pass mozilla::css::Rule instead of nsIStyleRule to nsIDocument/nsIDocumentObserver style rule methods. r=heycam (a632b828b9)
- Bug 978833 patch 15 - Make css::Rule no longer inherit from nsIStyleRule. r=heycam (a975922671)
- Bug 978833 patch 16 - Always call Declaration::SetImmutable when we match a rule. r=heycam (0f0c89aede)
- Bug 978833 patch 17 - Remove Rule::mWasMatched. r=heycam (d0bb9bfef1)
- Bug 978833 patch 18 - Eliminate StyleRule::RuleMatched and call Declaration::SetImmutable directly for style rules (like for @page and keyframe rules).  r=heycam (70d5e45a7c)
- Bug 978833 patch 19 - Fix ResolvedStyleCache to use Declaration rather than nsCSSKeyframeRule as keys. r=heycam (223cf85e8b)
- Bug 978833 patch 20 - Rev IIDs that I should have revised in Bug 978833 patch 14. (c6421cbca8)
- Bug 1214936 - Make the ArrayBuffer constructor throw if invoked without 'new'. (r=evilpie) (ec76f43c26)
- Bug 1198826 - Rename obj parameter to buffer to improve readability, r=terrence (3b1d280a76)
- pointer style (1f9d6a7d22)
- Bug 1218111 - Fix property enumeration order of unboxed objects with expando properties. r=bhackett (a7fdc9482d)
- Bug 980945 - Throw when invoking a typed array constructor without new. r=efaust (4f80026991)
- Bug 1192572 - Add id to each opcode section in SpiderMonkey Bytecode documentation. r=Waldo (bfd9d4c165)
- Bug 1219363 - Fix sort of indexed properties to not include properties already in the Vector. r=jorendorff (77edd4d779)
- Bug 1217593 - Fix compilation of LComputeThis now this can be undefined r=shu (d227ddf666)
- Bug 1212343 - Propagate OOM from SafepointWriter r=nbp (d5a79b7d61)
- remove core files (e008661015)
- Bug 1215937 - Remove use of expression closure from js/xpconnect/. r=bholley (e928296111)
- Bug 1196975 - part1: shimwaiver. r=billm (40bc720f37)
- Bug 1196975 - part2: shimwaiver applications. r=mossop (60cf9a9342)
- Bug 1196975 - part3: GetTabForContentWindowNoShim. r=billm (05d2af3c9a)
- Bug 1196975 - part4: waiveInterposition. r=billm (31ecb441b1)
- Bug 1196975 - part5: waiveInterposition for childloader. r=mossop (fe30dddc85)
- Bug 1196975 - part6: SDK Worker should not support CPOWs. r=mossop (7e59947069)
- Bug 1129662: sdk/page-worker should use a remote page. r=krizsa (ef63bafbe4)
- Bug 1216157 - Check for OOM when generating Ion RegExp stubs. r=jonco (690229c6d7)
- Bug 1221436 patch 5 - Stop generating new style rules in DeclarationChanged (and rename it to SetDeclaration), since we no longer need a new style rule for nsIStyleRule identity rules. r=heycam (98d860d06e)
- Bug 1220516 - Devirtualize CSSStyleSheet::GetOriginalURI. r=bzbarsky (6669f8ef70)
- Fix formatting of some macros; no bug. (fe337a3e91)
- Bug 1165538 part 1 - Use delegated constructor for nsStyleFont to simplify code and remove the need of nsStyleFont::Init. r=heycam (521e59852a)
- Bug 1165538 part 2 - Add -moz-min-font-size-ratio internal property. r=heycam (a16ef2d609)
- Bug 1165538 part 3 - Apply -moz-min-font-size-ratio to rt elements and add test. r=heycam (363684724b)
- Bug 1035091 part 1: change CSS parser and loader APIs to distinguish UA, user, and author sheets instead of just UA vs everyone else. r=heycam (01decf75df)
- Bug 1221436 patch 1 - Have a pointer back from the css::Declaration for style attributes to the nsHTMLCSSStyleSheet. r=heycam (308bf9701e)
- Bug 1221436 patch 2 - For style attributes, only store a css::Declaration instead of a css::StyleRule. r=heycam (f068adb5e9)
- Bug 1167588 - Mark Rule::mParentRule as MOZ_NON_OWNING_REF. r=dbaron (bdb2bfe4a7)
- Bug 1221436 patch 3 - Remove Rule::SetHTMLCSSStyleSheet and related code, now unused. r=heycam (d4fd6fca7c)
- Bug 1221436 patch 4 - Use the same pointer to store the owning rule and the nsHTMLCSSStyleSheet on css::Declaration, since we never need both. r=heycam (1a949ec7dc)
- Bug 1221436 patch 6 - Remove mechanism for replacing style rules. r=heycam (870539dcca)
- Bug 1221436 patch 7 - Remove ReplaceStyleRule/ReplaceRuleInGroup mechanism. r=heycam (a8a58186c1)
- Bug 1186768 patch 1 - Avoid setting different font-size conditions due to MathML font size adjustments. r=heycam (5b48d02031)
- Bug 1146101 - Test. r=dbaron a=abillings (b214ab1529)
- Bug 1161366 - Correctly set referrer when loading fonts with |new FontFace()|. r=dbaron (52a59ad6a4)
- Bug 1206105 - Use CheckedInt for an+b selector matching. r=bzbarsky (739875148c)
- Bug 1163446 - Drop reference to FontFace once a FontFaceBufferSource is loaded. r=jdaggett (9fd3a219c6)
- Bug 1164813 - Make nsAnimationManager update cached in-effect status even when there is no frame; r=dbaron (6f94c96764)
- Bug 1186768 patch 2 - Crashtest. r=heycam (a566cfef9b)
- Bug 1186768 patch 3 - Compute affectedByScriptMinSize sooner to avoid asserting or doing extra work. r=heycam (30dac96a78)
- Bug 1038663 (part 1) - Make nsStyleText::mWordSpacing an nsStyleCoord. r=heycam. (42a6a2398a)
- Bug 1038663 (part 2, attempt 2) - Move GetFirstFontMetrics() up. r=heycam. (5992325377)
- Bug 1038663 (part 3, attempt 2) - Factor out space width computation. r=heycam. (92281609f0)
- Bug 1038663 (part 4, attempt 2) - Inline StyleToCoord(). r=heycam. (f40476c105)
- Bug 1038663 (part 5, attempt 2) - Change GetSpacingFlags(). r=heycam (e1fe5ecdf0)
- Bug 1038663 (part 6, attempt 2) - Allow percentage values for 'word-spacing'. r=heycam. (433fee69f6)
- Bug 1038663 (part 7, attempt 3) - Add test for percentage values for 'word-spacing'. r=heycam. (72df555579)
- Bug 1216747 - Record dependency on writing mode in nsRuleNode::ComputeStylePosition. r=heycam (8604ceff20)
- Bug 1216747 followup - Use the correct value when calling SetWritingModeDependency. (b39a82cbf7)
- Bug 1216747 - Cleanup after test fix. r=heycam (e99ec5989a)
- Bug 1170781 - Patch 1: Implement CSS 'contain: paint'. r=dholbert (3b2f65288f)
- Bug 1170781 - Patch 2: Test CSS 'contain: paint'. r=dholbert (ee83c7c0fd)
2022-11-16 08:06:33 +08:00

908 lines
26 KiB
C++

/* -*- 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 "nsLayoutStylesheetCache.h"
#include "nsAppDirectoryServiceDefs.h"
#include "mozilla/CSSStyleSheet.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/Preferences.h"
#include "mozilla/css/Loader.h"
#include "nsIFile.h"
#include "nsNetUtil.h"
#include "nsIObserverService.h"
#include "nsServiceManagerUtils.h"
#include "nsIXULRuntime.h"
#include "nsPrintfCString.h"
// Includes for the crash report annotation in ErrorLoadingBuiltinSheet.
#ifdef MOZ_CRASHREPORTER
#include "mozilla/Omnijar.h"
#include "nsDirectoryService.h"
#include "nsDirectoryServiceDefs.h"
#include "nsExceptionHandler.h"
#include "nsIChromeRegistry.h"
#include "nsISimpleEnumerator.h"
#include "nsISubstitutingProtocolHandler.h"
#endif
using namespace mozilla;
using namespace mozilla::css;
static bool sNumberControlEnabled;
#define NUMBER_CONTROL_PREF "dom.forms.number"
NS_IMPL_ISUPPORTS(
nsLayoutStylesheetCache, nsIObserver, nsIMemoryReporter)
nsresult
nsLayoutStylesheetCache::Observe(nsISupports* aSubject,
const char* aTopic,
const char16_t* aData)
{
if (!strcmp(aTopic, "profile-before-change")) {
mUserContentSheet = nullptr;
mUserChromeSheet = nullptr;
}
else if (!strcmp(aTopic, "profile-do-change")) {
InitFromProfile();
}
else if (strcmp(aTopic, "chrome-flush-skin-caches") == 0 ||
strcmp(aTopic, "chrome-flush-caches") == 0) {
mScrollbarsSheet = nullptr;
mFormsSheet = nullptr;
mNumberControlSheet = nullptr;
}
else {
NS_NOTREACHED("Unexpected observer topic.");
}
return NS_OK;
}
CSSStyleSheet*
nsLayoutStylesheetCache::ScrollbarsSheet()
{
EnsureGlobal();
if (!gStyleCache->mScrollbarsSheet) {
// Scrollbars don't need access to unsafe rules
LoadSheetURL("chrome://global/skin/scrollbars.css",
gStyleCache->mScrollbarsSheet, eAuthorSheetFeatures);
}
return gStyleCache->mScrollbarsSheet;
}
CSSStyleSheet*
nsLayoutStylesheetCache::FormsSheet()
{
EnsureGlobal();
if (!gStyleCache->mFormsSheet) {
// forms.css needs access to unsafe rules
LoadSheetURL("resource://gre-resources/forms.css",
gStyleCache->mFormsSheet, eAgentSheetFeatures);
}
return gStyleCache->mFormsSheet;
}
CSSStyleSheet*
nsLayoutStylesheetCache::NumberControlSheet()
{
EnsureGlobal();
if (!sNumberControlEnabled) {
return nullptr;
}
if (!gStyleCache->mNumberControlSheet) {
LoadSheetURL("resource://gre-resources/number-control.css",
gStyleCache->mNumberControlSheet, eAgentSheetFeatures);
}
return gStyleCache->mNumberControlSheet;
}
CSSStyleSheet*
nsLayoutStylesheetCache::UserContentSheet()
{
EnsureGlobal();
return gStyleCache->mUserContentSheet;
}
CSSStyleSheet*
nsLayoutStylesheetCache::UserChromeSheet()
{
EnsureGlobal();
return gStyleCache->mUserChromeSheet;
}
CSSStyleSheet*
nsLayoutStylesheetCache::UASheet()
{
EnsureGlobal();
if (!gStyleCache->mUASheet) {
LoadSheetURL("resource://gre-resources/ua.css",
gStyleCache->mUASheet, eAgentSheetFeatures);
}
return gStyleCache->mUASheet;
}
CSSStyleSheet*
nsLayoutStylesheetCache::HTMLSheet()
{
EnsureGlobal();
if (!gStyleCache->mHTMLSheet) {
LoadSheetURL("resource://gre-resources/html.css",
gStyleCache->mHTMLSheet, eAgentSheetFeatures);
}
return gStyleCache->mHTMLSheet;
}
CSSStyleSheet*
nsLayoutStylesheetCache::MinimalXULSheet()
{
EnsureGlobal();
return gStyleCache->mMinimalXULSheet;
}
CSSStyleSheet*
nsLayoutStylesheetCache::XULSheet()
{
EnsureGlobal();
return gStyleCache->mXULSheet;
}
CSSStyleSheet*
nsLayoutStylesheetCache::QuirkSheet()
{
EnsureGlobal();
return gStyleCache->mQuirkSheet;
}
CSSStyleSheet*
nsLayoutStylesheetCache::SVGSheet()
{
EnsureGlobal();
return gStyleCache->mSVGSheet;
}
CSSStyleSheet*
nsLayoutStylesheetCache::MathMLSheet()
{
EnsureGlobal();
if (!gStyleCache->mMathMLSheet) {
LoadSheetURL("resource://gre-resources/mathml.css",
gStyleCache->mMathMLSheet, eAgentSheetFeatures);
}
return gStyleCache->mMathMLSheet;
}
CSSStyleSheet*
nsLayoutStylesheetCache::CounterStylesSheet()
{
EnsureGlobal();
return gStyleCache->mCounterStylesSheet;
}
CSSStyleSheet*
nsLayoutStylesheetCache::NoScriptSheet()
{
EnsureGlobal();
if (!gStyleCache->mNoScriptSheet) {
// If you update the data: URL, also update noscript.css (See bug 1194856.)
LoadSheetURL(
#ifdef RELEASE_BUILD
"data:text/css,noscript { display%3A none !important%3B }",
#else
"resource://gre-resources/noscript.css",
#endif
gStyleCache->mNoScriptSheet, eAgentSheetFeatures);
}
return gStyleCache->mNoScriptSheet;
}
CSSStyleSheet*
nsLayoutStylesheetCache::NoFramesSheet()
{
EnsureGlobal();
if (!gStyleCache->mNoFramesSheet) {
// If you update the data: URL, also update noframes.css (See bug 1194856.)
LoadSheetURL(
#ifdef RELEASE_BUILD
"data:text/css,noframes { display%3A block%3B } "
"frame%2C frameset%2C iframe { display%3A none !important%3B }",
#else
"resource://gre-resources/noframes.css",
#endif
gStyleCache->mNoFramesSheet, eAgentSheetFeatures);
}
return gStyleCache->mNoFramesSheet;
}
/* static */ CSSStyleSheet*
nsLayoutStylesheetCache::ChromePreferenceSheet(nsPresContext* aPresContext)
{
EnsureGlobal();
if (!gStyleCache->mChromePreferenceSheet) {
gStyleCache->BuildPreferenceSheet(gStyleCache->mChromePreferenceSheet,
aPresContext);
}
return gStyleCache->mChromePreferenceSheet;
}
/* static */ CSSStyleSheet*
nsLayoutStylesheetCache::ContentPreferenceSheet(nsPresContext* aPresContext)
{
EnsureGlobal();
if (!gStyleCache->mContentPreferenceSheet) {
gStyleCache->BuildPreferenceSheet(gStyleCache->mContentPreferenceSheet,
aPresContext);
}
return gStyleCache->mContentPreferenceSheet;
}
/* static */ CSSStyleSheet*
nsLayoutStylesheetCache::ContentEditableSheet()
{
EnsureGlobal();
if (!gStyleCache->mContentEditableSheet) {
LoadSheetURL("resource://gre/res/contenteditable.css",
gStyleCache->mContentEditableSheet, eAgentSheetFeatures);
}
return gStyleCache->mContentEditableSheet;
}
/* static */ CSSStyleSheet*
nsLayoutStylesheetCache::DesignModeSheet()
{
EnsureGlobal();
if (!gStyleCache->mDesignModeSheet) {
LoadSheetURL("resource://gre/res/designmode.css",
gStyleCache->mDesignModeSheet, eAgentSheetFeatures);
}
return gStyleCache->mDesignModeSheet;
}
void
nsLayoutStylesheetCache::Shutdown()
{
NS_IF_RELEASE(gCSSLoader);
gStyleCache = nullptr;
}
MOZ_DEFINE_MALLOC_SIZE_OF(LayoutStylesheetCacheMallocSizeOf)
NS_IMETHODIMP
nsLayoutStylesheetCache::CollectReports(nsIHandleReportCallback* aHandleReport,
nsISupports* aData, bool aAnonymize)
{
return MOZ_COLLECT_REPORT(
"explicit/layout/style-sheet-cache", KIND_HEAP, UNITS_BYTES,
SizeOfIncludingThis(LayoutStylesheetCacheMallocSizeOf),
"Memory used for some built-in style sheets.");
}
size_t
nsLayoutStylesheetCache::SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) const
{
size_t n = aMallocSizeOf(this);
#define MEASURE(s) n += s ? s->SizeOfIncludingThis(aMallocSizeOf) : 0;
MEASURE(mChromePreferenceSheet);
MEASURE(mContentEditableSheet);
MEASURE(mContentPreferenceSheet);
MEASURE(mCounterStylesSheet);
MEASURE(mDesignModeSheet);
MEASURE(mFormsSheet);
MEASURE(mHTMLSheet);
MEASURE(mMathMLSheet);
MEASURE(mMinimalXULSheet);
MEASURE(mNoFramesSheet);
MEASURE(mNoScriptSheet);
MEASURE(mNumberControlSheet);
MEASURE(mQuirkSheet);
MEASURE(mSVGSheet);
MEASURE(mScrollbarsSheet);
MEASURE(mUASheet);
MEASURE(mUserChromeSheet);
MEASURE(mUserContentSheet);
MEASURE(mXULSheet);
// Measurement of the following members may be added later if DMD finds it is
// worthwhile:
// - gCSSLoader
return n;
}
nsLayoutStylesheetCache::nsLayoutStylesheetCache()
{
nsCOMPtr<nsIObserverService> obsSvc =
mozilla::services::GetObserverService();
NS_ASSERTION(obsSvc, "No global observer service?");
if (obsSvc) {
obsSvc->AddObserver(this, "profile-before-change", false);
obsSvc->AddObserver(this, "profile-do-change", false);
obsSvc->AddObserver(this, "chrome-flush-skin-caches", false);
obsSvc->AddObserver(this, "chrome-flush-caches", false);
}
InitFromProfile();
// And make sure that we load our UA sheets. No need to do this
// per-profile, since they're profile-invariant.
LoadSheetURL("resource://gre-resources/counterstyles.css",
mCounterStylesSheet, eAgentSheetFeatures);
LoadSheetURL("chrome://global/content/minimal-xul.css",
mMinimalXULSheet, eAgentSheetFeatures);
LoadSheetURL("resource://gre-resources/quirk.css",
mQuirkSheet, eAgentSheetFeatures);
LoadSheetURL("resource://gre/res/svg.css",
mSVGSheet, eAgentSheetFeatures);
LoadSheetURL("chrome://global/content/xul.css",
mXULSheet, eAgentSheetFeatures);
// The remaining sheets are created on-demand do to their use being rarer
// (which helps save memory for Firefox OS apps) or because they need to
// be re-loadable in DependentPrefChanged.
}
nsLayoutStylesheetCache::~nsLayoutStylesheetCache()
{
mozilla::UnregisterWeakMemoryReporter(this);
MOZ_ASSERT(!gStyleCache);
}
void
nsLayoutStylesheetCache::InitMemoryReporter()
{
mozilla::RegisterWeakMemoryReporter(this);
}
void
nsLayoutStylesheetCache::EnsureGlobal()
{
MOZ_ASSERT(NS_IsMainThread());
if (gStyleCache) return;
gStyleCache = new nsLayoutStylesheetCache();
gStyleCache->InitMemoryReporter();
Preferences::AddBoolVarCache(&sNumberControlEnabled, NUMBER_CONTROL_PREF,
true);
// For each pref that controls a CSS feature that a UA style sheet depends
// on (such as a pref that enables a property that a UA style sheet uses),
// register DependentPrefChanged as a callback to ensure that the relevant
// style sheets will be re-parsed.
Preferences::RegisterCallback(&DependentPrefChanged,
"layout.css.ruby.enabled");
}
void
nsLayoutStylesheetCache::InitFromProfile()
{
nsCOMPtr<nsIXULRuntime> appInfo = do_GetService("@mozilla.org/xre/app-info;1");
if (appInfo) {
bool inSafeMode = false;
appInfo->GetInSafeMode(&inSafeMode);
if (inSafeMode)
return;
}
nsCOMPtr<nsIFile> contentFile;
nsCOMPtr<nsIFile> chromeFile;
NS_GetSpecialDirectory(NS_APP_USER_CHROME_DIR,
getter_AddRefs(contentFile));
if (!contentFile) {
// if we don't have a profile yet, that's OK!
return;
}
contentFile->Clone(getter_AddRefs(chromeFile));
if (!chromeFile) return;
contentFile->Append(NS_LITERAL_STRING("userContent.css"));
chromeFile->Append(NS_LITERAL_STRING("userChrome.css"));
LoadSheetFile(contentFile, mUserContentSheet, eUserSheetFeatures);
LoadSheetFile(chromeFile, mUserChromeSheet, eUserSheetFeatures);
}
/* static */ void
nsLayoutStylesheetCache::LoadSheetURL(const char* aURL,
RefPtr<CSSStyleSheet>& aSheet,
SheetParsingMode aParsingMode)
{
nsCOMPtr<nsIURI> uri;
NS_NewURI(getter_AddRefs(uri), aURL);
LoadSheet(uri, aSheet, aParsingMode);
if (!aSheet) {
NS_ERROR(nsPrintfCString("Could not load %s", aURL).get());
}
}
void
nsLayoutStylesheetCache::LoadSheetFile(nsIFile* aFile,
RefPtr<CSSStyleSheet>& aSheet,
SheetParsingMode aParsingMode)
{
bool exists = false;
aFile->Exists(&exists);
if (!exists) return;
nsCOMPtr<nsIURI> uri;
NS_NewFileURI(getter_AddRefs(uri), aFile);
LoadSheet(uri, aSheet, aParsingMode);
}
#ifdef MOZ_CRASHREPORTER
static void
ListInterestingFiles(nsString& aAnnotation, nsIFile* aFile,
const nsTArray<nsString>& aInterestingFilenames)
{
nsString filename;
aFile->GetLeafName(filename);
for (const nsString& interestingFilename : aInterestingFilenames) {
if (interestingFilename == filename) {
nsString path;
aFile->GetPath(path);
aAnnotation.AppendLiteral(" ");
aAnnotation.Append(path);
aAnnotation.AppendLiteral(" (");
int64_t size;
if (NS_SUCCEEDED(aFile->GetFileSize(&size))) {
aAnnotation.AppendPrintf("%ld", size);
} else {
aAnnotation.AppendLiteral("???");
}
aAnnotation.AppendLiteral(" bytes)\n");
return;
}
}
bool isDir = false;
aFile->IsDirectory(&isDir);
if (!isDir) {
return;
}
nsCOMPtr<nsISimpleEnumerator> entries;
if (NS_FAILED(aFile->GetDirectoryEntries(getter_AddRefs(entries)))) {
aAnnotation.AppendLiteral(" (failed to enumerated directory)\n");
return;
}
for (;;) {
bool hasMore = false;
if (NS_FAILED(entries->HasMoreElements(&hasMore))) {
aAnnotation.AppendLiteral(" (failed during directory enumeration)\n");
return;
}
if (!hasMore) {
break;
}
nsCOMPtr<nsISupports> entry;
if (NS_FAILED(entries->GetNext(getter_AddRefs(entry)))) {
aAnnotation.AppendLiteral(" (failed during directory enumeration)\n");
return;
}
nsCOMPtr<nsIFile> file = do_QueryInterface(entry);
if (file) {
ListInterestingFiles(aAnnotation, file, aInterestingFilenames);
}
}
}
// Generate a crash report annotation to help debug issues with style
// sheets failing to load (bug 1194856).
static void
AnnotateCrashReport(nsIURI* aURI)
{
nsAutoCString spec;
nsAutoCString scheme;
nsDependentCSubstring filename;
if (aURI) {
aURI->GetSpec(spec);
aURI->GetScheme(scheme);
int32_t i = spec.RFindChar('/');
if (i != -1) {
filename.Rebind(spec, i + 1);
}
}
nsString annotation;
// The URL of the sheet that failed to load.
annotation.AppendLiteral("Error loading sheet: ");
annotation.Append(NS_ConvertUTF8toUTF16(spec).get());
annotation.Append('\n');
// The jar: or file: URL that the sheet's resource: or chrome: URL
// resolves to.
if (scheme.EqualsLiteral("resource")) {
annotation.AppendLiteral("Real location: ");
nsCOMPtr<nsISubstitutingProtocolHandler> handler;
nsCOMPtr<nsIIOService> io(do_GetIOService());
if (io) {
nsCOMPtr<nsIProtocolHandler> ph;
io->GetProtocolHandler(scheme.get(), getter_AddRefs(ph));
if (ph) {
handler = do_QueryInterface(ph);
}
}
if (!handler) {
annotation.AppendLiteral("(ResolveURI failed)\n");
} else {
nsAutoCString resolvedSpec;
handler->ResolveURI(aURI, resolvedSpec);
annotation.Append(NS_ConvertUTF8toUTF16(resolvedSpec));
annotation.Append('\n');
}
} else if (scheme.EqualsLiteral("chrome")) {
annotation.AppendLiteral("Real location: ");
nsCOMPtr<nsIChromeRegistry> reg =
mozilla::services::GetChromeRegistryService();
if (!reg) {
annotation.AppendLiteral("(no chrome registry)\n");
} else {
nsCOMPtr<nsIURI> resolvedURI;
reg->ConvertChromeURL(aURI, getter_AddRefs(resolvedURI));
if (!resolvedURI) {
annotation.AppendLiteral("(ConvertChromeURL failed)\n");
} else {
nsAutoCString resolvedSpec;
resolvedURI->GetSpec(resolvedSpec);
annotation.Append(NS_ConvertUTF8toUTF16(resolvedSpec));
annotation.Append('\n');
}
}
}
nsTArray<nsString> interestingFiles;
interestingFiles.AppendElement(NS_LITERAL_STRING("chrome.manifest"));
interestingFiles.AppendElement(NS_LITERAL_STRING("omni.ja"));
interestingFiles.AppendElement(NS_ConvertUTF8toUTF16(filename));
annotation.AppendLiteral("GRE directory: ");
nsCOMPtr<nsIFile> file;
nsDirectoryService::gService->Get(NS_GRE_DIR, NS_GET_IID(nsIFile),
getter_AddRefs(file));
if (file) {
// The Firefox installation directory.
nsString path;
file->GetPath(path);
annotation.Append(path);
annotation.Append('\n');
// List interesting files -- any chrome.manifest or omni.ja file or any file
// whose name is the sheet's filename -- under the Firefox installation
// directory.
annotation.AppendLiteral("Interesting files in the GRE directory:\n");
ListInterestingFiles(annotation, file, interestingFiles);
// If the Firefox installation directory has a chrome.manifest file, let's
// see what's in it.
file->Append(NS_LITERAL_STRING("chrome.manifest"));
bool exists = false;
file->Exists(&exists);
if (exists) {
annotation.AppendLiteral("Contents of chrome.manifest:\n[[[\n");
PRFileDesc* fd;
if (NS_SUCCEEDED(file->OpenNSPRFileDesc(PR_RDONLY, 0, &fd))) {
nsCString contents;
char buf[512];
int32_t n;
while ((n = PR_Read(fd, buf, sizeof(buf))) > 0) {
contents.Append(buf, n);
}
if (n < 0) {
annotation.AppendLiteral(" (error while reading)\n");
} else {
annotation.Append(NS_ConvertUTF8toUTF16(contents));
}
PR_Close(fd);
}
annotation.AppendLiteral("]]]\n");
}
} else {
annotation.AppendLiteral("(none)\n");
}
// The jar: or file: URL prefix that chrome: and resource: URLs get translated
// to.
annotation.AppendLiteral("GRE omnijar URI string: ");
nsCString uri;
nsresult rv = Omnijar::GetURIString(Omnijar::GRE, uri);
if (NS_FAILED(rv)) {
annotation.AppendLiteral("(failed)\n");
} else {
annotation.Append(NS_ConvertUTF8toUTF16(uri));
annotation.Append('\n');
}
RefPtr<nsZipArchive> zip = Omnijar::GetReader(Omnijar::GRE);
if (zip) {
// List interesting files in the GRE omnijar.
annotation.AppendLiteral("Interesting files in the GRE omnijar:\n");
nsZipFind* find;
rv = zip->FindInit(nullptr, &find);
if (NS_FAILED(rv)) {
annotation.AppendPrintf(" (FindInit failed with 0x%08x)\n", rv);
} else if (!find) {
annotation.AppendLiteral(" (FindInit returned null)\n");
} else {
const char* result;
uint16_t len;
while (NS_SUCCEEDED(find->FindNext(&result, &len))) {
nsCString itemPathname;
nsString itemFilename;
itemPathname.Append(result, len);
int32_t i = itemPathname.RFindChar('/');
if (i != -1) {
itemFilename = NS_ConvertUTF8toUTF16(Substring(itemPathname, i + 1));
}
for (const nsString& interestingFile : interestingFiles) {
if (interestingFile == itemFilename) {
annotation.AppendLiteral(" ");
annotation.Append(NS_ConvertUTF8toUTF16(itemPathname));
nsZipItem* item = zip->GetItem(itemPathname.get());
if (!item) {
annotation.AppendLiteral(" (GetItem failed)\n");
} else {
annotation.AppendPrintf(" (%d bytes, crc32 = 0x%08x)\n",
item->RealSize(),
item->CRC32());
}
break;
}
}
}
delete find;
}
} else {
annotation.AppendLiteral("No GRE omnijar\n");
}
CrashReporter::AnnotateCrashReport(NS_LITERAL_CSTRING("SheetLoadFailure"),
NS_ConvertUTF16toUTF8(annotation));
}
#endif
static void
ErrorLoadingBuiltinSheet(nsIURI* aURI, const char* aMsg)
{
#ifdef MOZ_CRASHREPORTER
AnnotateCrashReport(aURI);
#endif
nsAutoCString spec;
if (aURI) {
aURI->GetSpec(spec);
}
NS_RUNTIMEABORT(nsPrintfCString("%s loading built-in stylesheet '%s'",
aMsg, spec.get()).get());
}
void
nsLayoutStylesheetCache::LoadSheet(nsIURI* aURI,
RefPtr<CSSStyleSheet>& aSheet,
SheetParsingMode aParsingMode)
{
if (!aURI) {
ErrorLoadingBuiltinSheet(aURI, "null URI");
return;
}
if (!gCSSLoader) {
gCSSLoader = new mozilla::css::Loader();
NS_IF_ADDREF(gCSSLoader);
if (!gCSSLoader) {
ErrorLoadingBuiltinSheet(aURI, "no Loader");
return;
}
}
nsresult rv = gCSSLoader->LoadSheetSync(aURI, aParsingMode, true,
getter_AddRefs(aSheet));
if (NS_FAILED(rv)) {
ErrorLoadingBuiltinSheet(aURI,
nsPrintfCString("LoadSheetSync failed with error %x", rv).get());
}
}
/* static */ void
nsLayoutStylesheetCache::InvalidateSheet(RefPtr<CSSStyleSheet>& aSheet)
{
MOZ_ASSERT(gCSSLoader, "pref changed before we loaded a sheet?");
if (aSheet) {
gCSSLoader->ObsoleteSheet(aSheet->GetSheetURI());
aSheet = nullptr;
}
}
/* static */ void
nsLayoutStylesheetCache::DependentPrefChanged(const char* aPref, void* aData)
{
MOZ_ASSERT(gStyleCache, "pref changed after shutdown?");
// Cause any UA style sheets whose parsing depends on the value of prefs
// to be re-parsed by dropping the sheet from gCSSLoader's cache then
// setting our cached sheet pointer to null. This will only work for sheets
// that are loaded lazily.
// for layout.css.ruby.enabled
InvalidateSheet(gStyleCache->mUASheet);
InvalidateSheet(gStyleCache->mHTMLSheet);
}
/* static */ void
nsLayoutStylesheetCache::InvalidatePreferenceSheets()
{
if (!gStyleCache) {
return;
}
gStyleCache->mContentPreferenceSheet = nullptr;
gStyleCache->mChromePreferenceSheet = nullptr;
}
/* static */ void
nsLayoutStylesheetCache::AppendPreferenceRule(CSSStyleSheet* aSheet,
const nsAString& aString)
{
uint32_t result;
aSheet->InsertRuleInternal(aString, aSheet->StyleRuleCount(), &result);
}
/* static */ void
nsLayoutStylesheetCache::AppendPreferenceColorRule(CSSStyleSheet* aSheet,
const char* aString,
nscolor aColor)
{
nsAutoString rule;
rule.AppendPrintf(
aString, NS_GET_R(aColor), NS_GET_G(aColor), NS_GET_B(aColor));
AppendPreferenceRule(aSheet, rule);
}
void
nsLayoutStylesheetCache::BuildPreferenceSheet(RefPtr<CSSStyleSheet>& aSheet,
nsPresContext* aPresContext)
{
aSheet = new CSSStyleSheet(CORS_NONE, mozilla::net::RP_Default);
nsCOMPtr<nsIURI> uri;
NS_NewURI(getter_AddRefs(uri), "about:PreferenceStyleSheet", nullptr);
MOZ_ASSERT(uri, "URI creation shouldn't fail");
aSheet->SetURIs(uri, uri, uri);
aSheet->SetComplete();
AppendPreferenceRule(aSheet,
NS_LITERAL_STRING("@namespace url(http://www.w3.org/1999/xhtml);"));
AppendPreferenceRule(aSheet,
NS_LITERAL_STRING("@namespace svg url(http://www.w3.org/2000/svg);"));
// Rules for link styling.
AppendPreferenceColorRule(aSheet,
"*|*:link { color: #%02x%02x%02x; }",
aPresContext->DefaultLinkColor());
AppendPreferenceColorRule(aSheet,
"*|*:-moz-any-link:active { color: #%02x%02x%02x; }",
aPresContext->DefaultActiveLinkColor());
AppendPreferenceColorRule(aSheet,
"*|*:visited { color: #%02x%02x%02x; }",
aPresContext->DefaultVisitedLinkColor());
AppendPreferenceRule(aSheet,
aPresContext->GetCachedBoolPref(kPresContext_UnderlineLinks) ?
NS_LITERAL_STRING(
"*|*:-moz-any-link:not(svg|a) { text-decoration: underline; }") :
NS_LITERAL_STRING(
"*|*:-moz-any-link{ text-decoration: none; }"));
// Rules for focus styling.
bool focusRingOnAnything = aPresContext->GetFocusRingOnAnything();
uint8_t focusRingWidth = aPresContext->FocusRingWidth();
uint8_t focusRingStyle = aPresContext->GetFocusRingStyle();
if ((focusRingWidth != 1 && focusRingWidth <= 4) || focusRingOnAnything) {
if (focusRingWidth != 1) {
// If the focus ring width is different from the default, fix buttons
// with rings.
nsString rule;
rule.AppendPrintf(
"button::-moz-focus-inner, input[type=\"reset\"]::-moz-focus-inner, "
"input[type=\"button\"]::-moz-focus-inner, "
"input[type=\"submit\"]::-moz-focus-inner { "
"padding: 1px 2px 1px 2px; "
"border: %d %s transparent !important; }",
focusRingWidth,
focusRingWidth == 0 ? (const char*) "solid" : (const char*) "dotted");
AppendPreferenceRule(aSheet, rule);
// NS_LITERAL_STRING doesn't work with concatenated string literals, hence
// the newline escaping.
AppendPreferenceRule(aSheet, NS_LITERAL_STRING("\
button:focus::-moz-focus-inner, \
input[type=\"reset\"]:focus::-moz-focus-inner, \
input[type=\"button\"]:focus::-moz-focus-inner, \
input[type=\"submit\"]:focus::-moz-focus-inner { \
border-color: ButtonText !important; }"));
}
nsString rule;
if (focusRingOnAnything) {
rule.AppendLiteral(":focus");
} else {
rule.AppendLiteral("*|*:link:focus, *|*:visited:focus");
}
rule.AppendPrintf(" { outline: %dpx ", focusRingWidth);
if (focusRingStyle == 0) { // solid
rule.AppendLiteral("solid -moz-mac-focusring !important; "
"-moz-outline-radius: 3px; outline-offset: 1px; }");
} else {
rule.AppendLiteral("dotted WindowText !important; }");
}
AppendPreferenceRule(aSheet, rule);
}
if (aPresContext->GetUseFocusColors()) {
nsString rule;
nscolor focusText = aPresContext->FocusTextColor();
nscolor focusBG = aPresContext->FocusBackgroundColor();
rule.AppendPrintf(
"*:focus, *:focus > font { color: #%02x%02x%02x !important; "
"background-color: #%02x%02x%02x !important; }",
NS_GET_R(focusText), NS_GET_G(focusText), NS_GET_B(focusText),
NS_GET_R(focusBG), NS_GET_G(focusBG), NS_GET_B(focusBG));
AppendPreferenceRule(aSheet, rule);
}
}
mozilla::StaticRefPtr<nsLayoutStylesheetCache>
nsLayoutStylesheetCache::gStyleCache;
mozilla::css::Loader*
nsLayoutStylesheetCache::gCSSLoader = nullptr;