Bug 1719855 - Take over preventDefaulted infomation for long-tap events to the origin...
[gecko.git] / dom / html / ImageDocument.cpp
blob74c6c0ae52f88888e243ae9a7b7815d83a3b54be
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"
21 #include "nsRect.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"
28 #include "nsIFrame.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"
38 #include "nsError.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"
46 #include <algorithm>
48 namespace mozilla::dom {
50 class ImageListener : public MediaDocumentStreamListener {
51 public:
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;
66 NS_IMETHODIMP
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);
72 if (!channel) {
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;
91 if (requestingNode) {
92 loadingPrincipal = requestingNode->NodePrincipal();
93 } else {
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);
110 return NS_OK;
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()
125 : MediaDocument(),
126 mVisibleWidth(0.0),
127 mVisibleHeight(0.0),
128 mImageWidth(0),
129 mImageHeight(0),
130 mImageIsResized(false),
131 mShouldResize(false),
132 mFirstResize(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,
146 nsIDOMEventListener)
148 nsresult ImageDocument::Init() {
149 nsresult rv = MediaDocument::Init();
150 NS_ENSURE_SUCCESS(rv, rv);
152 mShouldResize = StaticPrefs::browser_enable_automatic_image_resizing();
153 mFirstResize = true;
155 return NS_OK;
158 JSObject* ImageDocument::WrapNode(JSContext* aCx,
159 JS::Handle<JSObject*> aGivenProto) {
160 return ImageDocument_Binding::Wrap(aCx, this, aGivenProto);
163 nsresult ImageDocument::StartDocumentLoad(
164 const char* aCommand, nsIChannel* aChannel, nsILoadGroup* aLoadGroup,
165 nsISupports* aContainer, nsIStreamListener** aDocListener, bool aReset) {
166 nsresult rv = MediaDocument::StartDocumentLoad(
167 aCommand, aChannel, aLoadGroup, aContainer, aDocListener, aReset);
168 if (NS_FAILED(rv)) {
169 return rv;
172 mOriginalZoomLevel = IsSiteSpecific() ? 1.0 : GetZoomLevel();
173 CheckFullZoom();
174 mOriginalResolution = GetResolution();
176 if (BrowsingContext* context = GetBrowsingContext()) {
177 mIsInObjectOrEmbed = context->IsEmbedderTypeObjectOrEmbed();
180 NS_ASSERTION(aDocListener, "null aDocListener");
181 *aDocListener = new ImageListener(this);
182 NS_ADDREF(*aDocListener);
184 return NS_OK;
187 void ImageDocument::Destroy() {
188 if (RefPtr<HTMLImageElement> img = std::move(mImageContent)) {
189 // Remove our event listener from the image content.
190 img->RemoveEventListener(u"load"_ns, this, false);
191 img->RemoveEventListener(u"click"_ns, this, false);
193 // Break reference cycle with mImageContent, if we have one
194 if (mObservingImageLoader) {
195 img->RemoveNativeObserver(this);
199 MediaDocument::Destroy();
202 void ImageDocument::SetScriptGlobalObject(
203 nsIScriptGlobalObject* aScriptGlobalObject) {
204 // If the script global object is changing, we need to unhook our event
205 // listeners on the window.
206 nsCOMPtr<EventTarget> target;
207 if (mScriptGlobalObject && aScriptGlobalObject != mScriptGlobalObject) {
208 target = do_QueryInterface(mScriptGlobalObject);
209 target->RemoveEventListener(u"resize"_ns, this, false);
210 target->RemoveEventListener(u"keypress"_ns, this, false);
213 // Set the script global object on the superclass before doing
214 // anything that might require it....
215 MediaDocument::SetScriptGlobalObject(aScriptGlobalObject);
217 if (aScriptGlobalObject) {
218 if (!InitialSetupHasBeenDone()) {
219 MOZ_ASSERT(!GetRootElement(), "Where did the root element come from?");
220 // Create synthetic document
221 #ifdef DEBUG
222 nsresult rv =
223 #endif
224 CreateSyntheticDocument();
225 NS_ASSERTION(NS_SUCCEEDED(rv), "failed to create synthetic document");
227 target = mImageContent;
228 target->AddEventListener(u"load"_ns, this, false);
229 target->AddEventListener(u"click"_ns, this, false);
232 target = do_QueryInterface(aScriptGlobalObject);
233 target->AddEventListener(u"resize"_ns, this, false);
234 target->AddEventListener(u"keypress"_ns, this, false);
236 if (!InitialSetupHasBeenDone()) {
237 LinkStylesheet(u"resource://content-accessible/ImageDocument.css"_ns);
238 if (!nsContentUtils::IsChildOfSameType(this)) {
239 LinkStylesheet(nsLiteralString(
240 u"resource://content-accessible/TopLevelImageDocument.css"));
242 InitialSetupDone();
247 void ImageDocument::OnPageShow(bool aPersisted,
248 EventTarget* aDispatchStartTarget,
249 bool aOnlySystemGroup) {
250 if (aPersisted) {
251 mOriginalZoomLevel = IsSiteSpecific() ? 1.0 : GetZoomLevel();
252 CheckFullZoom();
253 mOriginalResolution = GetResolution();
255 RefPtr<ImageDocument> kungFuDeathGrip(this);
256 UpdateSizeFromLayout();
258 MediaDocument::OnPageShow(aPersisted, aDispatchStartTarget, aOnlySystemGroup);
261 void ImageDocument::ShrinkToFit() {
262 if (!mImageContent) {
263 return;
265 if (GetZoomLevel() != mOriginalZoomLevel && mImageIsResized &&
266 !nsContentUtils::IsChildOfSameType(this)) {
267 // If we're zoomed, so that we don't maintain the invariant that
268 // mImageIsResized if and only if its displayed width/height fit in
269 // mVisibleWidth/mVisibleHeight, then we may need to switch to/from the
270 // overflowingVertical class here, because our viewport size may have
271 // changed and we don't plan to adjust the image size to compensate. Since
272 // mImageIsResized it has a "height" attribute set, and we can just get the
273 // displayed image height by getting .height on the HTMLImageElement.
275 // Hold strong ref, because Height() can run script.
276 RefPtr<HTMLImageElement> img = mImageContent;
277 uint32_t imageHeight = img->Height();
278 nsDOMTokenList* classList = img->ClassList();
279 if (imageHeight > mVisibleHeight) {
280 classList->Add(u"overflowingVertical"_ns, IgnoreErrors());
281 } else {
282 classList->Remove(u"overflowingVertical"_ns, IgnoreErrors());
284 return;
286 if (GetResolution() != mOriginalResolution && mImageIsResized) {
287 // Don't resize if resolution has changed, e.g., through pinch-zooming on
288 // Android.
289 return;
292 // Keep image content alive while changing the attributes.
293 RefPtr<HTMLImageElement> image = mImageContent;
295 uint32_t newWidth = std::max(1, NSToCoordFloor(GetRatio() * mImageWidth));
296 uint32_t newHeight = std::max(1, NSToCoordFloor(GetRatio() * mImageHeight));
297 image->SetWidth(newWidth, IgnoreErrors());
298 image->SetHeight(newHeight, IgnoreErrors());
300 // The view might have been scrolled when zooming in, scroll back to the
301 // origin now that we're showing a shrunk-to-window version.
302 ScrollImageTo(0, 0);
304 if (!mImageContent) {
305 // ScrollImageTo flush destroyed our content.
306 return;
309 SetModeClass(eShrinkToFit);
311 mImageIsResized = true;
313 UpdateTitleAndCharset();
316 void ImageDocument::ScrollImageTo(int32_t aX, int32_t aY) {
317 RefPtr<PresShell> presShell = GetPresShell();
318 if (!presShell) {
319 return;
322 nsIScrollableFrame* sf = presShell->GetRootScrollFrameAsScrollable();
323 if (!sf) {
324 return;
327 float ratio = GetRatio();
328 // Don't try to scroll image if the document is not visible (mVisibleWidth or
329 // mVisibleHeight is zero).
330 if (ratio <= 0.0) {
331 return;
333 nsRect portRect = sf->GetScrollPortRect();
334 sf->ScrollTo(
335 nsPoint(
336 nsPresContext::CSSPixelsToAppUnits(aX / ratio) - portRect.width / 2,
337 nsPresContext::CSSPixelsToAppUnits(aY / ratio) - portRect.height / 2),
338 ScrollMode::Instant);
341 void ImageDocument::RestoreImage() {
342 if (!mImageContent) {
343 return;
345 // Keep image content alive while changing the attributes.
346 RefPtr<HTMLImageElement> imageContent = mImageContent;
347 imageContent->UnsetAttr(kNameSpaceID_None, nsGkAtoms::width, true);
348 imageContent->UnsetAttr(kNameSpaceID_None, nsGkAtoms::height, true);
350 if (mIsInObjectOrEmbed) {
351 SetModeClass(eIsInObjectOrEmbed);
352 } else if (ImageIsOverflowing()) {
353 if (!ImageIsOverflowingVertically()) {
354 SetModeClass(eOverflowingHorizontalOnly);
355 } else {
356 SetModeClass(eOverflowingVertical);
358 } else {
359 SetModeClass(eNone);
362 mImageIsResized = false;
364 UpdateTitleAndCharset();
367 void ImageDocument::NotifyPossibleTitleChange(bool aBoundTitleElement) {
368 if (!mHasCustomTitle && !mTitleUpdateInProgress) {
369 mHasCustomTitle = true;
372 Document::NotifyPossibleTitleChange(aBoundTitleElement);
375 void ImageDocument::Notify(imgIRequest* aRequest, int32_t aType,
376 const nsIntRect* aData) {
377 if (aType == imgINotificationObserver::SIZE_AVAILABLE) {
378 nsCOMPtr<imgIContainer> image;
379 aRequest->GetImage(getter_AddRefs(image));
380 return OnSizeAvailable(aRequest, image);
383 // Run this using a script runner because HAS_TRANSPARENCY notifications can
384 // come during painting and this will trigger invalidation.
385 if (aType == imgINotificationObserver::HAS_TRANSPARENCY) {
386 nsCOMPtr<nsIRunnable> runnable =
387 NewRunnableMethod("dom::ImageDocument::OnHasTransparency", this,
388 &ImageDocument::OnHasTransparency);
389 nsContentUtils::AddScriptRunner(runnable);
392 if (aType == imgINotificationObserver::LOAD_COMPLETE) {
393 uint32_t reqStatus;
394 aRequest->GetImageStatus(&reqStatus);
395 nsresult status =
396 reqStatus & imgIRequest::STATUS_ERROR ? NS_ERROR_FAILURE : NS_OK;
397 return OnLoadComplete(aRequest, status);
401 void ImageDocument::OnHasTransparency() {
402 if (!mImageContent || nsContentUtils::IsChildOfSameType(this)) {
403 return;
406 nsDOMTokenList* classList = mImageContent->ClassList();
407 classList->Add(u"transparent"_ns, IgnoreErrors());
410 void ImageDocument::SetModeClass(eModeClasses mode) {
411 nsDOMTokenList* classList = mImageContent->ClassList();
413 if (mode == eShrinkToFit) {
414 classList->Add(u"shrinkToFit"_ns, IgnoreErrors());
415 } else {
416 classList->Remove(u"shrinkToFit"_ns, IgnoreErrors());
419 if (mode == eOverflowingVertical) {
420 classList->Add(u"overflowingVertical"_ns, IgnoreErrors());
421 } else {
422 classList->Remove(u"overflowingVertical"_ns, IgnoreErrors());
425 if (mode == eOverflowingHorizontalOnly) {
426 classList->Add(u"overflowingHorizontalOnly"_ns, IgnoreErrors());
427 } else {
428 classList->Remove(u"overflowingHorizontalOnly"_ns, IgnoreErrors());
431 if (mode == eIsInObjectOrEmbed) {
432 classList->Add(u"isInObjectOrEmbed"_ns, IgnoreErrors());
436 void ImageDocument::OnSizeAvailable(imgIRequest* aRequest,
437 imgIContainer* aImage) {
438 int32_t oldWidth = mImageWidth;
439 int32_t oldHeight = mImageHeight;
441 // Styles have not yet been applied, so we don't know the final size. For now,
442 // default to the image's intrinsic size.
443 aImage->GetWidth(&mImageWidth);
444 aImage->GetHeight(&mImageHeight);
446 // Multipart images send size available for each part; ignore them if it
447 // doesn't change our size. (We may not even support changing size in
448 // multipart images in the future.)
449 if (oldWidth == mImageWidth && oldHeight == mImageHeight) {
450 return;
453 nsCOMPtr<nsIRunnable> runnable =
454 NewRunnableMethod("dom::ImageDocument::DefaultCheckOverflowing", this,
455 &ImageDocument::DefaultCheckOverflowing);
456 nsContentUtils::AddScriptRunner(runnable);
457 UpdateTitleAndCharset();
460 void ImageDocument::OnLoadComplete(imgIRequest* aRequest, nsresult aStatus) {
461 UpdateTitleAndCharset();
463 // mImageContent can be null if the document is already destroyed
464 if (NS_FAILED(aStatus) && mImageContent) {
465 nsAutoCString src;
466 mDocumentURI->GetSpec(src);
467 AutoTArray<nsString, 1> formatString;
468 CopyUTF8toUTF16(src, *formatString.AppendElement());
469 nsAutoString errorMsg;
470 FormatStringFromName("InvalidImage", formatString, errorMsg);
472 mImageContent->SetAttr(kNameSpaceID_None, nsGkAtoms::alt, errorMsg, false);
475 MaybeSendResultToEmbedder(aStatus);
478 NS_IMETHODIMP
479 ImageDocument::HandleEvent(Event* aEvent) {
480 nsAutoString eventType;
481 aEvent->GetType(eventType);
482 if (eventType.EqualsLiteral("resize")) {
483 CheckOverflowing(false);
484 CheckFullZoom();
485 } else if (eventType.EqualsLiteral("click") &&
486 StaticPrefs::browser_enable_click_image_resizing() &&
487 !mIsInObjectOrEmbed) {
488 ResetZoomLevel();
489 mShouldResize = true;
490 if (mImageIsResized) {
491 int32_t x = 0, y = 0;
492 MouseEvent* event = aEvent->AsMouseEvent();
493 if (event) {
494 RefPtr<HTMLImageElement> img = mImageContent;
495 x = event->ClientX() - img->OffsetLeft();
496 y = event->ClientY() - img->OffsetTop();
498 mShouldResize = false;
499 RestoreImage();
500 FlushPendingNotifications(FlushType::Layout);
501 ScrollImageTo(x, y);
502 } else if (ImageIsOverflowing()) {
503 ShrinkToFit();
505 } else if (eventType.EqualsLiteral("load")) {
506 UpdateSizeFromLayout();
509 return NS_OK;
512 void ImageDocument::UpdateSizeFromLayout() {
513 // Pull an updated size from the content frame to account for any size
514 // change due to CSS properties like |image-orientation|.
515 if (!mImageContent) {
516 return;
519 // Need strong ref, because GetPrimaryFrame can run script.
520 RefPtr<HTMLImageElement> imageContent = mImageContent;
521 nsIFrame* contentFrame = imageContent->GetPrimaryFrame(FlushType::Frames);
522 if (!contentFrame) {
523 return;
526 nsIntSize oldSize(mImageWidth, mImageHeight);
527 IntrinsicSize newSize = contentFrame->GetIntrinsicSize();
529 if (newSize.width) {
530 mImageWidth = nsPresContext::AppUnitsToFloatCSSPixels(*newSize.width);
532 if (newSize.height) {
533 mImageHeight = nsPresContext::AppUnitsToFloatCSSPixels(*newSize.height);
536 // Ensure that our information about overflow is up-to-date if needed.
537 if (mImageWidth != oldSize.width || mImageHeight != oldSize.height) {
538 CheckOverflowing(false);
542 void ImageDocument::UpdateRemoteStyle(StyleImageRendering aImageRendering) {
543 if (!mImageContent) {
544 return;
547 // Using ScriptRunner to avoid doing DOM mutation at an unexpected time.
548 if (!nsContentUtils::IsSafeToRunScript()) {
549 return nsContentUtils::AddScriptRunner(
550 NewRunnableMethod<StyleImageRendering>(
551 "UpdateRemoteStyle", this, &ImageDocument::UpdateRemoteStyle,
552 aImageRendering));
555 nsCOMPtr<nsICSSDeclaration> style = mImageContent->Style();
556 switch (aImageRendering) {
557 case StyleImageRendering::Auto:
558 case StyleImageRendering::Smooth:
559 case StyleImageRendering::Optimizequality:
560 style->SetProperty("image-rendering"_ns, "auto"_ns, ""_ns,
561 IgnoreErrors());
562 break;
563 case StyleImageRendering::Optimizespeed:
564 case StyleImageRendering::Pixelated:
565 style->SetProperty("image-rendering"_ns, "pixelated"_ns, ""_ns,
566 IgnoreErrors());
567 break;
568 case StyleImageRendering::CrispEdges:
569 style->SetProperty("image-rendering"_ns, "crisp-edges"_ns, ""_ns,
570 IgnoreErrors());
571 break;
575 nsresult ImageDocument::CreateSyntheticDocument() {
576 // Synthesize an html document that refers to the image
577 nsresult rv = MediaDocument::CreateSyntheticDocument();
578 NS_ENSURE_SUCCESS(rv, rv);
580 // Add the image element
581 RefPtr<Element> body = GetBodyElement();
582 if (!body) {
583 NS_WARNING("no body on image document!");
584 return NS_ERROR_FAILURE;
587 RefPtr<mozilla::dom::NodeInfo> nodeInfo;
588 nodeInfo = mNodeInfoManager->GetNodeInfo(
589 nsGkAtoms::img, nullptr, kNameSpaceID_XHTML, nsINode::ELEMENT_NODE);
591 RefPtr<Element> image = NS_NewHTMLImageElement(nodeInfo.forget());
592 mImageContent = HTMLImageElement::FromNodeOrNull(image);
593 if (!mImageContent) {
594 return NS_ERROR_OUT_OF_MEMORY;
597 nsAutoCString src;
598 mDocumentURI->GetSpec(src);
600 NS_ConvertUTF8toUTF16 srcString(src);
601 // Make sure not to start the image load from here...
602 mImageContent->SetLoadingEnabled(false);
603 mImageContent->SetAttr(kNameSpaceID_None, nsGkAtoms::src, srcString, false);
604 mImageContent->SetAttr(kNameSpaceID_None, nsGkAtoms::alt, srcString, false);
606 body->AppendChildTo(mImageContent, false, IgnoreErrors());
607 mImageContent->SetLoadingEnabled(true);
609 return NS_OK;
612 void ImageDocument::DefaultCheckOverflowing() {
613 CheckOverflowing(StaticPrefs::browser_enable_automatic_image_resizing());
616 nsresult ImageDocument::CheckOverflowing(bool changeState) {
617 const bool imageWasOverflowing = ImageIsOverflowing();
618 const bool imageWasOverflowingVertically = ImageIsOverflowingVertically();
621 nsPresContext* context = GetPresContext();
622 if (!context) {
623 return NS_OK;
626 nsRect visibleArea = context->GetVisibleArea();
628 mVisibleWidth = nsPresContext::AppUnitsToFloatCSSPixels(visibleArea.width);
629 mVisibleHeight =
630 nsPresContext::AppUnitsToFloatCSSPixels(visibleArea.height);
633 const bool windowBecameBigEnough =
634 imageWasOverflowing && !ImageIsOverflowing();
635 const bool verticalOverflowChanged =
636 imageWasOverflowingVertically != ImageIsOverflowingVertically();
638 if (changeState || mShouldResize || mFirstResize || windowBecameBigEnough ||
639 verticalOverflowChanged) {
640 if (mIsInObjectOrEmbed) {
641 SetModeClass(eIsInObjectOrEmbed);
642 } else if (ImageIsOverflowing() && (changeState || mShouldResize)) {
643 ShrinkToFit();
644 } else if (mImageIsResized || mFirstResize || windowBecameBigEnough) {
645 RestoreImage();
646 } else if (!mImageIsResized && verticalOverflowChanged) {
647 if (ImageIsOverflowingVertically()) {
648 SetModeClass(eOverflowingVertical);
649 } else {
650 SetModeClass(eOverflowingHorizontalOnly);
654 mFirstResize = false;
655 return NS_OK;
658 void ImageDocument::UpdateTitleAndCharset() {
659 if (mHasCustomTitle) {
660 return;
663 AutoRestore<bool> restore(mTitleUpdateInProgress);
664 mTitleUpdateInProgress = true;
666 nsAutoCString typeStr;
667 nsCOMPtr<imgIRequest> imageRequest;
668 if (mImageContent) {
669 mImageContent->GetRequest(nsIImageLoadingContent::CURRENT_REQUEST,
670 getter_AddRefs(imageRequest));
673 if (imageRequest) {
674 nsCString mimeType;
675 imageRequest->GetMimeType(getter_Copies(mimeType));
676 ToUpperCase(mimeType);
677 nsCString::const_iterator start, end;
678 mimeType.BeginReading(start);
679 mimeType.EndReading(end);
680 nsCString::const_iterator iter = end;
681 if (FindInReadable("IMAGE/"_ns, start, iter) && iter != end) {
682 // strip out "X-" if any
683 if (*iter == 'X') {
684 ++iter;
685 if (iter != end && *iter == '-') {
686 ++iter;
687 if (iter == end) {
688 // looks like "IMAGE/X-" is the type?? Bail out of here.
689 mimeType.BeginReading(iter);
691 } else {
692 --iter;
695 typeStr = Substring(iter, end);
696 } else {
697 typeStr = mimeType;
701 nsAutoString status;
702 if (mImageIsResized) {
703 AutoTArray<nsString, 1> formatString;
704 formatString.AppendElement()->AppendInt(NSToCoordFloor(GetRatio() * 100));
706 FormatStringFromName("ScaledImage", formatString, status);
709 static const char* const formatNames[4] = {
710 "ImageTitleWithNeitherDimensionsNorFile",
711 "ImageTitleWithoutDimensions",
712 "ImageTitleWithDimensions2",
713 "ImageTitleWithDimensions2AndFile",
716 MediaDocument::UpdateTitleAndCharset(typeStr, mChannel, formatNames,
717 mImageWidth, mImageHeight, status);
720 bool ImageDocument::IsSiteSpecific() {
721 // TODO(Bug 1837976) Need an RFPTarget for FullZoom._isSiteSpecific
722 return !ShouldResistFingerprinting(RFPTarget::IsAlwaysEnabledForPrecompute) &&
723 mozilla::Preferences::GetBool("browser.zoom.siteSpecific", false);
726 void ImageDocument::ResetZoomLevel() {
727 if (nsContentUtils::IsChildOfSameType(this)) {
728 return;
731 if (RefPtr<BrowsingContext> bc = GetBrowsingContext()) {
732 // Resetting the zoom level on a discarded browsing context has no effect.
733 Unused << bc->SetFullZoom(mOriginalZoomLevel);
737 float ImageDocument::GetZoomLevel() {
738 if (BrowsingContext* bc = GetBrowsingContext()) {
739 return bc->FullZoom();
741 return mOriginalZoomLevel;
744 void ImageDocument::CheckFullZoom() {
745 nsDOMTokenList* classList =
746 mImageContent ? mImageContent->ClassList() : nullptr;
748 if (!classList) {
749 return;
752 classList->Toggle(u"fullZoomOut"_ns,
753 dom::Optional<bool>(GetZoomLevel() > mOriginalZoomLevel),
754 IgnoreErrors());
755 classList->Toggle(u"fullZoomIn"_ns,
756 dom::Optional<bool>(GetZoomLevel() < mOriginalZoomLevel),
757 IgnoreErrors());
760 float ImageDocument::GetResolution() {
761 if (PresShell* presShell = GetPresShell()) {
762 return presShell->GetResolution();
764 return mOriginalResolution;
767 void ImageDocument::MaybeSendResultToEmbedder(nsresult aResult) {
768 if (!mIsInObjectOrEmbed) {
769 return;
772 BrowsingContext* context = GetBrowsingContext();
774 if (!context) {
775 return;
778 if (context->GetParent() && context->GetParent()->IsInProcess()) {
779 if (Element* embedder = context->GetEmbedderElement()) {
780 if (nsCOMPtr<nsIObjectLoadingContent> objectLoadingContent =
781 do_QueryInterface(embedder)) {
782 NS_DispatchToMainThread(NS_NewRunnableFunction(
783 "nsObjectLoadingContent::SubdocumentImageLoadComplete",
784 [objectLoadingContent, aResult]() {
785 static_cast<nsObjectLoadingContent*>(objectLoadingContent.get())
786 ->SubdocumentImageLoadComplete(aResult);
787 }));
789 return;
793 if (BrowserChild* browserChild =
794 BrowserChild::GetFrom(context->GetDocShell())) {
795 browserChild->SendImageLoadComplete(aResult);
798 } // namespace mozilla::dom
800 nsresult NS_NewImageDocument(mozilla::dom::Document** aResult) {
801 auto* doc = new mozilla::dom::ImageDocument();
802 NS_ADDREF(doc);
804 nsresult rv = doc->Init();
805 if (NS_FAILED(rv)) {
806 NS_RELEASE(doc);
809 *aResult = doc;
811 return rv;