/* -*- 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/. */ /* a presentation of a document, part 1 */ #include "nsPresContext.h" #include "nsPresContextInlines.h" #include "mozilla/ArrayUtils.h" #if defined(MOZ_WIDGET_ANDROID) # include "mozilla/AsyncEventDispatcher.h" #endif #include "mozilla/CycleCollectedJSContext.h" #include "mozilla/DebugOnly.h" #include "mozilla/Encoding.h" #include "mozilla/EventDispatcher.h" #include "mozilla/EventStateManager.h" #include "mozilla/PresShell.h" #include "mozilla/PresShellInlines.h" #include "mozilla/dom/ContentParent.h" #include "mozilla/dom/WindowGlobalChild.h" #include "base/basictypes.h" #include "nsCOMPtr.h" #include "nsCSSFrameConstructor.h" #include "nsDocShell.h" #include "nsIContentViewer.h" #include "nsPIDOMWindow.h" #include "mozilla/ServoStyleSet.h" #include "mozilla/MediaFeatureChange.h" #include "nsIContent.h" #include "nsIFrame.h" #include "mozilla/dom/BrowsingContext.h" #include "mozilla/dom/Document.h" #include "mozilla/dom/DocumentInlines.h" #include "nsIPrintSettings.h" #include "nsLanguageAtomService.h" #include "mozilla/LookAndFeel.h" #include "nsIInterfaceRequestorUtils.h" #include "nsHTMLDocument.h" #include "nsIWeakReferenceUtils.h" #include "nsThreadUtils.h" #include "nsLayoutUtils.h" #include "nsViewManager.h" #include "mozilla/RestyleManager.h" #include "SurfaceCacheUtils.h" #include "nsMediaFeatures.h" #include "gfxPlatform.h" #include "nsFontFaceLoader.h" #include "mozilla/AnimationEventDispatcher.h" #include "mozilla/EffectCompositor.h" #include "mozilla/EventListenerManager.h" #include "prenv.h" #include "nsPluginFrame.h" #include "nsTransitionManager.h" #include "nsAnimationManager.h" #include "CounterStyleManager.h" #include "mozilla/MemoryReporting.h" #include "mozilla/dom/Element.h" #include "nsIMessageManager.h" #include "mozilla/dom/HTMLBodyElement.h" #include "mozilla/dom/MediaQueryList.h" #include "mozilla/SMILAnimationController.h" #include "mozilla/css/ImageLoader.h" #include "mozilla/dom/PBrowserParent.h" #include "mozilla/dom/BrowserChild.h" #include "mozilla/dom/BrowserParent.h" #include "mozilla/StaticPresData.h" #include "nsRefreshDriver.h" #include "Layers.h" #include "LayerUserData.h" #include "ClientLayerManager.h" #include "mozilla/dom/NotifyPaintEvent.h" #include "nsFrameLoader.h" #include "nsContentUtils.h" #include "nsPIWindowRoot.h" #include "mozilla/Preferences.h" #include "gfxTextRun.h" #include "nsFontFaceUtils.h" #include "mozilla/GlobalStyleSheetCache.h" #include "mozilla/ServoBindings.h" #include "mozilla/StaticPrefs_layout.h" #include "mozilla/StaticPrefs_zoom.h" #include "mozilla/StyleSheet.h" #include "mozilla/StyleSheetInlines.h" #include "mozilla/Telemetry.h" #include "mozilla/dom/Performance.h" #include "mozilla/dom/PerformanceTiming.h" #include "mozilla/dom/PerformancePaintTiming.h" #include "mozilla/layers/APZThreadUtils.h" #include "MobileViewportManager.h" #include "mozilla/dom/ImageTracker.h" // Needed for Start/Stop of Image Animation #include "imgIContainer.h" #include "nsIImageLoadingContent.h" #include "nsBidiUtils.h" #include "nsServiceManagerUtils.h" #include "nsBidi.h" #include "mozilla/dom/URL.h" #include "mozilla/ServoCSSParser.h" using namespace mozilla; using namespace mozilla::dom; using namespace mozilla::gfx; using namespace mozilla::layers; uint8_t gNotifySubDocInvalidationData; /** * Layer UserData for ContainerLayers that want to be notified * of local invalidations of them and their descendant layers. * Pass a callback to ComputeDifferences to have these called. */ class ContainerLayerPresContext : public LayerUserData { public: nsPresContext* mPresContext; }; bool nsPresContext::IsDOMPaintEventPending() { if (!mTransactions.IsEmpty()) { return true; } nsRootPresContext* drpc = GetRootPresContext(); if (drpc && drpc->mRefreshDriver->ViewManagerFlushIsPending()) { // Since we're promising that there will be a MozAfterPaint event // fired, we record an empty invalidation in case display list // invalidation doesn't invalidate anything further. NotifyInvalidation(drpc->mRefreshDriver->LastTransactionId().Next(), nsRect(0, 0, 0, 0)); return true; } return false; } void nsPresContext::ForceReflowForFontInfoUpdate() { // Flush the device context's font cache, so that we won't risk getting // stale nsFontMetrics objects from it. DeviceContext()->FlushFontCache(); // If there's a user font set, discard any src:local() faces it may have // loaded because their font entries may no longer be valid. if (Document()->GetFonts()) { Document()->GetFonts()->GetUserFontSet()->ForgetLocalFaces(); } // We can trigger reflow by pretending a font.* preference has changed; // this is the same mechanism as gfxPlatform::ForceGlobalReflow() uses // if new fonts are installed during the session, for example. PreferenceChanged("font.internaluseonly.changed"); } static bool IsVisualCharset(NotNull aCharset) { return aCharset == ISO_8859_8_ENCODING; } nsPresContext::nsPresContext(dom::Document* aDocument, nsPresContextType aType) : mPresShell(nullptr), mDocument(aDocument), mMedium(aType == eContext_Galley ? nsGkAtoms::screen : nsGkAtoms::print), mSystemFontScale(1.0), mTextZoom(1.0), mEffectiveTextZoom(1.0), mFullZoom(1.0), mLastFontInflationScreenSize(gfxSize(-1.0, -1.0)), mCurAppUnitsPerDevPixel(0), mAutoQualityMinFontSizePixelsPref(0), mDynamicToolbarMaxHeight(0), mDynamicToolbarHeight(0), mPageSize(-1, -1), mPageScale(0.0), mPPScale(1.0f), mViewportScrollOverrideElement(nullptr), mElementsRestyled(0), mFramesConstructed(0), mFramesReflowed(0), mChangeHintForPrefChange(nsChangeHint(0)), mInterruptChecksToSkip(0), mNextFrameRateMultiplier(0), mViewportScrollStyles(StyleOverflow::Auto, StyleOverflow::Auto), // mImageAnimationMode is initialised below, in constructor body mImageAnimationModePref(imgIContainer::kNormalAnimMode), mType(aType), mInflationDisabledForShrinkWrap(false), mInteractionTimeEnabled(true), mHasPendingInterrupt(false), mHasEverBuiltInvisibleText(false), mPendingInterruptFromTest(false), mInterruptsEnabled(false), mSendAfterPaintToContent(false), mDrawImageBackground(true), // always draw the background mDrawColorBackground(true), // mNeverAnimate is initialised below, in constructor body mPaginated(aType != eContext_Galley), mCanPaginatedScroll(false), mDoScaledTwips(true), mIsRootPaginatedDocument(false), mPrefBidiDirection(false), mPrefScrollbarSide(0), mPendingThemeChanged(false), mPendingThemeChangeKind(0), mPendingUIResolutionChanged(false), mPostedPrefChangedRunnable(false), mIsGlyph(false), mUsesExChUnits(false), mCounterStylesDirty(true), mFontFeatureValuesDirty(true), mSuppressResizeReflow(false), mIsVisual(false), mPaintFlashing(false), mPaintFlashingInitialized(false), mHasWarnedAboutPositionedTableParts(false), mHasWarnedAboutTooLargeDashedOrDottedRadius(false), mQuirkSheetAdded(false), mHadNonBlankPaint(false), mHadContentfulPaint(false), mHadContentfulPaintComposite(false) #ifdef DEBUG , mInitialized(false) #endif { #ifdef DEBUG PodZero(&mLayoutPhaseCount); #endif if (!IsDynamic()) { mImageAnimationMode = imgIContainer::kDontAnimMode; mNeverAnimate = true; } else { mImageAnimationMode = imgIContainer::kNormalAnimMode; mNeverAnimate = false; } NS_ASSERTION(mDocument, "Null document"); // if text perf logging enabled, init stats struct if (MOZ_LOG_TEST(gfxPlatform::GetLog(eGfxLog_textperf), LogLevel::Warning)) { mTextPerf = MakeUnique(); } if (Preferences::GetBool(GFX_MISSING_FONTS_NOTIFY_PREF)) { mMissingFonts = MakeUnique(); } // TODO: check whether this is too expensive to do for all pages; // maybe we could throttle and only collect stats on 1% of page-loads, // or something like that. mFontStats = MakeUnique(); if (StaticPrefs::layout_dynamic_toolbar_max_height() > 0) { // The pref for dynamic toolbar max height is only used in reftests so it's // fine to set here. mDynamicToolbarMaxHeight = StaticPrefs::layout_dynamic_toolbar_max_height(); } } static const char* gExactCallbackPrefs[] = { "browser.underline_anchors", "browser.anchor_color", "browser.active_color", "browser.visited_color", "image.animation_mode", "dom.send_after_paint_to_content", "layout.css.dpi", "layout.css.devPixelsPerPx", "nglayout.debug.paint_flashing", "nglayout.debug.paint_flashing_chrome", "intl.accept_languages", "dom.meta-viewport.enabled", nullptr, }; static const char* gPrefixCallbackPrefs[] = { "font.", "browser.display.", "browser.viewport.", "bidi.", "gfx.font_rendering.", nullptr, }; void nsPresContext::Destroy() { if (mEventManager) { // unclear if these are needed, but can't hurt mEventManager->NotifyDestroyPresContext(this); mEventManager->SetPresContext(nullptr); mEventManager = nullptr; } // Unregister preference callbacks Preferences::UnregisterPrefixCallbacks(nsPresContext::PreferenceChanged, gPrefixCallbackPrefs, this); Preferences::UnregisterCallbacks(nsPresContext::PreferenceChanged, gExactCallbackPrefs, this); mRefreshDriver = nullptr; MOZ_ASSERT(mOneShotPostRefreshObservers.IsEmpty()); } nsPresContext::~nsPresContext() { MOZ_ASSERT(!mPresShell, "Presshell forgot to clear our mPresShell pointer"); DetachPresShell(); Destroy(); } NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsPresContext) NS_INTERFACE_MAP_ENTRY(nsISupports) NS_INTERFACE_MAP_END NS_IMPL_CYCLE_COLLECTING_ADDREF(nsPresContext) NS_IMPL_CYCLE_COLLECTING_RELEASE_WITH_LAST_RELEASE(nsPresContext, LastRelease()) void nsPresContext::LastRelease() { if (mMissingFonts) { mMissingFonts->Clear(); } } NS_IMPL_CYCLE_COLLECTION_CLASS(nsPresContext) NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsPresContext) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mAnimationEventDispatcher); NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDocument); // NS_IMPL_CYCLE_COLLECTION_TRAVERSE_RAWPTR(mDeviceContext); // not xpcom NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mEffectCompositor); NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mEventManager); // NS_IMPL_CYCLE_COLLECTION_TRAVERSE_RAWPTR(mLanguage); // an atom // NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTheme); // a service NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPrintSettings); NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsPresContext) NS_IMPL_CYCLE_COLLECTION_UNLINK(mAnimationEventDispatcher); NS_IMPL_CYCLE_COLLECTION_UNLINK(mDocument); NS_IMPL_CYCLE_COLLECTION_UNLINK(mDeviceContext); // worth bothering? NS_IMPL_CYCLE_COLLECTION_UNLINK(mEffectCompositor); // NS_RELEASE(tmp->mLanguage); // an atom // NS_IMPL_CYCLE_COLLECTION_UNLINK(mTheme); // a service NS_IMPL_CYCLE_COLLECTION_UNLINK(mPrintSettings); NS_IMPL_CYCLE_COLLECTION_UNLINK_WEAK_PTR tmp->Destroy(); NS_IMPL_CYCLE_COLLECTION_UNLINK_END // Set to true when LookAndFeelChanged needs to be called. This is used // because the look and feel is a service, so there's no need to notify it from // more than one prescontext. static bool sLookAndFeelChanged; // Set to true when ThemeChanged needs to be called on mTheme. This is used // because mTheme is a service, so there's no need to notify it from more than // one prescontext. static bool sThemeChanged; bool nsPresContext::IsChrome() const { return Document()->IsInChromeDocShell(); } void nsPresContext::GetUserPreferences() { if (!GetPresShell()) { // No presshell means nothing to do here. We'll do this when we // get a presshell. return; } mAutoQualityMinFontSizePixelsPref = Preferences::GetInt("browser.display.auto_quality_min_font_size"); PreferenceSheet::EnsureInitialized(); mSendAfterPaintToContent = Preferences::GetBool( "dom.send_after_paint_to_content", mSendAfterPaintToContent); mPrefScrollbarSide = Preferences::GetInt("layout.scrollbar.side"); Document()->SetMayNeedFontPrefsUpdate(); // * image animation nsAutoCString animatePref; Preferences::GetCString("image.animation_mode", animatePref); if (animatePref.EqualsLiteral("normal")) mImageAnimationModePref = imgIContainer::kNormalAnimMode; else if (animatePref.EqualsLiteral("none")) mImageAnimationModePref = imgIContainer::kDontAnimMode; else if (animatePref.EqualsLiteral("once")) mImageAnimationModePref = imgIContainer::kLoopOnceAnimMode; else // dynamic change to invalid value should act like it does initially mImageAnimationModePref = imgIContainer::kNormalAnimMode; uint32_t bidiOptions = GetBidi(); int32_t prefInt = Preferences::GetInt(IBMBIDI_TEXTDIRECTION_STR, GET_BIDI_OPTION_DIRECTION(bidiOptions)); SET_BIDI_OPTION_DIRECTION(bidiOptions, prefInt); mPrefBidiDirection = prefInt; prefInt = Preferences::GetInt(IBMBIDI_TEXTTYPE_STR, GET_BIDI_OPTION_TEXTTYPE(bidiOptions)); SET_BIDI_OPTION_TEXTTYPE(bidiOptions, prefInt); prefInt = Preferences::GetInt(IBMBIDI_NUMERAL_STR, GET_BIDI_OPTION_NUMERAL(bidiOptions)); SET_BIDI_OPTION_NUMERAL(bidiOptions, prefInt); // We don't need to force reflow: either we are initializing a new // prescontext or we are being called from UpdateAfterPreferencesChanged() // which triggers a reflow anyway. SetBidi(bidiOptions); } void nsPresContext::InvalidatePaintedLayers() { if (!mPresShell) { return; } if (nsIFrame* rootFrame = mPresShell->GetRootFrame()) { // FrameLayerBuilder caches invalidation-related values that depend on the // appunits-per-dev-pixel ratio, so ensure that all PaintedLayer drawing // is completely flushed. rootFrame->InvalidateFrameSubtree(); } } void nsPresContext::AppUnitsPerDevPixelChanged() { int32_t oldAppUnitsPerDevPixel = mCurAppUnitsPerDevPixel; InvalidatePaintedLayers(); if (mDeviceContext) { mDeviceContext->FlushFontCache(); } MediaFeatureValuesChanged( {RestyleHint::RecascadeSubtree(), NS_STYLE_HINT_REFLOW, MediaFeatureChangeReason::ResolutionChange}, MediaFeatureChangePropagation::JustThisDocument); mCurAppUnitsPerDevPixel = mDeviceContext->AppUnitsPerDevPixel(); // Recompute the size for vh units since it's changed by the dynamic toolbar // max height which is stored in screen coord. if (IsRootContentDocumentCrossProcess()) { AdjustSizeForViewportUnits(); } // nsSubDocumentFrame uses a AppUnitsPerDevPixel difference between parent and // child document to determine if it needs to build a nsDisplayZoom item. So // if we that changes then we need to invalidate the subdoc frame so that // item gets created/removed. if (mPresShell) { if (nsIFrame* frame = mPresShell->GetRootFrame()) { frame = nsLayoutUtils::GetCrossDocParentFrame(frame); if (frame) { int32_t parentAPD = frame->PresContext()->AppUnitsPerDevPixel(); if ((parentAPD == oldAppUnitsPerDevPixel) != (parentAPD == mCurAppUnitsPerDevPixel)) { frame->InvalidateFrame(); } } } } // We would also have to look at all of our child subdocuments but the // InvalidatePaintedLayers call above calls InvalidateFrameSubtree which // would invalidate all subdocument frames already. } // static void nsPresContext::PreferenceChanged(const char* aPrefName, void* aSelf) { static_cast(aSelf)->PreferenceChanged(aPrefName); } void nsPresContext::PreferenceChanged(const char* aPrefName) { nsDependentCString prefName(aPrefName); if (prefName.EqualsLiteral("layout.css.dpi") || prefName.EqualsLiteral("layout.css.devPixelsPerPx")) { int32_t oldAppUnitsPerDevPixel = mDeviceContext->AppUnitsPerDevPixel(); // We need to assume the DPI changes, since `mDeviceContext` is shared with // other documents, and we'd need to save the return value of the first call // for all of them. Unused << mDeviceContext->CheckDPIChange(); if (mPresShell) { OwningNonNull presShell(*mPresShell); // Re-fetch the view manager's window dimensions in case there's a // deferred resize which hasn't affected our mVisibleArea yet nscoord oldWidthAppUnits, oldHeightAppUnits; RefPtr vm = presShell->GetViewManager(); if (!vm) { return; } vm->GetWindowDimensions(&oldWidthAppUnits, &oldHeightAppUnits); float oldWidthDevPixels = oldWidthAppUnits / oldAppUnitsPerDevPixel; float oldHeightDevPixels = oldHeightAppUnits / oldAppUnitsPerDevPixel; AppUnitsPerDevPixelChanged(); nscoord width = NSToCoordRound(oldWidthDevPixels * AppUnitsPerDevPixel()); nscoord height = NSToCoordRound(oldHeightDevPixels * AppUnitsPerDevPixel()); vm->SetWindowDimensions(width, height); } return; } if (StringBeginsWith(prefName, "browser.viewport."_ns) || StringBeginsWith(prefName, "font.size.inflation."_ns) || prefName.EqualsLiteral("dom.meta-viewport.enabled")) { if (mPresShell) { mPresShell->MaybeReflowForInflationScreenSizeChange(); } } // Changing any of these potentially changes the value of @media // (prefers-contrast). if (prefName.EqualsLiteral("layout.css.prefers-contrast.enabled") || prefName.EqualsLiteral("browser.display.document_color_use") || prefName.EqualsLiteral("privacy.resistFingerprinting") || prefName.EqualsLiteral("browser.display.foreground_color") || prefName.EqualsLiteral("browser.display.background_color")) { MediaFeatureValuesChanged({MediaFeatureChangeReason::PreferenceChange}, MediaFeatureChangePropagation::JustThisDocument); } if (prefName.EqualsLiteral(GFX_MISSING_FONTS_NOTIFY_PREF)) { if (Preferences::GetBool(GFX_MISSING_FONTS_NOTIFY_PREF)) { if (!mMissingFonts) { mMissingFonts = MakeUnique(); // trigger reflow to detect missing fonts on the current page mChangeHintForPrefChange |= NS_STYLE_HINT_REFLOW; } } else { if (mMissingFonts) { mMissingFonts->Clear(); } mMissingFonts = nullptr; } } if (prefName.EqualsLiteral("font.internaluseonly.changed") && !IsPrintingOrPrintPreview()) { // If there's a change to the font list, we generally need to reconstruct // frames, as the existing frames may be referring to fonts that are no // longer available. But in the case of a static-clone document used for // printing or print-preview, this is undesirable because the nsPrintJob // is holding weak refs to frames that will get blown away unexpectedly by // this reconstruction. So the prescontext for a print/preview doc ignores // the font-list update. // // This means the print document may still be using cached fonts that are // no longer present in the font list, but that should be safe given that // all the required font instances have already been created, so it won't // be depending on access to the font-list entries. // // XXX Actually, I think it's probably a bad idea to do *any* restyling of // print documents in response to pref changes. We could be in the middle // of printing the document, and reflowing all the frames might cause some // kind of unwanted mid-document discontinuity. mChangeHintForPrefChange |= nsChangeHint_ReconstructFrame; } else if (StringBeginsWith(prefName, "font."_ns) || // Changes to font family preferences don't change anything in the // computed style data, so the style system won't generate a reflow // hint for us. We need to do that manually. prefName.EqualsLiteral("intl.accept_languages") || // Changes to bidi prefs need to trigger a reflow (see bug 443629) StringBeginsWith(prefName, "bidi."_ns) || // Changes to font_rendering prefs need to trigger a reflow StringBeginsWith(prefName, "gfx.font_rendering."_ns)) { mChangeHintForPrefChange |= NS_STYLE_HINT_REFLOW; } // We will end up calling InvalidatePreferenceSheets one from each pres // context, but all it's doing is clearing its cached sheet pointers, so it // won't be wastefully recreating the sheet multiple times. // // The first pres context that has its pref changed runnable called will // be the one to cause the reconstruction of the pref style sheet. GlobalStyleSheetCache::InvalidatePreferenceSheets(); PreferenceSheet::Refresh(); DispatchPrefChangedRunnableIfNeeded(); if (prefName.EqualsLiteral("nglayout.debug.paint_flashing") || prefName.EqualsLiteral("nglayout.debug.paint_flashing_chrome")) { mPaintFlashingInitialized = false; return; } } void nsPresContext::DispatchPrefChangedRunnableIfNeeded() { if (mPostedPrefChangedRunnable) { return; } nsCOMPtr runnable = NewRunnableMethod("nsPresContext::UpdateAfterPreferencesChanged", this, &nsPresContext::UpdateAfterPreferencesChanged); nsresult rv = Document()->Dispatch(TaskCategory::Other, runnable.forget()); if (NS_SUCCEEDED(rv)) { mPostedPrefChangedRunnable = true; } } void nsPresContext::UpdateAfterPreferencesChanged() { mPostedPrefChangedRunnable = false; if (!mPresShell) { return; } if (mDocument->IsInChromeDocShell()) { // FIXME(emilio): Do really all these prefs not affect chrome docs? I // suspect we should move this check somewhere else. return; } StaticPresData::Get()->InvalidateFontPrefs(); // Initialize our state from the user preferences GetUserPreferences(); // update the presShell: tell it to set the preference style rules up mPresShell->UpdatePreferenceStyles(); InvalidatePaintedLayers(); mDeviceContext->FlushFontCache(); // Preferences require rerunning selector matching because we rebuild // the pref style sheet for some preference changes. RebuildAllStyleData(mChangeHintForPrefChange, RestyleHint::RestyleSubtree()); mChangeHintForPrefChange = nsChangeHint(0); } nsresult nsPresContext::Init(nsDeviceContext* aDeviceContext) { NS_ASSERTION(!mInitialized, "attempt to reinit pres context"); NS_ENSURE_ARG(aDeviceContext); mDeviceContext = aDeviceContext; // In certain rare cases (such as changing page mode), we tear down layout // state and re-initialize a new prescontext for a document. Given that we // hang style state off the DOM, we detect that re-initialization case and // lazily drop the servo data. We don't do this eagerly during layout teardown // because that would incur an extra whole-tree traversal that's unnecessary // most of the time. // // FIXME(emilio): I'm pretty sure this doesn't happen after bug 1414999. Element* root = mDocument->GetRootElement(); if (root && root->HasServoData()) { RestyleManager::ClearServoDataFromSubtree(root); } if (mDeviceContext->SetFullZoom(mFullZoom)) { mDeviceContext->FlushFontCache(); } mCurAppUnitsPerDevPixel = mDeviceContext->AppUnitsPerDevPixel(); mEventManager = new mozilla::EventStateManager(); mAnimationEventDispatcher = new mozilla::AnimationEventDispatcher(this); mEffectCompositor = new mozilla::EffectCompositor(this); mTransitionManager = MakeUnique(this); mAnimationManager = MakeUnique(this); if (mDocument->GetDisplayDocument()) { NS_ASSERTION(mDocument->GetDisplayDocument()->GetPresContext(), "Why are we being initialized?"); mRefreshDriver = mDocument->GetDisplayDocument()->GetPresContext()->RefreshDriver(); } else { dom::Document* parent = mDocument->GetInProcessParentDocument(); // Unfortunately, sometimes |parent| here has no presshell because // printing screws up things. Assert that in other cases it does, // but whenever the shell is null just fall back on using our own // refresh driver. NS_ASSERTION( !parent || mDocument->IsStaticDocument() || parent->GetPresShell(), "How did we end up with a presshell if our parent doesn't " "have one?"); if (parent && parent->GetPresContext()) { // XXX the document can change in AttachPresShell, does this work? dom::BrowsingContext* browsingContext = mDocument->GetBrowsingContext(); if (browsingContext && !browsingContext->IsTop()) { Element* containingElement = parent->FindContentForSubDocument(mDocument); if (!containingElement->IsXULElement() || !containingElement->HasAttr(kNameSpaceID_None, nsGkAtoms::forceOwnRefreshDriver)) { mRefreshDriver = parent->GetPresContext()->RefreshDriver(); } } } if (!mRefreshDriver) { mRefreshDriver = new nsRefreshDriver(this); } } // Register callbacks so we're notified when the preferences change Preferences::RegisterPrefixCallbacks(nsPresContext::PreferenceChanged, gPrefixCallbackPrefs, this); Preferences::RegisterCallbacks(nsPresContext::PreferenceChanged, gExactCallbackPrefs, this); nsresult rv = mEventManager->Init(); NS_ENSURE_SUCCESS(rv, rv); mEventManager->SetPresContext(this); #if defined(MOZ_WIDGET_ANDROID) if (IsRootContentDocumentCrossProcess() && MOZ_LIKELY( !Preferences::HasUserValue("layout.dynamic-toolbar-max-height"))) { if (BrowserChild* browserChild = BrowserChild::GetFrom(mDocument->GetDocShell())) { mDynamicToolbarMaxHeight = browserChild->GetDynamicToolbarMaxHeight(); mDynamicToolbarHeight = mDynamicToolbarMaxHeight; } } #endif #ifdef DEBUG mInitialized = true; #endif return NS_OK; } // Note: We don't hold a reference on the shell; it has a reference to // us void nsPresContext::AttachPresShell(mozilla::PresShell* aPresShell) { MOZ_ASSERT(!mPresShell); mPresShell = aPresShell; mRestyleManager = MakeUnique(this); // Since CounterStyleManager is also the name of a method of // nsPresContext, it is necessary to prefix the class with the mozilla // namespace here. mCounterStyleManager = new mozilla::CounterStyleManager(this); dom::Document* doc = mPresShell->GetDocument(); MOZ_ASSERT(doc); // Have to update PresContext's mDocument before calling any other methods. mDocument = doc; // Initialize our state from the user preferences, now that we // have a presshell, and hence a document. GetUserPreferences(); nsIURI* docURI = doc->GetDocumentURI(); if (IsDynamic() && docURI) { if (!docURI->SchemeIs("chrome") && !docURI->SchemeIs("resource")) mImageAnimationMode = mImageAnimationModePref; else mImageAnimationMode = imgIContainer::kNormalAnimMode; } UpdateCharSet(doc->GetDocumentCharacterSet()); } void nsPresContext::RecomputeBrowsingContextDependentData() { MOZ_ASSERT(mDocument); dom::Document* doc = mDocument; // Resource documents inherit all this state from their display document. while (dom::Document* outer = doc->GetDisplayDocument()) { doc = outer; } auto* browsingContext = doc->GetBrowsingContext(); if (!browsingContext) { // This can legitimately happen for e.g. SVG images. Those just get scaled // as a result of the zoom on the embedder document so it doesn't really // matter... return; } SetFullZoom(browsingContext->FullZoom()); SetTextZoom(browsingContext->TextZoom()); mDocument->EnumerateExternalResources([](dom::Document& aSubResource) { if (nsPresContext* subResourcePc = aSubResource.GetPresContext()) { subResourcePc->RecomputeBrowsingContextDependentData(); } return CallState::Continue; }); } void nsPresContext::DetachPresShell() { // The counter style manager's destructor needs to deallocate with the // presshell arena. Disconnect it before nulling out the shell. // // XXXbholley: Given recent refactorings, it probably makes more sense to // just null our mPresShell at the bottom of this function. I'm leaving it // this way to preserve the old ordering, but I doubt anything would break. if (mCounterStyleManager) { mCounterStyleManager->Disconnect(); mCounterStyleManager = nullptr; } mPresShell = nullptr; if (mAnimationEventDispatcher) { mAnimationEventDispatcher->Disconnect(); mAnimationEventDispatcher = nullptr; } if (mEffectCompositor) { mEffectCompositor->Disconnect(); mEffectCompositor = nullptr; } if (mTransitionManager) { mTransitionManager->Disconnect(); mTransitionManager = nullptr; } if (mAnimationManager) { mAnimationManager->Disconnect(); mAnimationManager = nullptr; } if (mRestyleManager) { mRestyleManager->Disconnect(); mRestyleManager = nullptr; } if (mRefreshDriver && mRefreshDriver->GetPresContext() == this) { mRefreshDriver->Disconnect(); // Can't null out the refresh driver here. } if (IsRoot()) { nsRootPresContext* thisRoot = static_cast(this); // Have to cancel our plugin geometry timer, because the // callback for that depends on a non-null presshell. thisRoot->CancelApplyPluginGeometryTimer(); } } void nsPresContext::DocumentCharSetChanged(NotNull aCharSet) { UpdateCharSet(aCharSet); mDeviceContext->FlushFontCache(); // If a document contains one or more