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 "ImageBlocker.h"
27 #include "nsDOMTokenList.h"
28 #include "nsIDOMEventListener.h"
30 #include "nsGkAtoms.h"
31 #include "imgIRequest.h"
32 #include "imgIContainer.h"
33 #include "imgINotificationObserver.h"
34 #include "nsPresContext.h"
35 #include "nsIChannel.h"
36 #include "nsIContentPolicy.h"
37 #include "nsContentPolicyUtils.h"
38 #include "nsPIDOMWindow.h"
40 #include "nsURILoader.h"
41 #include "nsIDocShell.h"
42 #include "nsIDocumentViewer.h"
43 #include "nsThreadUtils.h"
44 #include "nsIScrollableFrame.h"
45 #include "nsContentUtils.h"
46 #include "mozilla/Preferences.h"
49 namespace mozilla::dom
{
51 class ImageListener
: public MediaDocumentStreamListener
{
53 // NS_DECL_NSIREQUESTOBSERVER
54 // We only implement OnStartRequest; OnStopRequest is
55 // implemented by MediaDocumentStreamListener
56 NS_IMETHOD
OnStartRequest(nsIRequest
* aRequest
) override
;
58 explicit ImageListener(ImageDocument
* aDocument
);
59 virtual ~ImageListener();
62 ImageListener::ImageListener(ImageDocument
* aDocument
)
63 : MediaDocumentStreamListener(aDocument
) {}
65 ImageListener::~ImageListener() = default;
68 ImageListener::OnStartRequest(nsIRequest
* request
) {
69 NS_ENSURE_TRUE(mDocument
, NS_ERROR_FAILURE
);
71 ImageDocument
* imgDoc
= static_cast<ImageDocument
*>(mDocument
.get());
72 nsCOMPtr
<nsIChannel
> channel
= do_QueryInterface(request
);
74 return NS_ERROR_FAILURE
;
77 nsCOMPtr
<nsPIDOMWindowOuter
> domWindow
= imgDoc
->GetWindow();
78 NS_ENSURE_TRUE(domWindow
, NS_ERROR_UNEXPECTED
);
80 // This is an image being loaded as a document, so it's not going to be
81 // detected by the ImageBlocker. However we don't want to call
82 // NS_CheckContentLoadPolicy (with an TYPE_INTERNAL_IMAGE) here, as it would
83 // e.g. make this image load be detectable by CSP.
84 nsCOMPtr
<nsIURI
> channelURI
;
85 channel
->GetURI(getter_AddRefs(channelURI
));
86 if (image::ImageBlocker::ShouldBlock(channelURI
)) {
87 request
->Cancel(NS_ERROR_CONTENT_BLOCKED
);
91 if (!imgDoc
->mObservingImageLoader
) {
92 NS_ENSURE_TRUE(imgDoc
->mImageContent
, NS_ERROR_UNEXPECTED
);
93 imgDoc
->mImageContent
->AddNativeObserver(imgDoc
);
94 imgDoc
->mObservingImageLoader
= true;
95 imgDoc
->mImageContent
->LoadImageWithChannel(channel
,
96 getter_AddRefs(mNextStream
));
99 return MediaDocumentStreamListener::OnStartRequest(request
);
102 ImageDocument::ImageDocument()
103 : mVisibleWidth(0.0),
107 mImageIsResized(false),
108 mShouldResize(false),
110 mObservingImageLoader(false),
111 mTitleUpdateInProgress(false),
112 mHasCustomTitle(false),
113 mIsInObjectOrEmbed(false),
114 mOriginalZoomLevel(1.0),
115 mOriginalResolution(1.0) {}
117 ImageDocument::~ImageDocument() = default;
119 NS_IMPL_CYCLE_COLLECTION_INHERITED(ImageDocument
, MediaDocument
, mImageContent
)
121 NS_IMPL_ISUPPORTS_CYCLE_COLLECTION_INHERITED(ImageDocument
, MediaDocument
,
122 imgINotificationObserver
,
125 nsresult
ImageDocument::Init(nsIPrincipal
* aPrincipal
,
126 nsIPrincipal
* aPartitionedPrincipal
) {
127 nsresult rv
= MediaDocument::Init(aPrincipal
, aPartitionedPrincipal
);
128 NS_ENSURE_SUCCESS(rv
, rv
);
130 mShouldResize
= StaticPrefs::browser_enable_automatic_image_resizing();
136 JSObject
* ImageDocument::WrapNode(JSContext
* aCx
,
137 JS::Handle
<JSObject
*> aGivenProto
) {
138 return ImageDocument_Binding::Wrap(aCx
, this, aGivenProto
);
141 nsresult
ImageDocument::StartDocumentLoad(
142 const char* aCommand
, nsIChannel
* aChannel
, nsILoadGroup
* aLoadGroup
,
143 nsISupports
* aContainer
, nsIStreamListener
** aDocListener
, bool aReset
) {
144 nsresult rv
= MediaDocument::StartDocumentLoad(
145 aCommand
, aChannel
, aLoadGroup
, aContainer
, aDocListener
, aReset
);
150 mOriginalZoomLevel
= IsSiteSpecific() ? 1.0 : GetZoomLevel();
152 mOriginalResolution
= GetResolution();
154 if (BrowsingContext
* context
= GetBrowsingContext()) {
155 mIsInObjectOrEmbed
= context
->IsEmbedderTypeObjectOrEmbed();
158 NS_ASSERTION(aDocListener
, "null aDocListener");
159 *aDocListener
= new ImageListener(this);
160 NS_ADDREF(*aDocListener
);
165 void ImageDocument::Destroy() {
166 if (RefPtr
<HTMLImageElement
> img
= std::move(mImageContent
)) {
167 // Remove our event listener from the image content.
168 img
->RemoveEventListener(u
"load"_ns
, this, false);
169 img
->RemoveEventListener(u
"click"_ns
, this, false);
171 // Break reference cycle with mImageContent, if we have one
172 if (mObservingImageLoader
) {
173 img
->RemoveNativeObserver(this);
177 MediaDocument::Destroy();
180 void ImageDocument::SetScriptGlobalObject(
181 nsIScriptGlobalObject
* aScriptGlobalObject
) {
182 // If the script global object is changing, we need to unhook our event
183 // listeners on the window.
184 nsCOMPtr
<EventTarget
> target
;
185 if (mScriptGlobalObject
&& aScriptGlobalObject
!= mScriptGlobalObject
) {
186 target
= do_QueryInterface(mScriptGlobalObject
);
187 target
->RemoveEventListener(u
"resize"_ns
, this, false);
188 target
->RemoveEventListener(u
"keypress"_ns
, this, false);
191 // Set the script global object on the superclass before doing
192 // anything that might require it....
193 MediaDocument::SetScriptGlobalObject(aScriptGlobalObject
);
195 if (aScriptGlobalObject
) {
196 if (!InitialSetupHasBeenDone()) {
197 MOZ_ASSERT(!GetRootElement(), "Where did the root element come from?");
198 // Create synthetic document
202 CreateSyntheticDocument();
203 NS_ASSERTION(NS_SUCCEEDED(rv
), "failed to create synthetic document");
205 target
= mImageContent
;
206 target
->AddEventListener(u
"load"_ns
, this, false);
207 target
->AddEventListener(u
"click"_ns
, this, false);
210 target
= do_QueryInterface(aScriptGlobalObject
);
211 target
->AddEventListener(u
"resize"_ns
, this, false);
212 target
->AddEventListener(u
"keypress"_ns
, this, false);
214 if (!InitialSetupHasBeenDone()) {
215 LinkStylesheet(u
"resource://content-accessible/ImageDocument.css"_ns
);
216 if (!nsContentUtils::IsChildOfSameType(this)) {
217 LinkStylesheet(nsLiteralString(
218 u
"resource://content-accessible/TopLevelImageDocument.css"));
225 void ImageDocument::OnPageShow(bool aPersisted
,
226 EventTarget
* aDispatchStartTarget
,
227 bool aOnlySystemGroup
) {
229 mOriginalZoomLevel
= IsSiteSpecific() ? 1.0 : GetZoomLevel();
231 mOriginalResolution
= GetResolution();
233 RefPtr
<ImageDocument
> kungFuDeathGrip(this);
234 UpdateSizeFromLayout();
236 MediaDocument::OnPageShow(aPersisted
, aDispatchStartTarget
, aOnlySystemGroup
);
239 void ImageDocument::ShrinkToFit() {
240 if (!mImageContent
) {
243 if (GetZoomLevel() != mOriginalZoomLevel
&& mImageIsResized
&&
244 !nsContentUtils::IsChildOfSameType(this)) {
245 // If we're zoomed, so that we don't maintain the invariant that
246 // mImageIsResized if and only if its displayed width/height fit in
247 // mVisibleWidth/mVisibleHeight, then we may need to switch to/from the
248 // overflowingVertical class here, because our viewport size may have
249 // changed and we don't plan to adjust the image size to compensate. Since
250 // mImageIsResized it has a "height" attribute set, and we can just get the
251 // displayed image height by getting .height on the HTMLImageElement.
253 // Hold strong ref, because Height() can run script.
254 RefPtr
<HTMLImageElement
> img
= mImageContent
;
255 uint32_t imageHeight
= img
->Height();
256 nsDOMTokenList
* classList
= img
->ClassList();
257 if (imageHeight
> mVisibleHeight
) {
258 classList
->Add(u
"overflowingVertical"_ns
, IgnoreErrors());
260 classList
->Remove(u
"overflowingVertical"_ns
, IgnoreErrors());
264 if (GetResolution() != mOriginalResolution
&& mImageIsResized
) {
265 // Don't resize if resolution has changed, e.g., through pinch-zooming on
270 // Keep image content alive while changing the attributes.
271 RefPtr
<HTMLImageElement
> image
= mImageContent
;
273 uint32_t newWidth
= std::max(1, NSToCoordFloor(GetRatio() * mImageWidth
));
274 uint32_t newHeight
= std::max(1, NSToCoordFloor(GetRatio() * mImageHeight
));
275 image
->SetWidth(newWidth
, IgnoreErrors());
276 image
->SetHeight(newHeight
, IgnoreErrors());
278 // The view might have been scrolled when zooming in, scroll back to the
279 // origin now that we're showing a shrunk-to-window version.
282 if (!mImageContent
) {
283 // ScrollImageTo flush destroyed our content.
287 SetModeClass(eShrinkToFit
);
289 mImageIsResized
= true;
291 UpdateTitleAndCharset();
294 void ImageDocument::ScrollImageTo(int32_t aX
, int32_t aY
) {
295 RefPtr
<PresShell
> presShell
= GetPresShell();
300 nsIScrollableFrame
* sf
= presShell
->GetRootScrollFrameAsScrollable();
305 float ratio
= GetRatio();
306 // Don't try to scroll image if the document is not visible (mVisibleWidth or
307 // mVisibleHeight is zero).
311 nsRect portRect
= sf
->GetScrollPortRect();
314 nsPresContext::CSSPixelsToAppUnits(aX
/ ratio
) - portRect
.width
/ 2,
315 nsPresContext::CSSPixelsToAppUnits(aY
/ ratio
) - portRect
.height
/ 2),
316 ScrollMode::Instant
);
319 void ImageDocument::RestoreImage() {
320 if (!mImageContent
) {
323 // Keep image content alive while changing the attributes.
324 RefPtr
<HTMLImageElement
> imageContent
= mImageContent
;
325 imageContent
->UnsetAttr(kNameSpaceID_None
, nsGkAtoms::width
, true);
326 imageContent
->UnsetAttr(kNameSpaceID_None
, nsGkAtoms::height
, true);
328 if (mIsInObjectOrEmbed
) {
329 SetModeClass(eIsInObjectOrEmbed
);
330 } else if (ImageIsOverflowing()) {
331 if (!ImageIsOverflowingVertically()) {
332 SetModeClass(eOverflowingHorizontalOnly
);
334 SetModeClass(eOverflowingVertical
);
340 mImageIsResized
= false;
342 UpdateTitleAndCharset();
345 void ImageDocument::NotifyPossibleTitleChange(bool aBoundTitleElement
) {
346 if (!mHasCustomTitle
&& !mTitleUpdateInProgress
) {
347 mHasCustomTitle
= true;
350 Document::NotifyPossibleTitleChange(aBoundTitleElement
);
353 void ImageDocument::Notify(imgIRequest
* aRequest
, int32_t aType
,
354 const nsIntRect
* aData
) {
355 if (aType
== imgINotificationObserver::SIZE_AVAILABLE
) {
356 nsCOMPtr
<imgIContainer
> image
;
357 aRequest
->GetImage(getter_AddRefs(image
));
358 return OnSizeAvailable(aRequest
, image
);
361 // Run this using a script runner because HAS_TRANSPARENCY notifications can
362 // come during painting and this will trigger invalidation.
363 if (aType
== imgINotificationObserver::HAS_TRANSPARENCY
) {
364 nsCOMPtr
<nsIRunnable
> runnable
=
365 NewRunnableMethod("dom::ImageDocument::OnHasTransparency", this,
366 &ImageDocument::OnHasTransparency
);
367 nsContentUtils::AddScriptRunner(runnable
);
370 if (aType
== imgINotificationObserver::LOAD_COMPLETE
) {
372 aRequest
->GetImageStatus(&reqStatus
);
374 reqStatus
& imgIRequest::STATUS_ERROR
? NS_ERROR_FAILURE
: NS_OK
;
375 return OnLoadComplete(aRequest
, status
);
379 void ImageDocument::OnHasTransparency() {
380 if (!mImageContent
|| nsContentUtils::IsChildOfSameType(this)) {
384 nsDOMTokenList
* classList
= mImageContent
->ClassList();
385 classList
->Add(u
"transparent"_ns
, IgnoreErrors());
388 void ImageDocument::SetModeClass(eModeClasses mode
) {
389 nsDOMTokenList
* classList
= mImageContent
->ClassList();
391 if (mode
== eShrinkToFit
) {
392 classList
->Add(u
"shrinkToFit"_ns
, IgnoreErrors());
394 classList
->Remove(u
"shrinkToFit"_ns
, IgnoreErrors());
397 if (mode
== eOverflowingVertical
) {
398 classList
->Add(u
"overflowingVertical"_ns
, IgnoreErrors());
400 classList
->Remove(u
"overflowingVertical"_ns
, IgnoreErrors());
403 if (mode
== eOverflowingHorizontalOnly
) {
404 classList
->Add(u
"overflowingHorizontalOnly"_ns
, IgnoreErrors());
406 classList
->Remove(u
"overflowingHorizontalOnly"_ns
, IgnoreErrors());
409 if (mode
== eIsInObjectOrEmbed
) {
410 classList
->Add(u
"isInObjectOrEmbed"_ns
, IgnoreErrors());
414 void ImageDocument::OnSizeAvailable(imgIRequest
* aRequest
,
415 imgIContainer
* aImage
) {
416 int32_t oldWidth
= mImageWidth
;
417 int32_t oldHeight
= mImageHeight
;
419 // Styles have not yet been applied, so we don't know the final size. For now,
420 // default to the image's intrinsic size.
421 aImage
->GetWidth(&mImageWidth
);
422 aImage
->GetHeight(&mImageHeight
);
424 // Multipart images send size available for each part; ignore them if it
425 // doesn't change our size. (We may not even support changing size in
426 // multipart images in the future.)
427 if (oldWidth
== mImageWidth
&& oldHeight
== mImageHeight
) {
431 nsCOMPtr
<nsIRunnable
> runnable
=
432 NewRunnableMethod("dom::ImageDocument::DefaultCheckOverflowing", this,
433 &ImageDocument::DefaultCheckOverflowing
);
434 nsContentUtils::AddScriptRunner(runnable
);
435 UpdateTitleAndCharset();
438 void ImageDocument::OnLoadComplete(imgIRequest
* aRequest
, nsresult aStatus
) {
439 UpdateTitleAndCharset();
441 // mImageContent can be null if the document is already destroyed
442 if (NS_FAILED(aStatus
) && mImageContent
) {
444 mDocumentURI
->GetSpec(src
);
445 AutoTArray
<nsString
, 1> formatString
;
446 CopyUTF8toUTF16(src
, *formatString
.AppendElement());
447 nsAutoString errorMsg
;
448 FormatStringFromName("InvalidImage", formatString
, errorMsg
);
450 mImageContent
->SetAttr(kNameSpaceID_None
, nsGkAtoms::alt
, errorMsg
, false);
453 MaybeSendResultToEmbedder(aStatus
);
457 ImageDocument::HandleEvent(Event
* aEvent
) {
458 nsAutoString eventType
;
459 aEvent
->GetType(eventType
);
460 if (eventType
.EqualsLiteral("resize")) {
461 CheckOverflowing(false);
463 } else if (eventType
.EqualsLiteral("click") &&
464 StaticPrefs::browser_enable_click_image_resizing() &&
465 !mIsInObjectOrEmbed
) {
467 mShouldResize
= true;
468 if (mImageIsResized
) {
469 int32_t x
= 0, y
= 0;
470 MouseEvent
* event
= aEvent
->AsMouseEvent();
472 RefPtr
<HTMLImageElement
> img
= mImageContent
;
473 x
= event
->ClientX() - img
->OffsetLeft();
474 y
= event
->ClientY() - img
->OffsetTop();
476 mShouldResize
= false;
478 FlushPendingNotifications(FlushType::Layout
);
480 } else if (ImageIsOverflowing()) {
483 } else if (eventType
.EqualsLiteral("load")) {
484 UpdateSizeFromLayout();
490 void ImageDocument::UpdateSizeFromLayout() {
491 // Pull an updated size from the content frame to account for any size
492 // change due to CSS properties like |image-orientation|.
493 if (!mImageContent
) {
497 // Need strong ref, because GetPrimaryFrame can run script.
498 RefPtr
<HTMLImageElement
> imageContent
= mImageContent
;
499 nsIFrame
* contentFrame
= imageContent
->GetPrimaryFrame(FlushType::Frames
);
504 nsIntSize
oldSize(mImageWidth
, mImageHeight
);
505 IntrinsicSize newSize
= contentFrame
->GetIntrinsicSize();
508 mImageWidth
= nsPresContext::AppUnitsToFloatCSSPixels(*newSize
.width
);
510 if (newSize
.height
) {
511 mImageHeight
= nsPresContext::AppUnitsToFloatCSSPixels(*newSize
.height
);
514 // Ensure that our information about overflow is up-to-date if needed.
515 if (mImageWidth
!= oldSize
.width
|| mImageHeight
!= oldSize
.height
) {
516 CheckOverflowing(false);
520 void ImageDocument::UpdateRemoteStyle(StyleImageRendering aImageRendering
) {
521 if (!mImageContent
) {
525 // Using ScriptRunner to avoid doing DOM mutation at an unexpected time.
526 if (!nsContentUtils::IsSafeToRunScript()) {
527 return nsContentUtils::AddScriptRunner(
528 NewRunnableMethod
<StyleImageRendering
>(
529 "UpdateRemoteStyle", this, &ImageDocument::UpdateRemoteStyle
,
533 nsCOMPtr
<nsICSSDeclaration
> style
= mImageContent
->Style();
534 switch (aImageRendering
) {
535 case StyleImageRendering::Auto
:
536 case StyleImageRendering::Smooth
:
537 case StyleImageRendering::Optimizequality
:
538 style
->SetProperty("image-rendering"_ns
, "auto"_ns
, ""_ns
,
541 case StyleImageRendering::Optimizespeed
:
542 case StyleImageRendering::Pixelated
:
543 style
->SetProperty("image-rendering"_ns
, "pixelated"_ns
, ""_ns
,
546 case StyleImageRendering::CrispEdges
:
547 style
->SetProperty("image-rendering"_ns
, "crisp-edges"_ns
, ""_ns
,
553 nsresult
ImageDocument::CreateSyntheticDocument() {
554 // Synthesize an html document that refers to the image
555 nsresult rv
= MediaDocument::CreateSyntheticDocument();
556 NS_ENSURE_SUCCESS(rv
, rv
);
558 // Add the image element
559 RefPtr
<Element
> body
= GetBodyElement();
561 NS_WARNING("no body on image document!");
562 return NS_ERROR_FAILURE
;
565 RefPtr
<mozilla::dom::NodeInfo
> nodeInfo
;
566 nodeInfo
= mNodeInfoManager
->GetNodeInfo(
567 nsGkAtoms::img
, nullptr, kNameSpaceID_XHTML
, nsINode::ELEMENT_NODE
);
569 RefPtr
<Element
> image
= NS_NewHTMLImageElement(nodeInfo
.forget());
570 mImageContent
= HTMLImageElement::FromNodeOrNull(image
);
571 if (!mImageContent
) {
572 return NS_ERROR_OUT_OF_MEMORY
;
576 mDocumentURI
->GetSpec(src
);
578 NS_ConvertUTF8toUTF16
srcString(src
);
579 // Make sure not to start the image load from here...
580 mImageContent
->SetLoadingEnabled(false);
581 mImageContent
->SetAttr(kNameSpaceID_None
, nsGkAtoms::src
, srcString
, false);
582 mImageContent
->SetAttr(kNameSpaceID_None
, nsGkAtoms::alt
, srcString
, false);
584 if (mIsInObjectOrEmbed
) {
585 SetModeClass(eIsInObjectOrEmbed
);
588 body
->AppendChildTo(mImageContent
, false, IgnoreErrors());
589 mImageContent
->SetLoadingEnabled(true);
594 void ImageDocument::DefaultCheckOverflowing() {
595 CheckOverflowing(StaticPrefs::browser_enable_automatic_image_resizing());
598 nsresult
ImageDocument::CheckOverflowing(bool changeState
) {
599 const bool imageWasOverflowing
= ImageIsOverflowing();
600 const bool imageWasOverflowingVertically
= ImageIsOverflowingVertically();
603 nsPresContext
* context
= GetPresContext();
608 nsRect visibleArea
= context
->GetVisibleArea();
610 mVisibleWidth
= nsPresContext::AppUnitsToFloatCSSPixels(visibleArea
.width
);
612 nsPresContext::AppUnitsToFloatCSSPixels(visibleArea
.height
);
615 const bool windowBecameBigEnough
=
616 imageWasOverflowing
&& !ImageIsOverflowing();
617 const bool verticalOverflowChanged
=
618 imageWasOverflowingVertically
!= ImageIsOverflowingVertically();
620 if (changeState
|| mShouldResize
|| mFirstResize
|| windowBecameBigEnough
||
621 verticalOverflowChanged
) {
622 if (mIsInObjectOrEmbed
) {
623 SetModeClass(eIsInObjectOrEmbed
);
624 } else if (ImageIsOverflowing() && (changeState
|| mShouldResize
)) {
626 } else if (mImageIsResized
|| mFirstResize
|| windowBecameBigEnough
) {
628 } else if (!mImageIsResized
&& verticalOverflowChanged
) {
629 if (ImageIsOverflowingVertically()) {
630 SetModeClass(eOverflowingVertical
);
632 SetModeClass(eOverflowingHorizontalOnly
);
636 mFirstResize
= false;
640 void ImageDocument::UpdateTitleAndCharset() {
641 if (mHasCustomTitle
) {
645 AutoRestore
<bool> restore(mTitleUpdateInProgress
);
646 mTitleUpdateInProgress
= true;
648 nsAutoCString typeStr
;
649 nsCOMPtr
<imgIRequest
> imageRequest
;
651 mImageContent
->GetRequest(nsIImageLoadingContent::CURRENT_REQUEST
,
652 getter_AddRefs(imageRequest
));
657 imageRequest
->GetMimeType(getter_Copies(mimeType
));
658 ToUpperCase(mimeType
);
659 nsCString::const_iterator start
, end
;
660 mimeType
.BeginReading(start
);
661 mimeType
.EndReading(end
);
662 nsCString::const_iterator iter
= end
;
663 if (FindInReadable("IMAGE/"_ns
, start
, iter
) && iter
!= end
) {
664 // strip out "X-" if any
667 if (iter
!= end
&& *iter
== '-') {
670 // looks like "IMAGE/X-" is the type?? Bail out of here.
671 mimeType
.BeginReading(iter
);
677 typeStr
= Substring(iter
, end
);
684 if (mImageIsResized
) {
685 AutoTArray
<nsString
, 1> formatString
;
686 formatString
.AppendElement()->AppendInt(NSToCoordFloor(GetRatio() * 100));
688 FormatStringFromName("ScaledImage", formatString
, status
);
691 static const char* const formatNames
[4] = {
692 "ImageTitleWithNeitherDimensionsNorFile",
693 "ImageTitleWithoutDimensions",
694 "ImageTitleWithDimensions2",
695 "ImageTitleWithDimensions2AndFile",
698 MediaDocument::UpdateTitleAndCharset(typeStr
, mChannel
, formatNames
,
699 mImageWidth
, mImageHeight
, status
);
702 bool ImageDocument::IsSiteSpecific() {
703 return !ShouldResistFingerprinting(RFPTarget::SiteSpecificZoom
) &&
704 StaticPrefs::browser_zoom_siteSpecific();
707 void ImageDocument::ResetZoomLevel() {
708 if (nsContentUtils::IsChildOfSameType(this)) {
712 if (RefPtr
<BrowsingContext
> bc
= GetBrowsingContext()) {
713 // Resetting the zoom level on a discarded browsing context has no effect.
714 Unused
<< bc
->SetFullZoom(mOriginalZoomLevel
);
718 float ImageDocument::GetZoomLevel() {
719 if (BrowsingContext
* bc
= GetBrowsingContext()) {
720 return bc
->FullZoom();
722 return mOriginalZoomLevel
;
725 void ImageDocument::CheckFullZoom() {
726 nsDOMTokenList
* classList
=
727 mImageContent
? mImageContent
->ClassList() : nullptr;
733 classList
->Toggle(u
"fullZoomOut"_ns
,
734 dom::Optional
<bool>(GetZoomLevel() > mOriginalZoomLevel
),
736 classList
->Toggle(u
"fullZoomIn"_ns
,
737 dom::Optional
<bool>(GetZoomLevel() < mOriginalZoomLevel
),
741 float ImageDocument::GetResolution() {
742 if (PresShell
* presShell
= GetPresShell()) {
743 return presShell
->GetResolution();
745 return mOriginalResolution
;
748 void ImageDocument::MaybeSendResultToEmbedder(nsresult aResult
) {
749 if (!mIsInObjectOrEmbed
) {
753 BrowsingContext
* context
= GetBrowsingContext();
759 if (context
->GetParent() && context
->GetParent()->IsInProcess()) {
760 if (Element
* embedder
= context
->GetEmbedderElement()) {
761 if (nsCOMPtr
<nsIObjectLoadingContent
> objectLoadingContent
=
762 do_QueryInterface(embedder
)) {
763 NS_DispatchToMainThread(NS_NewRunnableFunction(
764 "nsObjectLoadingContent::SubdocumentImageLoadComplete",
765 [objectLoadingContent
, aResult
]() {
766 static_cast<nsObjectLoadingContent
*>(objectLoadingContent
.get())
767 ->SubdocumentImageLoadComplete(aResult
);
774 if (BrowserChild
* browserChild
=
775 BrowserChild::GetFrom(context
->GetDocShell())) {
776 browserChild
->SendImageLoadComplete(aResult
);
779 } // namespace mozilla::dom
781 nsresult
NS_NewImageDocument(mozilla::dom::Document
** aResult
,
782 nsIPrincipal
* aPrincipal
,
783 nsIPrincipal
* aPartitionedPrincipal
) {
784 auto* doc
= new mozilla::dom::ImageDocument();
787 nsresult rv
= doc
->Init(aPrincipal
, aPartitionedPrincipal
);