Files
palemoon27/dom/html/HTMLImageElement.cpp
T
roytam1 842ee3f700 import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1215921 - Range Analysis: Recover observable operands if they are recoverable. r=jandem,sunfish (5d0387ba66)
- Bug 1221923 - Remove pointless "initialized" static in VMFunction::addToFunctions; r=Waldo (fbf61fff54)
- Bug 12228397 - Bail out when dividing large unsigned integer by one. r=sunfish (cbd9d34bcf)
- Bug 1229292 - IonMonkey: MIPS64: Fix skip nops in conditional branches. r=huangwenjun06 (2244600084)
- Bug 1090957 - IonMonkey: MIPS: Implement atomics in MacroAssembler. r=lth (29399e4a33)
- Bug 1229989 - IonMonkey: MIPS: Fix patchCall for mips32. r=luke (1ae6f20686)
- Bug 1213747 - IonMonkey: MIPS: Import MIPS64 support into MoveEmitter-mips-shared. r=nbp f=rankov (16d46fe32e)
- Bug 1233863 - ARM64: Record the correct branch offset. r=sstangl (b2f940056e)
- Bug 1233884 - Remove unused CompactBufferWriters from MozBaseAssembler. r=jolesen (e37860be67)
- Bug 1233863 - ARM64: Avoid BumpSystemStackPointer(). r=sstangl (5c06e601c1)
- Bug 1229802 - Simplify MacroAssemblerARMCompat::decBranchPtr. r=nbp (a908c62e5b)
- bit of Bug 1217515 - Clean up the way touch event support is configured (2cfd0e4c65)
- Bug 1221459 - Remove SelectionStateChangedEvent. r=mtseng, r=smaug (9a827ab9fc)
- Bug 1209479 - Map Android back button to nsIWebNavigation::GoBack() for the current active frame r=fabrice (be41e7b8da)
- Bug 1165841 - Part 1: add window into nsINfcEventListener. r=dimi (475a56ab28)
- Bug 1165841 - Part 2: move window-related code to nsNfc.js. r=dimi (e2a0487b75)
- Bug 1165841 - Part 3: remove _rfState and init from NfcContentHelper. r=dimi (b8be95012d)
- Bug 1165841 - Part 4: using eventListeners. r=dimi (a22ff6d56c)
- Bug 1165841 - Part 5: remove listener when window is destroyed. r=dimi (48716e2ba1)
- Bug 1168292 - Part 1: update SYSTEM_APP_ID. r=dimi (ecdbbefb03)
- Bug 1168292 - Part 2: notify listener with correct tabId. r=dimi (4fb26c705e)
- Bug 1168292 - Part 3: add tabId in notifyUserAccepted. r=dimi (1b36a15b65)
- Bug 1170053 - [Aries] Not able to share a picture using NFC. r=yoshi (0b80df2866)
- Bug 1172159 - [NFC] Introduce getFocusTabId function. r=allstars.chh (b917d0dac7)
- Bug 1168704 - Rename setFocusApp in nslNfcContentHelper. r=yoshi (9918707442)
- more missing of Bug 1209479 (6480ccc315)
- Bug 1166210 - Remove ServicesSetting changes listener in NfcContentHelper. r=yoshi (6e8f388637)
- Bug 1121900 - [flatfish] build break by "error: undefined reference to 'mozilla::dom::MozIsoDepTech::mTechnology'". r=yoshi (b5aaaada08)
- Bug 976457 - B2G NFC: API for supporting NFC_A tags. r=yoshi r=smaug (b908a5d60a)
- Bug 1156208 - this.nfc.getErrorMessage is not a function. r=dimi (42e33fcfc9)
- Bug 1225701 - Add comments in TouchCaret and SelectionCarets for their obsolescence. r=mtseng (ba85234c0e)
- Bug 1210341 - (v3) Reduce accessiblecaret size. r=TYLin Bug 1221459 - Remove TouchCaret and SelectionCarets. r=mtseng, r=roc (ad6282ff96)
- Bug 1216986 - Fix usage of nsIURI.host in password manager and prompt code to support IPv6. r=dolske,liuche,kanru (cec90a6251)
- Bug 962249 part 1 - Add Element.scroll{Top,Left}Min (chrome-only) and convert most of scrollLeftMax uses and part of scrollTopMax uses to combinations with the new properties. r=roc,bz (13ed8ee58f)
- Bug 940292 - when using Australis' customize mode, the bookmarks toolbar chevron breaks, r=jaws (4167911610)
- Bug 962249 part 3 - Add Window.scrollMin{X,Y} (chrome-only) and conve… (b9b6e6aa8f)
- Bug 918771 - Part 1: Move Fragment Serialization logic into nsContentUtils::SerializeNodeToMarkup, r=bz (865ea1d334)
- Bug 918771 - Part 2: Send text/html as MIME type for XHR send() of HTML document, r=bz (129b8d4115)
- Bug 918771 - Part 3: Update Web Platform tests to check for correct behavior, r=bz (ed0536f5b8)
- Bug 1085284 - Implement URLSearchParams iterable<>, r=bz (db1edd6d74)
- Bug 1224643. Fix handling of U+0000 in URLSearchParams serialization. r=baku (55856e5353)
- Bug 1224580. Copy of URLSearchParams should not copy its observer pointer. r=baku (1a5d859de5)
- Bug 1153145 - Ensure trusted focus events from web content focus plugins. r=smaug (d79fb35d4b)
- Bug 1183901, properly support WrapperCache on DistributedContentList, r=wchen (f15879c8ca)
- Bug 1188887: P1. Allow seeking when readyState is HAVE_NOTHING. r=jwwang (aa33721a44)
- Bug 1188887: P2. Add mochitest testing new seek behavior. r=jwwang (0520088343)
- Bug 1232223 - Part 6: Remove function prototype for undefined function IsAudioAPIEnabled(). r=jya (5126eb83ed)
- Bug 1232223 - Part 5: Run wave tests unconditionally. r=jya (668e6b9b77)
- Bug 1232223 - Part 1: Remove MOZ_WEBM #ifdefs because WebM is always supported, though not necessarily enabled. r=jya r=glandium (b3ec44f5bc)
- Bug 1232223 - Part 2: Remove MOZ_VPX #ifdefs because VPx is always supported, though not necessarily enabled. r=jya (c8853a16c4)
- Bug 1232223 - Part 3: Remove MOZ_WAVE #ifdefs because Wave is always supported. r=jya (e5c18f912c)
- Bug 1232223 - Part 4: Run webm tests unconditionally. r=jya (a81ab83b00)
- fix (9d9acad7f8)
- bug 1169640 - use nsIPrompt instead of nsIPromptService for insecure form submission r=mrbkap (1091d0d839)
- Bug 1231919 - crash in mozilla::a11y::DocAccessible::ValidateARIAOwned, r=davidb (3466d77e14)
- bug 1172538 - make sure a document has an IPC actor before shutting it down r=davidb, lsocks (823a447f7f)
- Bug 1147646 - Crash in mozilla::a11y::DocAccessible::ProcessContentInserted while stability testing, r=davidb (c9e4e7ef2f)
- Bug 1230118 - added asserts on aOwner and aOwner->Elm() r=surkov (94295ffd61)
- Bug 1213281 - crash in mozilla::a11y::DocAccessible::UpdateTreeOnInsertion, r=davidb (6442f927cd)
- bug 1196460 - add method to get wrapper of proxy for document containing this proxied accessible r=surkov (0cc7ff8758)
- Bug 1222174 - add override declarations in AccessibleWrap.h; r=tbsaunde (a8c1d0d3f3)
- bug 1187055 - check the proxy being destroyed has a wrapper before cleaning it up r=davidb (b73966446c)
- bug 1196460 - remove proxy's ids when they are destroyed r=surkov (3cbc9a8536)
- bug 1196372 - make GetHWNDFor() work with proxied accessibles r=surkov (28a6057913)
- Bug 1196460 - teach GetChildIDFor() to deal with proxied accessibles r=surkov (4746bfa128)
- bug 1199735 - remove event logging from the windows AccessibleWrap::HandleAccEvent r=davidb (869e18d13f)
- bug 1199735 - factor win event dispatch logic into its own function r=davidb (0a9704aa9d)
- bug 1196460 - create different proxy wrappers depending on the type of the proxy r=surkov (cd2d18ebdc)
- bug 1213327 - store interfaces a proxy implements on the Accessible wrapping it (406c9a3715)
- bug 1213606 - work around proxy's that don't have a wrapper for their document r=davidb (252a3ff2e7)
- bug 1192330 - update text change data for proxied text change events r=surkov (4deb371062)
- bug 1199735 - fire windows events on proxies r=davidb (6400387e71)
- bug 1186536 - Bail out of ProxyTextChangeEvent() if the proxy doesn't have a wrapper r=davidb (b40f69c77b)
- bug 1207862 - make WrapperFor() take a const ProxyAccessible * r=davidb (8e79dc6d75)
- bug 1213402 - fixup silly array , on windows r=me landing on a CLOSED TREE (33368af3af)
- bug 606080 - add class to generate unique 32 bit ids r=froydnj (ebf0888dcc)
- Bug 1231148 - Avoid requiring IDL files installed in $DIST/idl to run AccEventGen.py. r=ted (22078343ce)
- Bug 1228518 - Don't send SessionStore:update for initial about:blank page load. r=ttaubert (8fcc970d50)
- Bug 950399 - SessionStore shouldn't forget domain cookies r=yoric (3303ca35b7)
- Bug 1226333 - Add tests for async window flushing. r=billm. (95dc2e250e)
- Bug 1195295 - Remove SessionStore's SyncHandler since all tab and window flushing is now async. r=ttaubert (4ad6b14a1b)
- Bug 1225921 - Have SessionStore keep a list of window data that might be saved during a flush. r=billm (1385337faf)
- bit of Bug 1216775 - Remove for-each from browser/ (1464b2b726)
- Bug 996053 - make nsISessionStore's setTabValue, setWindowValue and setGlobalValue take arbitrary JS values but throw for non-strings, for consistency with SessionStore.jsm. r=ttaubert (776a13d830)
- Bug 1080934 - add radio buttons to about:welcomeback. r=Unfocused (87f461e9dc)
- Bug 1221050 - part 2: migrate data into bookmarks, r=ttaubert,mak (9ba4f6e8d0)
- Bug 1221050 - part 3: strip hidden tab groups out of 'real' session store data, r=ttaubert (2c5396addb)
- Bug 1221050 - part 4: write a backup to desktop, r=ttaubert (22b8afa244)
- Bug 1221050 - part 5: create page for use with tabview migration, r=ttaubert (8f8c90edd7)
- Bug 1221050 - part z: rudimentary tests to ensure the individual bits work as advertised, r=ttaubert (855fbbd763)
- Bug 1232677 - ignore empty state passed by session restore observer notification in the tab groups migration code, r=jaws (0246efda7a)
- Bug 1229831 - tab group migration code loses group titles, r=felipe (54cb3770f0)
- Bug 1230564 - stick backup in profile directory instead, r=mconley (34f73b1b55)
- Bug 1231126 - always use unique property name for group titles, r=felipe (d98720afb4)
- Bug 1230831 - fix treatment of tabs with no group information, r=mconley (97e15edcef)
- Bug 1231114 - fix labels of unnamed groups as well as group ordering on the tab migration page, r=mconley (9cc692e45b)
- Bug 1209999 - Update string for push notification doorhanger. (968646e288)
- Bug 1216684 - Notification permissions cannot be granted/denied in private windows. r=MattN (da8800b632)
- Bug 1208295 - Open content preferences after receiving notifications-open-settings. r=jaws (292c567eb6)
- Bug 1228980 - Display favicons of tab entries in aboutSessionRestore-based pages. r=ttaubert (17fc0041dd)
- Bug 1113031 - Replace deprecated expression closures in about:sessionrestore with real functions. r=ttaubert (ad6941b477)
- Bug 1229838 - rel=apple-touch-icon-precomposed should fire mozbrowsericonchange. r=fabrice (2a3e93da96)
- Bug 1231040 - Check for premulting better. - r=jrmuizel (811609bbb3)
- Bug 1224475 - Start agent after seeking. r=baku (a009b58f2c)
- Bug 1231557 - Use the URL Classifier in Media elements. r=cpearce,r=gcp (9f5503581d)
- bug 1228484 throw instead of capturing a second stream to a different graph r=roc (e762799424)
- Bug 1198435 - MediaElementTableCount now checks that the element is not present for URIs other than the expected one. r=rillian (838b1b886b)
- Bug 1224991 - Log format string mismatch the number of parameters. r=cpearce. (9cd2770bd2)
- Bug 1144409 - Encrypted event should be fired once per initData. r=cpearce (e50b380feb)
- Bug 1213589 part.1 Make ContentEventHandler::GetTextLength() and GetNativeTextLength() called only with a text node r=smaug (10955440a9)
- Bug 1213589 part.2 Clean up GenerateFlatTextContent(), GelerateFlatFontRanges() and GetFlatTextOffsetOfRange() of ContentEventHandler r=smaug (3f6bf987ff)
- Bug 1213589 part.3 ContentEventHandler::GetFlatTextLengthInRange() should handle specially when it's called by nsIMutationObserver::ContentRemoved() r=smaug (ed03499803)
- Bug 1213859 part.4 ContentEventHandler should use NS_NewPreContentIterator rathr than NS_NewContentIterator at converting between DOM tree and flattened text r=smaug (fe6e3b1114)
- Bug 1213589 part.5 Redesign the rules to create range in ContentEventHandler::SetRangeFromFlatTextOffset() r=smaug (edaa7baf87)
- Bug 1213589 part.6 ContentEventHandler should insert line breaks at open tag of elements except non-replaced inline elements r=smaug (c2e9cc11dc)
- Bug 1213589 part.7 Add new testcases to runSetSelectionEventTest() and runQueryTextContentEventTest() for checking the behavior with open tag r=smaug (bcea465e5e)
- Bug 1213589 part.8 When there are no nodes causing text, ContentEventHandler should set start of the editor root to start of the range r=smaug (a6d6b4d8d5)
- Bug 1213589 part.9 ContentEventHandler::ShouldBreakLineBefore() should return false if the content is unknown HTML element r=smaug (960936477f)
- Bug 1214164 - Don't honor all <option> descendants of <select>; r=bz (188bfe2b89)
- Bug 1228876. Correctly ignore nested optgroups even if an optgroup is inserted into another, existing, optgroup. r=mats (f2058c8b68)
- Bug 1193637 - Use IsMap() in HTMLImageElement::PreHandleEvent; r=mrbkap (6f2ef9da61)
- Bug 1160819 - ResponsiveImageSelector - improve some over-aggressive assertions (b5d40119ac)
- Bug 1233259, only in-document images should respond to viewport changes, r=mystor (eb448e258c)
- Bug 773429 - Remove dom.disable_image_src_set. r=khuey (fa06677726)
- Bug 1230110 - HTMLImageElement should call its superclass's DestroyContent(). r=smaug (bac1d12c65)
- Bug 1231245 - Fix logging of Matrix4x4. r=botond (f5c93b67cb)
- Bug 1208661 - Remove some no-longer-used debugging code. r=BenWa (2c86e3efd2)
- Bug 1228602 - Ensure that we pick up the presShell resolution from the layer if there isn't a metrics. r=botond (3c1835a022)
- Annotate FrameMetrics that are created for ScrollInfoLayers. (bug 1192919 part 1, r=kats) (5be0234333)
- Minimize the displayport for frames that must animate synchronously.  (bug 1192919 part 2, r=kats) (5abc63e72d)
- Force a paint to be scheduled for scroll info layers. (bug 1192919 part 3, r=kats) (4ed61248c7)
- Bug 1141127 - When inside a slop area around the first touchstart, prevent touchmove events from going to content. r=botond (18fa91d74e)
- Bug 1174532 - Even if the APZC is not pannable, have a small slop area to consume touchmove events. r=botond (ff8e6f46fe)
- Bug 1208636 - Adjust displayport size based on available system memory. r=kats (d1ff9798b2)
- Bug 1232094 - Make some APZ prefs live. r=botond (d45207bc5b)
- Bug 1231168 - Disable memory-based displayport size adjustment by default. r=mchang (c17b445171)
- Turn apz.use_paint_duration off. (bug 1192919 part 4, r=kats) (dc094c9617)
- Bug 1170325 - Undo an unnecessary signature change to AsyncPanZoomAnimation::TakeDeferredTasks(). r=Waldo (62eafb38ef)
- Bug 1216355 - Ensure that if a repaint request is ignored due to a stale generation number the next repaint request doesn't get dropped. r=botond (c070172b48)
- Bug 1228407 - Rearrange some code by extracting a helper function. r=botond (ae53af7449)
- Bug 1228407 - Update existing smooth scroll animations with new destinations when possible, rather than canceling and restarting them. r=kip (c15022d920)
- Dispatch all APZ repaint requests immediately, and rely on content vsync. (bug 1192919 part 5, r=kats) (53ea2674c8)
- Bug 1230552 - Update some out-of-date comments and remove an old #undef. r=kats (16ba5a82e1)
- Bug 1230552 - Introduce a structure to group fling handoff state. r=kats (4f98893742)
- Bug 1230552 - Extend the immediate scroll handoff pref to apply to flings. r=kats (6b3d4fb0e5)
- Bug 1231228 - Correctly check for whether an APZC along the handoff chain is panned into overscroll. r=kats (bbaeb881af)
- Bug 1226920 - For instances of ForEachNode where we want to traverse the entire tree, use an action that returns void. r=botond (e42de54aea)
- Bug 1230552 - Make immediate scroll handoff for panning prefable. r=kats (89ddb8853a)
- Bug 1230552 - Fuzz a floating-point comparison to avoid an intermittent test failure. r=bustage (839bee076d)
- Bug 1231228 - Gtest. r=kats (e141ee97ef)
- Bug 1208973 - Move function bodies into .cpp file, and remove an unused one. r=botond (ef89b08738)
- Bug 1208973 - Refactor and add logging to TaskThrottler. r=botond (0a88091e20)
- Bug 1208973 - Ensure all code in TaskThrottler is threadsafe since it gets called from various threads. r=botond (9735621fd1)
- Bug 1213273 - Use a chromium Task instead of an nsITimer for the timeout in TaskThrottler. r=mstange (6cc9a9369e)
- Bug 1217251 - In TaskThrottler, dispatch the timeout task correctly from the Java UI thread on Android. r=kats (ee64d9458e)
- Bug 1230552 - Const-correctness improvements. r=kats (cc56f3404a)
- Bug 1230552 - Introduce a helper AsyncPanZoomController::CurrentInputBlock(). r=kats (4cef12a744)
- Remove the TaskThrottler. (bug 1192919 part 6, r=kats) (534312c146)
- Bug 1169695 - Advance the stored time when sampling the transform for a future frame. r=botod (3b08c07827)
- Bug 1169695 - Remove as many manual calls to spin the task queue as possible. r=botond (80c390ec7a)
- Bug 1218618 - Assert that the hit-testing tree's root node doesn't have siblings. r=kats (95ec1d07a7)
- Bug 1225178 - Don't start APZ drag if we don't have a displayport to handle it. r=kats (c29d4f962d)
- bit of  End APZ wheel transactions when the mouse moves out of frame. (bug 1142866 part 2, r=kats,botond) (5a0c79d052)
- Bug 1226320 - Fix a refactoring in APZCTreeManager that didn't preserve semantics correctly. r=kats (35b92bd4a1)
2023-06-27 11:24:57 +08:00

