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 #include "ImageDocument.h"
8 #include "mozilla/AutoRestore.h"
9 #include "mozilla/ComputedStyle.h"
10 #include "mozilla/dom/BrowserChild.h"
11 #include "mozilla/dom/Element.h"
12 #include "mozilla/dom/Event.h"
13 #include "mozilla/dom/ImageDocumentBinding.h"
14 #include "mozilla/dom/HTMLImageElement.h"
15 #include "mozilla/dom/MouseEvent.h"
16 #include "mozilla/LoadInfo.h"
17 #include "mozilla/PresShell.h"
18 #include "mozilla/StaticPrefs_browser.h"
19 #include "nsICSSDeclaration.h"
20 #include "nsObjectLoadingContent.h"
22 #include "nsIImageLoadingContent.h"
23 #include "nsGenericHTMLElement.h"
24 #include "nsDocShell.h"
25 #include "DocumentInlines.h"
26 #include "nsDOMTokenList.h"
27 #include "nsIDOMEventListener.h"
29 #include "nsGkAtoms.h"
30 #include "imgIRequest.h"
31 #include "imgIContainer.h"
32 #include "imgINotificationObserver.h"
33 #include "nsPresContext.h"
34 #include "nsIChannel.h"
35 #include "nsIContentPolicy.h"
36 #include "nsContentPolicyUtils.h"
37 #include "nsPIDOMWindow.h"
39 #include "nsURILoader.h"
40 #include "nsIDocShell.h"
41 #include "nsIContentViewer.h"
42 #include "nsThreadUtils.h"
43 #include "nsIScrollableFrame.h"
44 #include "nsContentUtils.h"
45 #include "mozilla/Preferences.h"
48 namespace mozilla::dom
{
50 class ImageListener
: public MediaDocumentStreamListener
{
52 // NS_DECL_NSIREQUESTOBSERVER
53 // We only implement OnStartRequest; OnStopRequest is
54 // implemented by MediaDocumentStreamListener
55 NS_IMETHOD
OnStartRequest(nsIRequest
* aRequest
) override
;
57 explicit ImageListener(ImageDocument
* aDocument
);
58 virtual ~ImageListener();
61 ImageListener::ImageListener(ImageDocument
* aDocument
)
62 : MediaDocumentStreamListener(aDocument
) {}
64 ImageListener::~ImageListener() = default;
67 ImageListener::OnStartRequest(nsIRequest
* request
) {
68 NS_ENSURE_TRUE(mDocument
, NS_ERROR_FAILURE
);
70 ImageDocument
* imgDoc
= static_cast<ImageDocument
*>(mDocument
.get());
71 nsCOMPtr
<nsIChannel
> channel
= do_QueryInterface(request
);
73 return NS_ERROR_FAILURE
;
76 nsCOMPtr
<nsPIDOMWindowOuter
> domWindow
= imgDoc
->GetWindow();
77 NS_ENSURE_TRUE(domWindow
, NS_ERROR_UNEXPECTED
);
79 // Do a ShouldProcess check to see whether to keep loading the image.
80 nsCOMPtr
<nsIURI
> channelURI
;
81 channel
->GetURI(getter_AddRefs(channelURI
));
83 nsAutoCString mimeType
;
84 channel
->GetContentType(mimeType
);
86 nsCOMPtr
<nsILoadInfo
> loadInfo
= channel
->LoadInfo();
87 // query the corresponding arguments for the channel loadinfo and pass
88 // it on to the temporary loadinfo used for content policy checks.
89 nsCOMPtr
<nsINode
> requestingNode
= domWindow
->GetFrameElementInternal();
90 nsCOMPtr
<nsIPrincipal
> loadingPrincipal
;
92 loadingPrincipal
= requestingNode
->NodePrincipal();
94 nsContentUtils::GetSecurityManager()->GetChannelResultPrincipal(
95 channel
, getter_AddRefs(loadingPrincipal
));
98 nsCOMPtr
<nsILoadInfo
> secCheckLoadInfo
= new net::LoadInfo(
99 loadingPrincipal
, loadInfo
->TriggeringPrincipal(), requestingNode
,
100 nsILoadInfo::SEC_ONLY_FOR_EXPLICIT_CONTENTSEC_CHECK
,
101 nsIContentPolicy::TYPE_INTERNAL_IMAGE
);
103 int16_t decision
= nsIContentPolicy::ACCEPT
;
104 nsresult rv
= NS_CheckContentProcessPolicy(
105 channelURI
, secCheckLoadInfo
, mimeType
, &decision
,
106 nsContentUtils::GetContentPolicy());
108 if (NS_FAILED(rv
) || NS_CP_REJECTED(decision
)) {
109 request
->Cancel(NS_ERROR_CONTENT_BLOCKED
);
113 if (!imgDoc
->mObservingImageLoader
) {
114 NS_ENSURE_TRUE(imgDoc
->mImageContent
, NS_ERROR_UNEXPECTED
);
115 imgDoc
->mImageContent
->AddNativeObserver(imgDoc
);
116 imgDoc
->mObservingImageLoader
= true;
117 imgDoc
->mImageContent
->LoadImageWithChannel(channel
,
118 getter_AddRefs(mNextStream
));
121 return MediaDocumentStreamListener::OnStartRequest(request
);
124 ImageDocument::ImageDocument()
130 mImageIsResized(false),
131 mShouldResize(false),
133 mObservingImageLoader(false),
134 mTitleUpdateInProgress(false),
135 mHasCustomTitle(false),
136 mIsInObjectOrEmbed(false),
137 mOriginalZoomLevel(1.0),
138 mOriginalResolution(1.0) {}
140 ImageDocument::~ImageDocument() = default;
142 NS_IMPL_CYCLE_COLLECTION_INHERITED(ImageDocument
, MediaDocument
, mImageContent
)
144 NS_IMPL_ISUPPORTS_CYCLE_COLLECTION_INHERITED(ImageDocument
, MediaDocument
,
145 imgINotificationObserver
,
148 nsresult
ImageDocument::Init(nsIPrincipal
* aPrincipal
,
149 nsIPrincipal
* aPartitionedPrincipal
) {
150 nsresult rv
= MediaDocument::Init(aPrincipal
, aPartitionedPrincipal
);
151 NS_ENSURE_SUCCESS(rv
, rv
);
153 mShouldResize
= StaticPrefs::browser_enable_automatic_image_resizing();
159 JSObject
* ImageDocument::WrapNode(JSContext
* aCx
,
160 JS::Handle
<JSObject
*> aGivenProto
) {
161 return ImageDocument_Binding::Wrap(aCx
, this, aGivenProto
);
164 nsresult
ImageDocument::StartDocumentLoad(
165 const char* aCommand
, nsIChannel
* aChannel
, nsILoadGroup
* aLoadGroup
,
166 nsISupports
* aContainer
, nsIStreamListener
** aDocListener
, bool aReset
) {
167 nsresult rv
= MediaDocument::StartDocumentLoad(
168 aCommand
, aChannel
, aLoadGroup
, aContainer
, aDocListener
, aReset
);
173 mOriginalZoomLevel
= IsSiteSpecific() ? 1.0 : GetZoomLevel();
175 mOriginalResolution
= GetResolution();
177 if (BrowsingContext
* context
= GetBrowsingContext()) {
178 mIsInObjectOrEmbed
= context
->IsEmbedderTypeObjectOrEmbed();
181 NS_ASSERTION(aDocListener
, "null aDocListener");
182 *aDocListener
= new ImageListener(this);
183 NS_ADDREF(*aDocListener
);
188 void ImageDocument::Destroy() {
189 if (RefPtr
<HTMLImageElement
> img
= std::move(mImageContent
)) {
190 // Remove our event listener from the image content.
191 img
->RemoveEventListener(u
"load"_ns
, this, false);
192 img
->RemoveEventListener(u
"click"_ns
, this, false);
194 // Break reference cycle with mImageContent, if we have one
195 if (mObservingImageLoader
) {
196 img
->RemoveNativeObserver(this);
200 MediaDocument::Destroy();
203 void ImageDocument::SetScriptGlobalObject(
204 nsIScriptGlobalObject
* aScriptGlobalObject
) {
205 // If the script global object is changing, we need to unhook our event
206 // listeners on the window.
207 nsCOMPtr
<EventTarget
> target
;
208 if (mScriptGlobalObject
&& aScriptGlobalObject
!= mScriptGlobalObject
) {
209 target
= do_QueryInterface(mScriptGlobalObject
);
210 target
->RemoveEventListener(u
"resize"_ns
, this, false);
211 target
->RemoveEventListener(u
"keypress"_ns
, this, false);
214 // Set the script global object on the superclass before doing
215 // anything that might require it....
216 MediaDocument::SetScriptGlobalObject(aScriptGlobalObject
);
218 if (aScriptGlobalObject
) {
219 if (!InitialSetupHasBeenDone()) {
220 MOZ_ASSERT(!GetRootElement(), "Where did the root element come from?");
221 // Create synthetic document
225 CreateSyntheticDocument();
226 NS_ASSERTION(NS_SUCCEEDED(rv
), "failed to create synthetic document");
228 target
= mImageContent
;
229 target
->AddEventListener(u
"load"_ns
, this, false);
230 target
->AddEventListener(u
"click"_ns
, this, false);
233 target
= do_QueryInterface(aScriptGlobalObject
);
234 target
->AddEventListener(u
"resize"_ns
, this, false);
235 target
->AddEventListener(u
"keypress"_ns
, this, false);
237 if (!InitialSetupHasBeenDone()) {
238 LinkStylesheet(u
"resource://content-accessible/ImageDocument.css"_ns
);
239 if (!nsContentUtils::IsChildOfSameType(this)) {
240 LinkStylesheet(nsLiteralString(
241 u
"resource://content-accessible/TopLevelImageDocument.css"));
248 void ImageDocument::OnPageShow(bool aPersisted
,
249 EventTarget
* aDispatchStartTarget
,
250 bool aOnlySystemGroup
) {
252 mOriginalZoomLevel
= IsSiteSpecific() ? 1.0 : GetZoomLevel();
254 mOriginalResolution
= GetResolution();
256 RefPtr
<ImageDocument
> kungFuDeathGrip(this);
257 UpdateSizeFromLayout();
259 MediaDocument::OnPageShow(aPersisted
, aDispatchStartTarget
, aOnlySystemGroup
);
262 void ImageDocument::ShrinkToFit() {
263 if (!mImageContent
) {
266 if (GetZoomLevel() != mOriginalZoomLevel
&& mImageIsResized
&&
267 !nsContentUtils::IsChildOfSameType(this)) {
268 // If we're zoomed, so that we don't maintain the invariant that
269 // mImageIsResized if and only if its displayed width/height fit in
270 // mVisibleWidth/mVisibleHeight, then we may need to switch to/from the
271 // overflowingVertical class here, because our viewport size may have
272 // changed and we don't plan to adjust the image size to compensate. Since
273 // mImageIsResized it has a "height" attribute set, and we can just get the
274 // displayed image height by getting .height on the HTMLImageElement.
276 // Hold strong ref, because Height() can run script.
277 RefPtr
<HTMLImageElement
> img
= mImageContent
;
278 uint32_t imageHeight
= img
->Height();
279 nsDOMTokenList
* classList
= img
->ClassList();
280 if (imageHeight
> mVisibleHeight
) {
281 classList
->Add(u
"overflowingVertical"_ns
, IgnoreErrors());
283 classList
->Remove(u
"overflowingVertical"_ns
, IgnoreErrors());
287 if (GetResolution() != mOriginalResolution
&& mImageIsResized
) {
288 // Don't resize if resolution has changed, e.g., through pinch-zooming on
293 // Keep image content alive while changing the attributes.
294 RefPtr
<HTMLImageElement
> image
= mImageContent
;
296 uint32_t newWidth
= std::max(1, NSToCoordFloor(GetRatio() * mImageWidth
));
297 uint32_t newHeight
= std::max(1, NSToCoordFloor(GetRatio() * mImageHeight
));
298 image
->SetWidth(newWidth
, IgnoreErrors());
299 image
->SetHeight(newHeight
, IgnoreErrors());
301 // The view might have been scrolled when zooming in, scroll back to the
302 // origin now that we're showing a shrunk-to-window version.
305 if (!mImageContent
) {
306 // ScrollImageTo flush destroyed our content.
310 SetModeClass(eShrinkToFit
);
312 mImageIsResized
= true;
314 UpdateTitleAndCharset();
317 void ImageDocument::ScrollImageTo(int32_t aX
, int32_t aY
) {
318 RefPtr
<PresShell
> presShell
= GetPresShell();
323 nsIScrollableFrame
* sf
= presShell
->GetRootScrollFrameAsScrollable();
328 float ratio
= GetRatio();
329 // Don't try to scroll image if the document is not visible (mVisibleWidth or
330 // mVisibleHeight is zero).
334 nsRect portRect
= sf
->GetScrollPortRect();
337 nsPresContext::CSSPixelsToAppUnits(aX
/ ratio
) - portRect
.width
/ 2,
338 nsPresContext::CSSPixelsToAppUnits(aY
/ ratio
) - portRect
.height
/ 2),
339 ScrollMode::Instant
);
342 void ImageDocument::RestoreImage() {
343 if (!mImageContent
) {
346 // Keep image content alive while changing the attributes.
347 RefPtr
<HTMLImageElement
> imageContent
= mImageContent
;
348 imageContent
->UnsetAttr(kNameSpaceID_None
, nsGkAtoms::width
, true);
349 imageContent
->UnsetAttr(kNameSpaceID_None
, nsGkAtoms::height
, true);
351 if (mIsInObjectOrEmbed
) {
352 SetModeClass(eIsInObjectOrEmbed
);
353 } else if (ImageIsOverflowing()) {
354 if (!ImageIsOverflowingVertically()) {
355 SetModeClass(eOverflowingHorizontalOnly
);
357 SetModeClass(eOverflowingVertical
);
363 mImageIsResized
= false;
365 UpdateTitleAndCharset();
368 void ImageDocument::NotifyPossibleTitleChange(bool aBoundTitleElement
) {
369 if (!mHasCustomTitle
&& !mTitleUpdateInProgress
) {
370 mHasCustomTitle
= true;
373 Document::NotifyPossibleTitleChange(aBoundTitleElement
);
376 void ImageDocument::Notify(imgIRequest
* aRequest
, int32_t aType
,
377 const nsIntRect
* aData
) {
378 if (aType
== imgINotificationObserver::SIZE_AVAILABLE
) {
379 nsCOMPtr
<imgIContainer
> image
;
380 aRequest
->GetImage(getter_AddRefs(image
));
381 return OnSizeAvailable(aRequest
, image
);
384 // Run this using a script runner because HAS_TRANSPARENCY notifications can
385 // come during painting and this will trigger invalidation.
386 if (aType
== imgINotificationObserver::HAS_TRANSPARENCY
) {
387 nsCOMPtr
<nsIRunnable
> runnable
=
388 NewRunnableMethod("dom::ImageDocument::OnHasTransparency", this,
389 &ImageDocument::OnHasTransparency
);
390 nsContentUtils::AddScriptRunner(runnable
);
393 if (aType
== imgINotificationObserver::LOAD_COMPLETE
) {
395 aRequest
->GetImageStatus(&reqStatus
);
397 reqStatus
& imgIRequest::STATUS_ERROR
? NS_ERROR_FAILURE
: NS_OK
;
398 return OnLoadComplete(aRequest
, status
);
402 void ImageDocument::OnHasTransparency() {
403 if (!mImageContent
|| nsContentUtils::IsChildOfSameType(this)) {
407 nsDOMTokenList
* classList
= mImageContent
->ClassList();
408 classList
->Add(u
"transparent"_ns
, IgnoreErrors());
411 void ImageDocument::SetModeClass(eModeClasses mode
) {
412 nsDOMTokenList
* classList
= mImageContent
->ClassList();
414 if (mode
== eShrinkToFit
) {
415 classList
->Add(u
"shrinkToFit"_ns
, IgnoreErrors());
417 classList
->Remove(u
"shrinkToFit"_ns
, IgnoreErrors());
420 if (mode
== eOverflowingVertical
) {
421 classList
->Add(u
"overflowingVertical"_ns
, IgnoreErrors());
423 classList
->Remove(u
"overflowingVertical"_ns
, IgnoreErrors());
426 if (mode
== eOverflowingHorizontalOnly
) {
427 classList
->Add(u
"overflowingHorizontalOnly"_ns
, IgnoreErrors());
429 classList
->Remove(u
"overflowingHorizontalOnly"_ns
, IgnoreErrors());
432 if (mode
== eIsInObjectOrEmbed
) {
433 classList
->Add(u
"isInObjectOrEmbed"_ns
, IgnoreErrors());
437 void ImageDocument::OnSizeAvailable(imgIRequest
* aRequest
,
438 imgIContainer
* aImage
) {
439 int32_t oldWidth
= mImageWidth
;
440 int32_t oldHeight
= mImageHeight
;
442 // Styles have not yet been applied, so we don't know the final size. For now,
443 // default to the image's intrinsic size.
444 aImage
->GetWidth(&mImageWidth
);
445 aImage
->GetHeight(&mImageHeight
);
447 // Multipart images send size available for each part; ignore them if it
448 // doesn't change our size. (We may not even support changing size in
449 // multipart images in the future.)
450 if (oldWidth
== mImageWidth
&& oldHeight
== mImageHeight
) {
454 nsCOMPtr
<nsIRunnable
> runnable
=
455 NewRunnableMethod("dom::ImageDocument::DefaultCheckOverflowing", this,
456 &ImageDocument::DefaultCheckOverflowing
);
457 nsContentUtils::AddScriptRunner(runnable
);
458 UpdateTitleAndCharset();
461 void ImageDocument::OnLoadComplete(imgIRequest
* aRequest
, nsresult aStatus
) {
462 UpdateTitleAndCharset();
464 // mImageContent can be null if the document is already destroyed
465 if (NS_FAILED(aStatus
) && mImageContent
) {
467 mDocumentURI
->GetSpec(src
);
468 AutoTArray
<nsString
, 1> formatString
;
469 CopyUTF8toUTF16(src
, *formatString
.AppendElement());
470 nsAutoString errorMsg
;
471 FormatStringFromName("InvalidImage", formatString
, errorMsg
);
473 mImageContent
->SetAttr(kNameSpaceID_None
, nsGkAtoms::alt
, errorMsg
, false);
476 MaybeSendResultToEmbedder(aStatus
);
480 ImageDocument::HandleEvent(Event
* aEvent
) {
481 nsAutoString eventType
;
482 aEvent
->GetType(eventType
);
483 if (eventType
.EqualsLiteral("resize")) {
484 CheckOverflowing(false);
486 } else if (eventType
.EqualsLiteral("click") &&
487 StaticPrefs::browser_enable_click_image_resizing() &&
488 !mIsInObjectOrEmbed
) {
490 mShouldResize
= true;
491 if (mImageIsResized
) {
492 int32_t x
= 0, y
= 0;
493 MouseEvent
* event
= aEvent
->AsMouseEvent();
495 RefPtr
<HTMLImageElement
> img
= mImageContent
;
496 x
= event
->ClientX() - img
->OffsetLeft();
497 y
= event
->ClientY() - img
->OffsetTop();
499 mShouldResize
= false;
501 FlushPendingNotifications(FlushType::Layout
);
503 } else if (ImageIsOverflowing()) {
506 } else if (eventType
.EqualsLiteral("load")) {
507 UpdateSizeFromLayout();
513 void ImageDocument::UpdateSizeFromLayout() {
514 // Pull an updated size from the content frame to account for any size
515 // change due to CSS properties like |image-orientation|.
516 if (!mImageContent
) {
520 // Need strong ref, because GetPrimaryFrame can run script.
521 RefPtr
<HTMLImageElement
> imageContent
= mImageContent
;
522 nsIFrame
* contentFrame
= imageContent
->GetPrimaryFrame(FlushType::Frames
);
527 nsIntSize
oldSize(mImageWidth
, mImageHeight
);
528 IntrinsicSize newSize
= contentFrame
->GetIntrinsicSize();
531 mImageWidth
= nsPresContext::AppUnitsToFloatCSSPixels(*newSize
.width
);
533 if (newSize
.height
) {
534 mImageHeight
= nsPresContext::AppUnitsToFloatCSSPixels(*newSize
.height
);
537 // Ensure that our information about overflow is up-to-date if needed.
538 if (mImageWidth
!= oldSize
.width
|| mImageHeight
!= oldSize
.height
) {
539 CheckOverflowing(false);
543 void ImageDocument::UpdateRemoteStyle(StyleImageRendering aImageRendering
) {
544 if (!mImageContent
) {
548 // Using ScriptRunner to avoid doing DOM mutation at an unexpected time.
549 if (!nsContentUtils::IsSafeToRunScript()) {
550 return nsContentUtils::AddScriptRunner(
551 NewRunnableMethod
<StyleImageRendering
>(
552 "UpdateRemoteStyle", this, &ImageDocument::UpdateRemoteStyle
,
556 nsCOMPtr
<nsICSSDeclaration
> style
= mImageContent
->Style();
557 switch (aImageRendering
) {
558 case StyleImageRendering::Auto
:
559 case StyleImageRendering::Smooth
:
560 case StyleImageRendering::Optimizequality
:
561 style
->SetProperty("image-rendering"_ns
, "auto"_ns
, ""_ns
,
564 case StyleImageRendering::Optimizespeed
:
565 case StyleImageRendering::Pixelated
:
566 style
->SetProperty("image-rendering"_ns
, "pixelated"_ns
, ""_ns
,
569 case StyleImageRendering::CrispEdges
:
570 style
->SetProperty("image-rendering"_ns
, "crisp-edges"_ns
, ""_ns
,
576 nsresult
ImageDocument::CreateSyntheticDocument() {
577 // Synthesize an html document that refers to the image
578 nsresult rv
= MediaDocument::CreateSyntheticDocument();
579 NS_ENSURE_SUCCESS(rv
, rv
);
581 // Add the image element
582 RefPtr
<Element
> body
= GetBodyElement();
584 NS_WARNING("no body on image document!");
585 return NS_ERROR_FAILURE
;
588 RefPtr
<mozilla::dom::NodeInfo
> nodeInfo
;
589 nodeInfo
= mNodeInfoManager
->GetNodeInfo(
590 nsGkAtoms::img
, nullptr, kNameSpaceID_XHTML
, nsINode::ELEMENT_NODE
);
592 RefPtr
<Element
> image
= NS_NewHTMLImageElement(nodeInfo
.forget());
593 mImageContent
= HTMLImageElement::FromNodeOrNull(image
);
594 if (!mImageContent
) {
595 return NS_ERROR_OUT_OF_MEMORY
;
599 mDocumentURI
->GetSpec(src
);
601 NS_ConvertUTF8toUTF16
srcString(src
);
602 // Make sure not to start the image load from here...
603 mImageContent
->SetLoadingEnabled(false);
604 mImageContent
->SetAttr(kNameSpaceID_None
, nsGkAtoms::src
, srcString
, false);
605 mImageContent
->SetAttr(kNameSpaceID_None
, nsGkAtoms::alt
, srcString
, false);
607 if (mIsInObjectOrEmbed
) {
608 SetModeClass(eIsInObjectOrEmbed
);
611 body
->AppendChildTo(mImageContent
, false, IgnoreErrors());
612 mImageContent
->SetLoadingEnabled(true);
617 void ImageDocument::DefaultCheckOverflowing() {
618 CheckOverflowing(StaticPrefs::browser_enable_automatic_image_resizing());
621 nsresult
ImageDocument::CheckOverflowing(bool changeState
) {
622 const bool imageWasOverflowing
= ImageIsOverflowing();
623 const bool imageWasOverflowingVertically
= ImageIsOverflowingVertically();
626 nsPresContext
* context
= GetPresContext();
631 nsRect visibleArea
= context
->GetVisibleArea();
633 mVisibleWidth
= nsPresContext::AppUnitsToFloatCSSPixels(visibleArea
.width
);
635 nsPresContext::AppUnitsToFloatCSSPixels(visibleArea
.height
);
638 const bool windowBecameBigEnough
=
639 imageWasOverflowing
&& !ImageIsOverflowing();
640 const bool verticalOverflowChanged
=
641 imageWasOverflowingVertically
!= ImageIsOverflowingVertically();
643 if (changeState
|| mShouldResize
|| mFirstResize
|| windowBecameBigEnough
||
644 verticalOverflowChanged
) {
645 if (mIsInObjectOrEmbed
) {
646 SetModeClass(eIsInObjectOrEmbed
);
647 } else if (ImageIsOverflowing() && (changeState
|| mShouldResize
)) {
649 } else if (mImageIsResized
|| mFirstResize
|| windowBecameBigEnough
) {
651 } else if (!mImageIsResized
&& verticalOverflowChanged
) {
652 if (ImageIsOverflowingVertically()) {
653 SetModeClass(eOverflowingVertical
);
655 SetModeClass(eOverflowingHorizontalOnly
);
659 mFirstResize
= false;
663 void ImageDocument::UpdateTitleAndCharset() {
664 if (mHasCustomTitle
) {
668 AutoRestore
<bool> restore(mTitleUpdateInProgress
);
669 mTitleUpdateInProgress
= true;
671 nsAutoCString typeStr
;
672 nsCOMPtr
<imgIRequest
> imageRequest
;
674 mImageContent
->GetRequest(nsIImageLoadingContent::CURRENT_REQUEST
,
675 getter_AddRefs(imageRequest
));
680 imageRequest
->GetMimeType(getter_Copies(mimeType
));
681 ToUpperCase(mimeType
);
682 nsCString::const_iterator start
, end
;
683 mimeType
.BeginReading(start
);
684 mimeType
.EndReading(end
);
685 nsCString::const_iterator iter
= end
;
686 if (FindInReadable("IMAGE/"_ns
, start
, iter
) && iter
!= end
) {
687 // strip out "X-" if any
690 if (iter
!= end
&& *iter
== '-') {
693 // looks like "IMAGE/X-" is the type?? Bail out of here.
694 mimeType
.BeginReading(iter
);
700 typeStr
= Substring(iter
, end
);
707 if (mImageIsResized
) {
708 AutoTArray
<nsString
, 1> formatString
;
709 formatString
.AppendElement()->AppendInt(NSToCoordFloor(GetRatio() * 100));
711 FormatStringFromName("ScaledImage", formatString
, status
);
714 static const char* const formatNames
[4] = {
715 "ImageTitleWithNeitherDimensionsNorFile",
716 "ImageTitleWithoutDimensions",
717 "ImageTitleWithDimensions2",
718 "ImageTitleWithDimensions2AndFile",
721 MediaDocument::UpdateTitleAndCharset(typeStr
, mChannel
, formatNames
,
722 mImageWidth
, mImageHeight
, status
);
725 bool ImageDocument::IsSiteSpecific() {
726 return !ShouldResistFingerprinting(RFPTarget::SiteSpecificZoom
) &&
727 StaticPrefs::browser_zoom_siteSpecific();
730 void ImageDocument::ResetZoomLevel() {
731 if (nsContentUtils::IsChildOfSameType(this)) {
735 if (RefPtr
<BrowsingContext
> bc
= GetBrowsingContext()) {
736 // Resetting the zoom level on a discarded browsing context has no effect.
737 Unused
<< bc
->SetFullZoom(mOriginalZoomLevel
);
741 float ImageDocument::GetZoomLevel() {
742 if (BrowsingContext
* bc
= GetBrowsingContext()) {
743 return bc
->FullZoom();
745 return mOriginalZoomLevel
;
748 void ImageDocument::CheckFullZoom() {
749 nsDOMTokenList
* classList
=
750 mImageContent
? mImageContent
->ClassList() : nullptr;
756 classList
->Toggle(u
"fullZoomOut"_ns
,
757 dom::Optional
<bool>(GetZoomLevel() > mOriginalZoomLevel
),
759 classList
->Toggle(u
"fullZoomIn"_ns
,
760 dom::Optional
<bool>(GetZoomLevel() < mOriginalZoomLevel
),
764 float ImageDocument::GetResolution() {
765 if (PresShell
* presShell
= GetPresShell()) {
766 return presShell
->GetResolution();
768 return mOriginalResolution
;
771 void ImageDocument::MaybeSendResultToEmbedder(nsresult aResult
) {
772 if (!mIsInObjectOrEmbed
) {
776 BrowsingContext
* context
= GetBrowsingContext();
782 if (context
->GetParent() && context
->GetParent()->IsInProcess()) {
783 if (Element
* embedder
= context
->GetEmbedderElement()) {
784 if (nsCOMPtr
<nsIObjectLoadingContent
> objectLoadingContent
=
785 do_QueryInterface(embedder
)) {
786 NS_DispatchToMainThread(NS_NewRunnableFunction(
787 "nsObjectLoadingContent::SubdocumentImageLoadComplete",
788 [objectLoadingContent
, aResult
]() {
789 static_cast<nsObjectLoadingContent
*>(objectLoadingContent
.get())
790 ->SubdocumentImageLoadComplete(aResult
);
797 if (BrowserChild
* browserChild
=
798 BrowserChild::GetFrom(context
->GetDocShell())) {
799 browserChild
->SendImageLoadComplete(aResult
);
802 } // namespace mozilla::dom
804 nsresult
NS_NewImageDocument(mozilla::dom::Document
** aResult
,
805 nsIPrincipal
* aPrincipal
,
806 nsIPrincipal
* aPartitionedPrincipal
) {
807 auto* doc
= new mozilla::dom::ImageDocument();
810 nsresult rv
= doc
->Init(aPrincipal
, aPartitionedPrincipal
);