1337 lines
37 KiB
C++

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "mozilla/dom/HTMLImageElement.h"
#include "mozilla/dom/HTMLImageElementBinding.h"
#include "nsGkAtoms.h"
#include "nsStyleConsts.h"
#include "nsPresContext.h"
#include "nsMappedAttributes.h"
#include "nsSize.h"
#include "nsDocument.h"
#include "nsIDocument.h"
#include "nsIDOMMutationEvent.h"
#include "nsIScriptContext.h"
#include "nsIURL.h"
#include "nsIIOService.h"
#include "nsIServiceManager.h"
#include "nsContentUtils.h"
#include "nsContainerFrame.h"
#include "nsNodeInfoManager.h"
#include "mozilla/MouseEvents.h"
#include "nsContentPolicyUtils.h"
#include "nsIDOMWindow.h"
#include "nsFocusManager.h"
#include "mozilla/dom/HTMLFormElement.h"
#include "nsAttrValueOrString.h"
#include "imgLoader.h"
#include "Image.h"
// Responsive images!
#include "mozilla/dom/HTMLSourceElement.h"
#include "mozilla/dom/ResponsiveImageSelector.h"
#include "imgIContainer.h"
#include "imgILoader.h"
#include "imgINotificationObserver.h"
#include "imgRequestProxy.h"
#include "nsILoadGroup.h"
#include "nsRuleData.h"
#include "nsIDOMHTMLMapElement.h"
#include "mozilla/EventDispatcher.h"
#include "mozilla/EventStates.h"
#include "nsLayoutUtils.h"
#include "mozilla/Preferences.h"
static const char *kPrefSrcsetEnabled = "dom.image.srcset.enabled";
NS_IMPL_NS_NEW_HTML_ELEMENT(Image)
#ifdef DEBUG
// Is aSubject a previous sibling of aNode.
static bool IsPreviousSibling(nsINode *aSubject, nsINode *aNode)
{
if (aSubject == aNode) {
return false;
}
nsINode *parent = aSubject->GetParentNode();
if (parent && parent == aNode->GetParentNode()) {
return parent->IndexOf(aSubject) < parent->IndexOf(aNode);
}
return false;
}
#endif
namespace mozilla {
namespace dom {
// Calls LoadSelectedImage on host element unless it has been superseded or
// canceled -- this is the synchronous section of "update the image data".
// https://html.spec.whatwg.org/multipage/embedded-content.html#update-the-image-data
class ImageLoadTask : public nsRunnable
{
public:
ImageLoadTask(HTMLImageElement *aElement, bool aAlwaysLoad)
: mElement(aElement)
, mAlwaysLoad(aAlwaysLoad)
{
mDocument = aElement->OwnerDoc();
mDocument->BlockOnload();
}
NS_IMETHOD Run()
{
if (mElement->mPendingImageLoadTask == this) {
mElement->mPendingImageLoadTask = nullptr;
mElement->LoadSelectedImage(true, true, mAlwaysLoad);
}
mDocument->UnblockOnload(false);
return NS_OK;
}
private:
~ImageLoadTask() {}
RefPtr<HTMLImageElement> mElement;
nsCOMPtr<nsIDocument> mDocument;
bool mAlwaysLoad;
};
HTMLImageElement::HTMLImageElement(already_AddRefed<mozilla::dom::NodeInfo>& aNodeInfo)
: nsGenericHTMLElement(aNodeInfo)
, mForm(nullptr)
, mInDocResponsiveContent(false)
{
// We start out broken
AddStatesSilently(NS_EVENT_STATE_BROKEN);
}
HTMLImageElement::~HTMLImageElement()
{
DestroyImageLoadingContent();
}
NS_IMPL_ADDREF_INHERITED(HTMLImageElement, Element)
NS_IMPL_RELEASE_INHERITED(HTMLImageElement, Element)
NS_IMPL_CYCLE_COLLECTION_INHERITED(HTMLImageElement,
nsGenericHTMLElement,
mResponsiveSelector)
// QueryInterface implementation for HTMLImageElement
NS_INTERFACE_TABLE_HEAD_CYCLE_COLLECTION_INHERITED(HTMLImageElement)
NS_INTERFACE_TABLE_INHERITED(HTMLImageElement,
nsIDOMHTMLImageElement,
nsIImageLoadingContent,
imgIOnloadBlocker,
imgINotificationObserver)
NS_INTERFACE_TABLE_TAIL_INHERITING(nsGenericHTMLElement)
NS_IMPL_ELEMENT_CLONE(HTMLImageElement)
NS_IMPL_STRING_ATTR(HTMLImageElement, Name, name)
NS_IMPL_STRING_ATTR(HTMLImageElement, Align, align)
NS_IMPL_STRING_ATTR(HTMLImageElement, Alt, alt)
NS_IMPL_STRING_ATTR(HTMLImageElement, Border, border)
NS_IMPL_INT_ATTR(HTMLImageElement, Hspace, hspace)
NS_IMPL_BOOL_ATTR(HTMLImageElement, IsMap, ismap)
NS_IMPL_URI_ATTR(HTMLImageElement, LongDesc, longdesc)
NS_IMPL_STRING_ATTR(HTMLImageElement, Sizes, sizes)
NS_IMPL_STRING_ATTR(HTMLImageElement, Lowsrc, lowsrc)
NS_IMPL_URI_ATTR(HTMLImageElement, Src, src)
NS_IMPL_STRING_ATTR(HTMLImageElement, Srcset, srcset)
NS_IMPL_STRING_ATTR(HTMLImageElement, UseMap, usemap)
NS_IMPL_INT_ATTR(HTMLImageElement, Vspace, vspace)
bool
HTMLImageElement::IsInteractiveHTMLContent(bool aIgnoreTabindex) const
{
return HasAttr(kNameSpaceID_None, nsGkAtoms::usemap) ||
nsGenericHTMLElement::IsInteractiveHTMLContent(aIgnoreTabindex);
}
bool
HTMLImageElement::IsSrcsetEnabled()
{
return Preferences::GetBool(kPrefSrcsetEnabled, false);
}
nsresult
HTMLImageElement::GetCurrentSrc(nsAString& aValue)
{
if (!IsSrcsetEnabled()) {
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsIURI> currentURI;
GetCurrentURI(getter_AddRefs(currentURI));
if (currentURI) {
nsAutoCString spec;
currentURI->GetSpec(spec);
CopyUTF8toUTF16(spec, aValue);
} else {
SetDOMStringToNull(aValue);
}
return NS_OK;
}
void
HTMLImageElement::GetItemValueText(DOMString& aValue)
{
GetSrc(aValue);
}
void
HTMLImageElement::SetItemValueText(const nsAString& aValue)
{
SetSrc(aValue);
}
bool
HTMLImageElement::Draggable() const
{
// images may be dragged unless the draggable attribute is false
return !AttrValueIs(kNameSpaceID_None, nsGkAtoms::draggable,
nsGkAtoms::_false, eIgnoreCase);
}
bool
HTMLImageElement::Complete()
{
if (!mCurrentRequest) {
return true;
}
if (mPendingRequest) {
return false;
}
uint32_t status;
mCurrentRequest->GetImageStatus(&status);
return
(status &
(imgIRequest::STATUS_LOAD_COMPLETE | imgIRequest::STATUS_ERROR)) != 0;
}
NS_IMETHODIMP
HTMLImageElement::GetComplete(bool* aComplete)
{
NS_PRECONDITION(aComplete, "Null out param!");
*aComplete = Complete();
return NS_OK;
}
CSSIntPoint
HTMLImageElement::GetXY()
{
nsIFrame* frame = GetPrimaryFrame(Flush_Layout);
if (!frame) {
return CSSIntPoint(0, 0);
}
nsIFrame* layer = nsLayoutUtils::GetClosestLayer(frame->GetParent());
return CSSIntPoint::FromAppUnitsRounded(frame->GetOffsetTo(layer));
}
int32_t
HTMLImageElement::X()
{
return GetXY().x;
}
int32_t
HTMLImageElement::Y()
{
return GetXY().y;
}
NS_IMETHODIMP
HTMLImageElement::GetX(int32_t* aX)
{
*aX = X();
return NS_OK;
}
NS_IMETHODIMP
HTMLImageElement::GetY(int32_t* aY)
{
*aY = Y();
return NS_OK;
}
NS_IMETHODIMP
HTMLImageElement::GetHeight(uint32_t* aHeight)
{
*aHeight = Height();
return NS_OK;
}
NS_IMETHODIMP
HTMLImageElement::SetHeight(uint32_t aHeight)
{
ErrorResult rv;
SetHeight(aHeight, rv);
return rv.StealNSResult();
}
NS_IMETHODIMP
HTMLImageElement::GetWidth(uint32_t* aWidth)
{
*aWidth = Width();
return NS_OK;
}
NS_IMETHODIMP
HTMLImageElement::SetWidth(uint32_t aWidth)
{
ErrorResult rv;
SetWidth(aWidth, rv);
return rv.StealNSResult();
}
bool
HTMLImageElement::ParseAttribute(int32_t aNamespaceID,
nsIAtom* aAttribute,
const nsAString& aValue,
nsAttrValue& aResult)
{
if (aNamespaceID == kNameSpaceID_None) {
if (aAttribute == nsGkAtoms::align) {
return ParseAlignValue(aValue, aResult);
}
if (aAttribute == nsGkAtoms::crossorigin) {
ParseCORSValue(aValue, aResult);
return true;
}
if (ParseImageAttribute(aAttribute, aValue, aResult)) {
return true;
}
}
return nsGenericHTMLElement::ParseAttribute(aNamespaceID, aAttribute, aValue,
aResult);
}
void
HTMLImageElement::MapAttributesIntoRule(const nsMappedAttributes* aAttributes,
nsRuleData* aData)
{
nsGenericHTMLElement::MapImageAlignAttributeInto(aAttributes, aData);
nsGenericHTMLElement::MapImageBorderAttributeInto(aAttributes, aData);
nsGenericHTMLElement::MapImageMarginAttributeInto(aAttributes, aData);
nsGenericHTMLElement::MapImageSizeAttributesInto(aAttributes, aData);
nsGenericHTMLElement::MapCommonAttributesInto(aAttributes, aData);
}
nsChangeHint
HTMLImageElement::GetAttributeChangeHint(const nsIAtom* aAttribute,
int32_t aModType) const
{
nsChangeHint retval =
nsGenericHTMLElement::GetAttributeChangeHint(aAttribute, aModType);
if (aAttribute == nsGkAtoms::usemap ||
aAttribute == nsGkAtoms::ismap) {
NS_UpdateHint(retval, NS_STYLE_HINT_FRAMECHANGE);
} else if (aAttribute == nsGkAtoms::alt) {
if (aModType == nsIDOMMutationEvent::ADDITION ||
aModType == nsIDOMMutationEvent::REMOVAL) {
NS_UpdateHint(retval, NS_STYLE_HINT_FRAMECHANGE);
}
}
return retval;
}
NS_IMETHODIMP_(bool)
HTMLImageElement::IsAttributeMapped(const nsIAtom* aAttribute) const
{
static const MappedAttributeEntry* const map[] = {
sCommonAttributeMap,
sImageMarginSizeAttributeMap,
sImageBorderAttributeMap,
sImageAlignAttributeMap
};
return FindAttributeDependence(aAttribute, map);
}
nsMapRuleToAttributesFunc
HTMLImageElement::GetAttributeMappingFunction() const
{
return &MapAttributesIntoRule;
}
nsresult
HTMLImageElement::BeforeSetAttr(int32_t aNameSpaceID, nsIAtom* aName,
nsAttrValueOrString* aValue,
bool aNotify)
{
if (aNameSpaceID == kNameSpaceID_None && mForm &&
(aName == nsGkAtoms::name || aName == nsGkAtoms::id)) {
// remove the image from the hashtable as needed
nsAutoString tmp;
GetAttr(kNameSpaceID_None, aName, tmp);
if (!tmp.IsEmpty()) {
mForm->RemoveImageElementFromTable(this, tmp,
HTMLFormElement::AttributeUpdated);
}
}
return nsGenericHTMLElement::BeforeSetAttr(aNameSpaceID, aName,
aValue, aNotify);
}
nsresult
HTMLImageElement::AfterSetAttr(int32_t aNameSpaceID, nsIAtom* aName,
const nsAttrValue* aValue, bool aNotify)
{
if (aNameSpaceID == kNameSpaceID_None && mForm &&
(aName == nsGkAtoms::name || aName == nsGkAtoms::id) &&
aValue && !aValue->IsEmptyString()) {
// add the image to the hashtable as needed
MOZ_ASSERT(aValue->Type() == nsAttrValue::eAtom,
"Expected atom value for name/id");
mForm->AddImageElementToTable(this,
nsDependentAtomString(aValue->GetAtomValue()));
}
// Handle src/srcset/crossorigin updates. If aNotify is false, we are coming
// from the parser or some such place; we'll get bound after all the
// attributes have been set, so we'll do the image load from BindToTree.
nsAttrValueOrString attrVal(aValue);
if (aName == nsGkAtoms::src &&
aNameSpaceID == kNameSpaceID_None &&
!aValue) {
// SetAttr handles setting src since it needs to catch img.src =
// img.src, so we only need to handle the unset case
if (InResponsiveMode()) {
if (mResponsiveSelector &&
mResponsiveSelector->Content() == this) {
mResponsiveSelector->SetDefaultSource(NullString());
}
QueueImageLoadTask(true);
} else {
// Bug 1076583 - We still behave synchronously in the non-responsive case
CancelImageRequests(aNotify);
}
} else if (aName == nsGkAtoms::srcset &&
aNameSpaceID == kNameSpaceID_None &&
IsSrcsetEnabled()) {
PictureSourceSrcsetChanged(this, attrVal.String(), aNotify);
} else if (aName == nsGkAtoms::sizes &&
aNameSpaceID == kNameSpaceID_None &&
HTMLPictureElement::IsPictureEnabled()) {
PictureSourceSizesChanged(this, attrVal.String(), aNotify);
} else if (aName == nsGkAtoms::crossorigin &&
aNameSpaceID == kNameSpaceID_None &&
aNotify) {
// Force a new load of the image with the new cross origin policy.
if (InResponsiveMode()) {
// per spec, full selection runs when this changes, even though
// it doesn't directly affect the source selection
QueueImageLoadTask(true);
} else {
// Bug 1076583 - We still use the older synchronous algorithm in
// non-responsive mode. Force a new load of the image with the
// new cross origin policy.
ForceReload(aNotify);
}
}
return nsGenericHTMLElement::AfterSetAttr(aNameSpaceID, aName,
aValue, aNotify);
}
nsresult
HTMLImageElement::PreHandleEvent(EventChainPreVisitor& aVisitor)
{
// If we are a map and get a mouse click, don't let it be handled by
// the Generic Element as this could cause a click event to fire
// twice, once by the image frame for the map and once by the Anchor
// element. (bug 39723)
WidgetMouseEvent* mouseEvent = aVisitor.mEvent->AsMouseEvent();
if (mouseEvent && mouseEvent->IsLeftClickEvent() && IsMap()) {
aVisitor.mEventStatus = nsEventStatus_eConsumeNoDefault;
}
return nsGenericHTMLElement::PreHandleEvent(aVisitor);
}
bool
HTMLImageElement::IsHTMLFocusable(bool aWithMouse,
bool *aIsFocusable, int32_t *aTabIndex)
{
int32_t tabIndex = TabIndex();
if (IsInDoc()) {
nsAutoString usemap;
GetUseMap(usemap);
// XXXbz which document should this be using? sXBL/XBL2 issue! I
// think that OwnerDoc() is right, since we don't want to
// assume stuff about the document we're bound to.
if (OwnerDoc()->FindImageMap(usemap)) {
if (aTabIndex) {
// Use tab index on individual map areas
*aTabIndex = (sTabFocusModel & eTabFocus_linksMask)? 0 : -1;
}
// Image map is not focusable itself, but flag as tabbable
// so that image map areas get walked into.
*aIsFocusable = false;
return false;
}
}
if (aTabIndex) {
// Can be in tab order if tabindex >=0 and form controls are tabbable.
*aTabIndex = (sTabFocusModel & eTabFocus_formElementsMask)? tabIndex : -1;
}
*aIsFocusable =
#ifdef XP_MACOSX
(!aWithMouse || nsFocusManager::sMouseFocusesFormControl) &&
#endif
(tabIndex >= 0 || HasAttr(kNameSpaceID_None, nsGkAtoms::tabindex));
return false;
}
nsresult
HTMLImageElement::SetAttr(int32_t aNameSpaceID, nsIAtom* aName,
nsIAtom* aPrefix, const nsAString& aValue,
bool aNotify)
{
// We need to force our image to reload. This must be done here, not in
// AfterSetAttr or BeforeSetAttr, because we want to do it even if the attr is
// being set to its existing value, which is normally optimized away as a
// no-op.
//
// If we are in responsive mode, we drop the forced reload behavior,
// but still trigger a image load task for img.src = img.src per
// spec.
//
// Both cases handle unsetting src in AfterSetAttr
if (aNameSpaceID == kNameSpaceID_None &&
aName == nsGkAtoms::src) {
if (InResponsiveMode()) {
if (mResponsiveSelector &&
mResponsiveSelector->Content() == this) {
mResponsiveSelector->SetDefaultSource(aValue);
}
QueueImageLoadTask(true);
} else if (aNotify) {
// If aNotify is false, we are coming from the parser or some such place;
// we'll get bound after all the attributes have been set, so we'll do the
// sync image load from BindToTree. Skip the LoadImage call in that case.
// Note that this sync behavior is partially removed from the spec, bug 1076583
// A hack to get animations to reset. See bug 594771.
mNewRequestsWillNeedAnimationReset = true;
// Force image loading here, so that we'll try to load the image from
// network if it's set to be not cacheable... If we change things so that
// the state gets in Element's attr-setting happen around this
// LoadImage call, we could start passing false instead of aNotify
// here.
LoadImage(aValue, true, aNotify, eImageLoadType_Normal);
mNewRequestsWillNeedAnimationReset = false;
}
}
return nsGenericHTMLElement::SetAttr(aNameSpaceID, aName, aPrefix, aValue,
aNotify);
}
nsresult
HTMLImageElement::BindToTree(nsIDocument* aDocument, nsIContent* aParent,
nsIContent* aBindingParent,
bool aCompileEventHandlers)
{
nsresult rv = nsGenericHTMLElement::BindToTree(aDocument, aParent,
aBindingParent,
aCompileEventHandlers);
NS_ENSURE_SUCCESS(rv, rv);
nsImageLoadingContent::BindToTree(aDocument, aParent, aBindingParent,
aCompileEventHandlers);
if (aParent) {
UpdateFormOwner();
}
if (HaveSrcsetOrInPicture()) {
if (aDocument && !mInDocResponsiveContent) {
aDocument->AddResponsiveContent(this);
mInDocResponsiveContent = true;
}
bool forceLoadEvent = HTMLPictureElement::IsPictureEnabled() &&
aParent && aParent->IsHTMLElement(nsGkAtoms::picture);
QueueImageLoadTask(forceLoadEvent);
} else if (!InResponsiveMode() &&
HasAttr(kNameSpaceID_None, nsGkAtoms::src)) {
// We skip loading when our attributes were set from parser land,
// so trigger a aForce=false load now to check if things changed.
// This isn't necessary for responsive mode, since creating the
// image load task is asynchronous we don't need to take special
// care to avoid doing so when being filled by the parser.
// FIXME: Bug 660963 it would be nice if we could just have
// ClearBrokenState update our state and do it fast...
ClearBrokenState();
RemoveStatesSilently(NS_EVENT_STATE_BROKEN);
// We still act synchronously for the non-responsive case (Bug
// 1076583), but still need to delay if it is unsafe to run
// script.
// If loading is temporarily disabled, don't even launch MaybeLoadImage.
// Otherwise MaybeLoadImage may run later when someone has reenabled
// loading.
if (LoadingEnabled()) {
nsContentUtils::AddScriptRunner(
NS_NewRunnableMethod(this, &HTMLImageElement::MaybeLoadImage));
}
}
return rv;
}
void
HTMLImageElement::UnbindFromTree(bool aDeep, bool aNullParent)
{
if (mForm) {
if (aNullParent || !FindAncestorForm(mForm)) {
ClearForm(true);
} else {
UnsetFlags(MAYBE_ORPHAN_FORM_ELEMENT);
}
}
if (mInDocResponsiveContent) {
nsIDocument* doc = GetOurOwnerDoc();
MOZ_ASSERT(doc);
if (doc) {
doc->RemoveResponsiveContent(this);
mInDocResponsiveContent = false;
}
}
if (GetParent() &&
GetParent()->IsHTMLElement(nsGkAtoms::picture) &&
HTMLPictureElement::IsPictureEnabled()) {
// Being removed from picture re-triggers selection, even if we
// weren't using a <source> peer
if (aNullParent) {
QueueImageLoadTask(true);
}
}
nsImageLoadingContent::UnbindFromTree(aDeep, aNullParent);
nsGenericHTMLElement::UnbindFromTree(aDeep, aNullParent);
}
void
HTMLImageElement::UpdateFormOwner()
{
if (!mForm) {
mForm = FindAncestorForm();
}
if (mForm && !HasFlag(ADDED_TO_FORM)) {
// Now we need to add ourselves to the form
nsAutoString nameVal, idVal;
GetAttr(kNameSpaceID_None, nsGkAtoms::name, nameVal);
GetAttr(kNameSpaceID_None, nsGkAtoms::id, idVal);
SetFlags(ADDED_TO_FORM);
mForm->AddImageElement(this);
if (!nameVal.IsEmpty()) {
mForm->AddImageElementToTable(this, nameVal);
}
if (!idVal.IsEmpty()) {
mForm->AddImageElementToTable(this, idVal);
}
}
}
void
HTMLImageElement::MaybeLoadImage()
{
// Our base URI may have changed, or we may have had responsive parameters
// change while not bound to the tree. Re-parse src/srcset and call LoadImage,
// which is a no-op if it resolves to the same effective URI without aForce.
// Note, check LoadingEnabled() after LoadImage call.
LoadSelectedImage(false, true, false);
if (!LoadingEnabled()) {
CancelImageRequests(true);
}
}
EventStates
HTMLImageElement::IntrinsicState() const
{
return nsGenericHTMLElement::IntrinsicState() |
nsImageLoadingContent::ImageState();
}
// static
already_AddRefed<HTMLImageElement>
HTMLImageElement::Image(const GlobalObject& aGlobal,
const Optional<uint32_t>& aWidth,
const Optional<uint32_t>& aHeight,
ErrorResult& aError)
{
nsCOMPtr<nsPIDOMWindow> win = do_QueryInterface(aGlobal.GetAsSupports());
nsIDocument* doc;
if (!win || !(doc = win->GetExtantDoc())) {
aError.Throw(NS_ERROR_FAILURE);
return nullptr;
}
already_AddRefed<mozilla::dom::NodeInfo> nodeInfo =
doc->NodeInfoManager()->GetNodeInfo(nsGkAtoms::img, nullptr,
kNameSpaceID_XHTML,
nsIDOMNode::ELEMENT_NODE);
RefPtr<HTMLImageElement> img = new HTMLImageElement(nodeInfo);
if (aWidth.WasPassed()) {
img->SetWidth(aWidth.Value(), aError);
if (aError.Failed()) {
return nullptr;
}
if (aHeight.WasPassed()) {
img->SetHeight(aHeight.Value(), aError);
if (aError.Failed()) {
return nullptr;
}
}
}
return img.forget();
}
uint32_t
HTMLImageElement::NaturalHeight()
{
uint32_t height;
nsresult rv = nsImageLoadingContent::GetNaturalHeight(&height);
if (NS_FAILED(rv)) {
MOZ_ASSERT(false, "GetNaturalHeight should not fail");
return 0;
}
if (mResponsiveSelector) {
double density = mResponsiveSelector->GetSelectedImageDensity();
MOZ_ASSERT(density >= 0.0);
height = NSToIntRound(double(height) / density);
height = std::max(height, 0u);
}
return height;
}
NS_IMETHODIMP
HTMLImageElement::GetNaturalHeight(uint32_t* aNaturalHeight)
{
*aNaturalHeight = NaturalHeight();
return NS_OK;
}
uint32_t
HTMLImageElement::NaturalWidth()
{
uint32_t width;
nsresult rv = nsImageLoadingContent::GetNaturalWidth(&width);
if (NS_FAILED(rv)) {
MOZ_ASSERT(false, "GetNaturalWidth should not fail");
return 0;
}
if (mResponsiveSelector) {
double density = mResponsiveSelector->GetSelectedImageDensity();
MOZ_ASSERT(density >= 0.0);
width = NSToIntRound(double(width) / density);
width = std::max(width, 0u);
}
return width;
}
NS_IMETHODIMP
HTMLImageElement::GetNaturalWidth(uint32_t* aNaturalWidth)
{
*aNaturalWidth = NaturalWidth();
return NS_OK;
}
nsresult
HTMLImageElement::CopyInnerTo(Element* aDest)
{
bool destIsStatic = aDest->OwnerDoc()->IsStaticDocument();
auto dest = static_cast<HTMLImageElement*>(aDest);
if (destIsStatic) {
CreateStaticImageClone(dest);
}
nsresult rv = nsGenericHTMLElement::CopyInnerTo(aDest);
if (NS_FAILED(rv)) {
return rv;
}
if (!destIsStatic) {
// In SetAttr (called from nsGenericHTMLElement::CopyInnerTo), dest skipped
// doing the image load because we passed in false for aNotify. But we
// really do want it to do the load, so set it up to happen once the cloning
// reaches a stable state.
if (!dest->InResponsiveMode() &&
dest->HasAttr(kNameSpaceID_None, nsGkAtoms::src)) {
nsContentUtils::AddScriptRunner(
NS_NewRunnableMethod(dest, &HTMLImageElement::MaybeLoadImage));
}
}
return NS_OK;
}
CORSMode
HTMLImageElement::GetCORSMode()
{
return AttrValueToCORSMode(GetParsedAttr(nsGkAtoms::crossorigin));
}
JSObject*
HTMLImageElement::WrapNode(JSContext* aCx, JS::Handle<JSObject*> aGivenProto)
{
return HTMLImageElementBinding::Wrap(aCx, this, aGivenProto);
}
#ifdef DEBUG
nsIDOMHTMLFormElement*
HTMLImageElement::GetForm() const
{
return mForm;
}
#endif
void
HTMLImageElement::SetForm(nsIDOMHTMLFormElement* aForm)
{
NS_PRECONDITION(aForm, "Don't pass null here");
NS_ASSERTION(!mForm,
"We don't support switching from one non-null form to another.");
mForm = static_cast<HTMLFormElement*>(aForm);
}
void
HTMLImageElement::ClearForm(bool aRemoveFromForm)
{
NS_ASSERTION((mForm != nullptr) == HasFlag(ADDED_TO_FORM),
"Form control should have had flag set correctly");
if (!mForm) {
return;
}
if (aRemoveFromForm) {
nsAutoString nameVal, idVal;
GetAttr(kNameSpaceID_None, nsGkAtoms::name, nameVal);
GetAttr(kNameSpaceID_None, nsGkAtoms::id, idVal);
mForm->RemoveImageElement(this);
if (!nameVal.IsEmpty()) {
mForm->RemoveImageElementFromTable(this, nameVal,
HTMLFormElement::ElementRemoved);
}
if (!idVal.IsEmpty()) {
mForm->RemoveImageElementFromTable(this, idVal,
HTMLFormElement::ElementRemoved);
}
}
UnsetFlags(ADDED_TO_FORM);
mForm = nullptr;
}
void
HTMLImageElement::QueueImageLoadTask(bool aAlwaysLoad)
{
// If loading is temporarily disabled, we don't want to queue tasks
// that may then run when loading is re-enabled.
if (!LoadingEnabled() || !this->OwnerDoc()->IsCurrentActiveDocument()) {
return;
}
nsCOMPtr<nsIRunnable> task = new ImageLoadTask(this, aAlwaysLoad);
// The task checks this to determine if it was the last
// queued event, and so earlier tasks are implicitly canceled.
mPendingImageLoadTask = task;
nsContentUtils::RunInStableState(task.forget());
}
bool
HTMLImageElement::HaveSrcsetOrInPicture()
{
if (IsSrcsetEnabled() && HasAttr(kNameSpaceID_None, nsGkAtoms::srcset)) {
return true;
}
if (!HTMLPictureElement::IsPictureEnabled()) {
return false;
}
Element *parent = nsINode::GetParentElement();
return (parent && parent->IsHTMLElement(nsGkAtoms::picture));
}
bool
HTMLImageElement::InResponsiveMode()
{
// When we lose srcset or leave a <picture> element, the fallback to img.src
// will happen from the microtask, and we should behave responsively in the
// interim
return mResponsiveSelector ||
mPendingImageLoadTask ||
HaveSrcsetOrInPicture();
}
nsresult
HTMLImageElement::LoadSelectedImage(bool aForce, bool aNotify, bool aAlwaysLoad)
{
nsresult rv = NS_ERROR_FAILURE;
if (aForce) {
// In responsive mode we generally want to re-run the full
// selection algorithm whenever starting a new load, per
// spec. This also causes us to re-resolve the URI as appropriate.
if (!UpdateResponsiveSource() && !aAlwaysLoad) {
return NS_OK;
}
}
if (mResponsiveSelector) {
nsCOMPtr<nsIURI> url = mResponsiveSelector->GetSelectedImageURL();
if (url) {
rv = LoadImage(url, aForce, aNotify, eImageLoadType_Imageset);
}
} else {
nsAutoString src;
if (!GetAttr(kNameSpaceID_None, nsGkAtoms::src, src)) {
CancelImageRequests(aNotify);
rv = NS_OK;
} else {
// If we have a srcset attribute or are in a <picture> element,
// we always use the Imageset load type, even if we parsed no
// valid responsive sources from either, per spec.
rv = LoadImage(src, aForce, aNotify,
HaveSrcsetOrInPicture() ? eImageLoadType_Imageset
: eImageLoadType_Normal);
}
}
if (NS_FAILED(rv)) {
CancelImageRequests(aNotify);
}
return rv;
}
void
HTMLImageElement::PictureSourceSrcsetChanged(nsIContent *aSourceNode,
const nsAString& aNewValue,
bool aNotify)
{
bool isSelf = aSourceNode == this;
if (!IsSrcsetEnabled() ||
(!isSelf && !HTMLPictureElement::IsPictureEnabled())) {
return;
}
MOZ_ASSERT(isSelf || IsPreviousSibling(aSourceNode, this),
"Should not be getting notifications for non-previous-siblings");
nsIContent *currentSrc =
mResponsiveSelector ? mResponsiveSelector->Content() : nullptr;
if (aSourceNode == currentSrc) {
// We're currently using this node as our responsive selector
// source.
mResponsiveSelector->SetCandidatesFromSourceSet(aNewValue);
}
if (!mInDocResponsiveContent && IsInComposedDoc()) {
nsIDocument* doc = GetOurOwnerDoc();
if (doc) {
doc->AddResponsiveContent(this);
mInDocResponsiveContent = true;
}
}
// This always triggers the image update steps per the spec, even if
// we are not using this source.
QueueImageLoadTask(true);
}
void
HTMLImageElement::PictureSourceSizesChanged(nsIContent *aSourceNode,
const nsAString& aNewValue,
bool aNotify)
{
if (!HTMLPictureElement::IsPictureEnabled()) {
return;
}
MOZ_ASSERT(aSourceNode == this ||
IsPreviousSibling(aSourceNode, this),
"Should not be getting notifications for non-previous-siblings");
nsIContent *currentSrc =
mResponsiveSelector ? mResponsiveSelector->Content() : nullptr;
if (aSourceNode == currentSrc) {
// We're currently using this node as our responsive selector
// source.
mResponsiveSelector->SetSizesFromDescriptor(aNewValue);
}
// This always triggers the image update steps per the spec, even if
// we are not using this source.
QueueImageLoadTask(true);
}
void
HTMLImageElement::PictureSourceMediaOrTypeChanged(nsIContent *aSourceNode,
bool aNotify)
{
if (!HTMLPictureElement::IsPictureEnabled()) {
return;
}
MOZ_ASSERT(IsPreviousSibling(aSourceNode, this),
"Should not be getting notifications for non-previous-siblings");
// This always triggers the image update steps per the spec, even if
// we are not switching to/from this source
QueueImageLoadTask(true);
}
void
HTMLImageElement::PictureSourceAdded(nsIContent *aSourceNode)
{
if (!HTMLPictureElement::IsPictureEnabled()) {
return;
}
QueueImageLoadTask(true);
}
void
HTMLImageElement::PictureSourceRemoved(nsIContent *aSourceNode)
{
if (!HTMLPictureElement::IsPictureEnabled()) {
return;
}
QueueImageLoadTask(true);
}
bool
HTMLImageElement::UpdateResponsiveSource()
{
bool hadSelector = !!mResponsiveSelector;
if (!IsSrcsetEnabled()) {
mResponsiveSelector = nullptr;
return hadSelector;
}
nsIContent *currentSource =
mResponsiveSelector ? mResponsiveSelector->Content() : nullptr;
bool pictureEnabled = HTMLPictureElement::IsPictureEnabled();
Element *parent = pictureEnabled ? nsINode::GetParentElement() : nullptr;
nsINode *candidateSource = nullptr;
if (parent && parent->IsHTMLElement(nsGkAtoms::picture)) {
// Walk source nodes previous to ourselves
candidateSource = parent->GetFirstChild();
} else {
candidateSource = this;
}
while (candidateSource) {
if (candidateSource == currentSource) {
// found no better source before current, re-run selection on
// that and keep it if it's still usable.
bool changed = mResponsiveSelector->SelectImage(true);
if (mResponsiveSelector->NumCandidates()) {
bool isUsableCandidate = true;
// an otherwise-usable source element may still have a media query that may not
// match any more.
if (candidateSource->IsHTMLElement(nsGkAtoms::source) &&
!SourceElementMatches(candidateSource->AsContent())) {
isUsableCandidate = false;
}
if (isUsableCandidate) {
return changed;
}
}
// no longer valid
mResponsiveSelector = nullptr;
if (candidateSource == this) {
// No further possibilities
break;
}
} else if (candidateSource == this) {
// We are the last possible source
if (!TryCreateResponsiveSelector(candidateSource->AsContent())) {
// Failed to find any source
mResponsiveSelector = nullptr;
}
break;
} else if (candidateSource->IsHTMLElement(nsGkAtoms::source) &&
TryCreateResponsiveSelector(candidateSource->AsContent())) {
// This led to a valid source, stop
break;
}
candidateSource = candidateSource->GetNextSibling();
}
if (!candidateSource) {
// Ran out of siblings without finding ourself, e.g. XBL magic.
mResponsiveSelector = nullptr;
}
return !hadSelector || mResponsiveSelector;
}
/*static */ bool
HTMLImageElement::SupportedPictureSourceType(const nsAString& aType)
{
return
imgLoader::SupportImageWithMimeType(NS_ConvertUTF16toUTF8(aType).get(),
AcceptedMimeTypes::IMAGES_AND_DOCUMENTS);
}
bool
HTMLImageElement::SourceElementMatches(nsIContent* aSourceNode)
{
MOZ_ASSERT(aSourceNode->IsHTMLElement(nsGkAtoms::source));
DebugOnly<Element *> parent(nsINode::GetParentElement());
MOZ_ASSERT(parent && parent->IsHTMLElement(nsGkAtoms::picture));
MOZ_ASSERT(IsPreviousSibling(aSourceNode, this));
MOZ_ASSERT(HTMLPictureElement::IsPictureEnabled());
// Check media and type
HTMLSourceElement *src = static_cast<HTMLSourceElement*>(aSourceNode);
if (!src->MatchesCurrentMedia()) {
return false;
}
nsAutoString type;
if (aSourceNode->GetAttr(kNameSpaceID_None, nsGkAtoms::type, type) &&
!SupportedPictureSourceType(type)) {
return false;
}
return true;
}
bool
HTMLImageElement::TryCreateResponsiveSelector(nsIContent *aSourceNode,
const nsAString *aSrcset,
const nsAString *aSizes)
{
if (!IsSrcsetEnabled()) {
return false;
}
bool pictureEnabled = HTMLPictureElement::IsPictureEnabled();
// Skip if this is not a <source> with matching media query
bool isSourceTag = aSourceNode->IsHTMLElement(nsGkAtoms::source);
if (isSourceTag) {
if (!SourceElementMatches(aSourceNode)) {
return false;
}
} else if (aSourceNode->IsHTMLElement(nsGkAtoms::img)) {
// Otherwise this is the <img> tag itself
MOZ_ASSERT(aSourceNode == this);
}
// Skip if has no srcset or an empty srcset
nsString srcset;
if (aSrcset) {
srcset = *aSrcset;
} else if (!aSourceNode->GetAttr(kNameSpaceID_None, nsGkAtoms::srcset,
srcset)) {
return false;
}
if (srcset.IsEmpty()) {
return false;
}
// Try to parse
RefPtr<ResponsiveImageSelector> sel = new ResponsiveImageSelector(aSourceNode);
if (!sel->SetCandidatesFromSourceSet(srcset)) {
// No possible candidates, don't need to bother parsing sizes
return false;
}
if (pictureEnabled && aSizes) {
sel->SetSizesFromDescriptor(*aSizes);
} else if (pictureEnabled) {
nsAutoString sizes;
aSourceNode->GetAttr(kNameSpaceID_None, nsGkAtoms::sizes, sizes);
sel->SetSizesFromDescriptor(sizes);
}
// If this is the <img> tag, also pull in src as the default source
if (!isSourceTag) {
MOZ_ASSERT(aSourceNode == this);
nsAutoString src;
if (GetAttr(kNameSpaceID_None, nsGkAtoms::src, src) && !src.IsEmpty()) {
sel->SetDefaultSource(src);
}
}
mResponsiveSelector = sel;
return true;
}
/* static */ bool
HTMLImageElement::SelectSourceForTagWithAttrs(nsIDocument *aDocument,
bool aIsSourceTag,
const nsAString& aSrcAttr,
const nsAString& aSrcsetAttr,
const nsAString& aSizesAttr,
const nsAString& aTypeAttr,
const nsAString& aMediaAttr,
nsAString& aResult)
{
MOZ_ASSERT(aIsSourceTag || (aTypeAttr.IsEmpty() && aMediaAttr.IsEmpty()),
"Passing type or media attrs makes no sense without aIsSourceTag");
MOZ_ASSERT(!aIsSourceTag || aSrcAttr.IsEmpty(),
"Passing aSrcAttr makes no sense with aIsSourceTag set");
bool pictureEnabled = HTMLPictureElement::IsPictureEnabled();
if (aIsSourceTag && !pictureEnabled) {
return false;
}
if (!IsSrcsetEnabled() || aSrcsetAttr.IsEmpty()) {
if (!aIsSourceTag) {
// For an <img> with no srcset, we would always select the src attr.
aResult.Assign(aSrcAttr);
return true;
}
// Otherwise, a <source> without srcset is never selected
return false;
}
// Would not consider source tags with unsupported media or type
if (aIsSourceTag &&
((!aMediaAttr.IsVoid() &&
!HTMLSourceElement::WouldMatchMediaForDocument(aMediaAttr, aDocument)) ||
(!aTypeAttr.IsVoid() &&
!SupportedPictureSourceType(aTypeAttr)))) {
return false;
}
// Using srcset or picture <source>, build a responsive selector for this tag.
RefPtr<ResponsiveImageSelector> sel =
new ResponsiveImageSelector(aDocument);
sel->SetCandidatesFromSourceSet(aSrcsetAttr);
if (pictureEnabled && !aSizesAttr.IsEmpty()) {
sel->SetSizesFromDescriptor(aSizesAttr);
}
if (!aIsSourceTag) {
sel->SetDefaultSource(aSrcAttr);
}
if (sel->GetSelectedImageURLSpec(aResult)) {
return true;
}
if (!aIsSourceTag) {
// <img> tag with no match would definitively load nothing.
aResult.Truncate();
return true;
}
// <source> tags with no match would leave source yet-undetermined.
return false;
}
void
HTMLImageElement::DestroyContent()
{
mResponsiveSelector = nullptr;
nsGenericHTMLElement::DestroyContent();
}
void
HTMLImageElement::MediaFeatureValuesChanged()
{
QueueImageLoadTask(false);
}
void
HTMLImageElement::FlushUseCounters()
{
nsCOMPtr<imgIRequest> request;
GetRequest(CURRENT_REQUEST, getter_AddRefs(request));
nsCOMPtr<imgIContainer> container;
request->GetImage(getter_AddRefs(container));
static_cast<image::Image*>(container.get())->ReportUseCounters();
}
} // namespace dom
} // namespace mozilla