Bumping gaia.json for 8 gaia revision(s) a=gaia-bump
[gecko.git] / dom / base / nsImageLoadingContent.h
blob6719ffed6f644c3fbc44e80318e64262d9957cb3
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 // vim: ft=cpp tw=78 sw=2 et ts=2
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 /*
8 * A base class which implements nsIImageLoadingContent and can be
9 * subclassed by various content nodes that want to provide image
10 * loading functionality (eg <img>, <object>, etc).
13 #ifndef nsImageLoadingContent_h__
14 #define nsImageLoadingContent_h__
16 #include "imgINotificationObserver.h"
17 #include "imgIOnloadBlocker.h"
18 #include "mozilla/CORSMode.h"
19 #include "mozilla/EventStates.h"
20 #include "nsCOMPtr.h"
21 #include "nsIImageLoadingContent.h"
22 #include "nsIRequest.h"
23 #include "mozilla/ErrorResult.h"
24 #include "nsAutoPtr.h"
25 #include "nsIContentPolicy.h"
26 #include "mozilla/dom/BindingDeclarations.h"
28 class nsIURI;
29 class nsIDocument;
30 class imgILoader;
31 class nsIIOService;
32 class nsPresContext;
33 class nsIContent;
34 class imgRequestProxy;
36 #ifdef LoadImage
37 // Undefine LoadImage to prevent naming conflict with Windows.
38 #undef LoadImage
39 #endif
41 class nsImageLoadingContent : public nsIImageLoadingContent,
42 public imgIOnloadBlocker
44 /* METHODS */
45 public:
46 nsImageLoadingContent();
47 virtual ~nsImageLoadingContent();
49 NS_DECL_IMGINOTIFICATIONOBSERVER
50 NS_DECL_NSIIMAGELOADINGCONTENT
51 NS_DECL_IMGIONLOADBLOCKER
53 // Web IDL binding methods.
54 // Note that the XPCOM SetLoadingEnabled, AddObserver, RemoveObserver,
55 // ForceImageState methods are OK for Web IDL bindings to use as well,
56 // since none of them throw when called via the Web IDL bindings.
58 bool LoadingEnabled() const { return mLoadingEnabled; }
59 int16_t ImageBlockingStatus() const
61 return mImageBlockingStatus;
63 already_AddRefed<imgIRequest>
64 GetRequest(int32_t aRequestType, mozilla::ErrorResult& aError);
65 int32_t
66 GetRequestType(imgIRequest* aRequest, mozilla::ErrorResult& aError);
67 already_AddRefed<nsIURI> GetCurrentURI(mozilla::ErrorResult& aError);
68 void ForceReload(const mozilla::dom::Optional<bool>& aNotify,
69 mozilla::ErrorResult& aError);
71 // XPCOM [optional] syntax helper
72 nsresult ForceReload(bool aNotify = true) {
73 return ForceReload(aNotify, 1);
76 /**
77 * Used to initialize content with a previously opened channel. Assumes
78 * eImageLoadType_Normal
80 already_AddRefed<nsIStreamListener>
81 LoadImageWithChannel(nsIChannel* aChannel, mozilla::ErrorResult& aError);
83 protected:
84 enum ImageLoadType {
85 // Most normal image loads
86 eImageLoadType_Normal,
87 // From a <img srcset> or <picture> context. Affects type given to content
88 // policy.
89 eImageLoadType_Imageset
92 /**
93 * LoadImage is called by subclasses when the appropriate
94 * attributes (eg 'src' for <img> tags) change. The string passed
95 * in is the new uri string; this consolidates the code for getting
96 * the charset, constructing URI objects, and any other incidentals
97 * into this superclass.
99 * @param aNewURI the URI spec to be loaded (may be a relative URI)
100 * @param aForce If true, make sure to load the URI. If false, only
101 * load if the URI is different from the currently loaded URI.
102 * @param aNotify If true, nsIDocumentObserver state change notifications
103 * will be sent as needed.
104 * @param aImageLoadType The ImageLoadType for this request
106 nsresult LoadImage(const nsAString& aNewURI, bool aForce,
107 bool aNotify, ImageLoadType aImageLoadType);
110 * ImageState is called by subclasses that are computing their content state.
111 * The return value will have the NS_EVENT_STATE_BROKEN,
112 * NS_EVENT_STATE_USERDISABLED, and NS_EVENT_STATE_SUPPRESSED bits set as
113 * needed. Note that this state assumes that this node is "trying" to be an
114 * image (so for example complete lack of attempt to load an image will lead
115 * to NS_EVENT_STATE_BROKEN being set). Subclasses that are not "trying" to
116 * be an image (eg an HTML <input> of type other than "image") should just
117 * not call this method when computing their intrinsic state.
119 mozilla::EventStates ImageState() const;
122 * LoadImage is called by subclasses when the appropriate
123 * attributes (eg 'src' for <img> tags) change. If callers have an
124 * URI object already available, they should use this method.
126 * @param aNewURI the URI to be loaded
127 * @param aForce If true, make sure to load the URI. If false, only
128 * load if the URI is different from the currently loaded URI.
129 * @param aNotify If true, nsIDocumentObserver state change notifications
130 * will be sent as needed.
131 * @param aImageLoadType The ImageLoadType for this request
132 * @param aDocument Optional parameter giving the document this node is in.
133 * This is purely a performance optimization.
134 * @param aLoadFlags Optional parameter specifying load flags to use for
135 * the image load
137 nsresult LoadImage(nsIURI* aNewURI, bool aForce, bool aNotify,
138 ImageLoadType aImageLoadType, nsIDocument* aDocument = nullptr,
139 nsLoadFlags aLoadFlags = nsIRequest::LOAD_NORMAL);
142 * helpers to get the document for this content (from the nodeinfo
143 * and such). Not named GetOwnerDoc/GetCurrentDoc to prevent ambiguous
144 * method names in subclasses
146 * @return the document we belong to
148 nsIDocument* GetOurOwnerDoc();
149 nsIDocument* GetOurCurrentDoc();
152 * Helper function to get the frame associated with this content. Not named
153 * GetPrimaryFrame to prevent ambiguous method names in subclasses.
155 * @return The frame which we belong to, or nullptr if it doesn't exist.
157 nsIFrame* GetOurPrimaryFrame();
160 * Helper function to get the PresContext associated with this content's
161 * frame. Not named GetPresContext to prevent ambiguous method names in
162 * subclasses.
164 * @return The nsPresContext associated with our frame, or nullptr if either
165 * the frame doesn't exist, or the frame's prescontext doesn't exist.
167 nsPresContext* GetFramePresContext();
170 * CancelImageRequests is called by subclasses when they want to
171 * cancel all image requests (for example when the subclass is
172 * somehow not an image anymore).
174 void CancelImageRequests(bool aNotify);
177 * UseAsPrimaryRequest is called by subclasses when they have an existing
178 * imgRequestProxy that they want this nsImageLoadingContent to use. This may
179 * effectively be called instead of LoadImage or LoadImageWithChannel.
180 * If aNotify is true, this method will notify on state changes.
182 nsresult UseAsPrimaryRequest(imgRequestProxy* aRequest, bool aNotify,
183 ImageLoadType aImageLoadType);
186 * Derived classes of nsImageLoadingContent MUST call
187 * DestroyImageLoadingContent from their destructor, or earlier. It
188 * does things that cannot be done in ~nsImageLoadingContent because
189 * they rely on being able to QueryInterface to other derived classes,
190 * which cannot happen once the derived class destructor has started
191 * calling the base class destructors.
193 void DestroyImageLoadingContent();
195 void ClearBrokenState() { mBroken = false; }
197 // Sets blocking state only if the desired state is different from the
198 // current one. See the comment for mBlockingOnload for more information.
199 void SetBlockingOnload(bool aBlocking);
202 * Returns the CORS mode that will be used for all future image loads. The
203 * default implementation returns CORS_NONE unconditionally.
205 virtual mozilla::CORSMode GetCORSMode();
207 // Subclasses are *required* to call BindToTree/UnbindFromTree.
208 void BindToTree(nsIDocument* aDocument, nsIContent* aParent,
209 nsIContent* aBindingParent, bool aCompileEventHandlers);
210 void UnbindFromTree(bool aDeep, bool aNullParent);
212 nsresult OnLoadComplete(imgIRequest* aRequest, nsresult aStatus);
213 void OnUnlockedDraw();
214 nsresult OnImageIsAnimated(imgIRequest *aRequest);
216 // The nsContentPolicyType we would use for this ImageLoadType
217 static nsContentPolicyType PolicyTypeForLoad(ImageLoadType aImageLoadType);
219 private:
221 * Struct used to manage the image observers.
223 struct ImageObserver {
224 explicit ImageObserver(imgINotificationObserver* aObserver);
225 ~ImageObserver();
227 nsCOMPtr<imgINotificationObserver> mObserver;
228 ImageObserver* mNext;
232 * Struct to report state changes
234 struct AutoStateChanger {
235 AutoStateChanger(nsImageLoadingContent* aImageContent,
236 bool aNotify) :
237 mImageContent(aImageContent),
238 mNotify(aNotify)
240 mImageContent->mStateChangerDepth++;
242 ~AutoStateChanger()
244 mImageContent->mStateChangerDepth--;
245 mImageContent->UpdateImageState(mNotify);
248 nsImageLoadingContent* mImageContent;
249 bool mNotify;
252 friend struct AutoStateChanger;
255 * UpdateImageState recomputes the current state of this image loading
256 * content and updates what ImageState() returns accordingly. It will also
257 * fire a ContentStatesChanged() notification as needed if aNotify is true.
259 void UpdateImageState(bool aNotify);
262 * Method to fire an event once we know what's going on with the image load.
264 * @param aEventType "load" or "error" depending on how things went
266 nsresult FireEvent(const nsAString& aEventType);
268 protected:
270 * Method to create an nsIURI object from the given string (will
271 * handle getting the right charset, base, etc). You MUST pass in a
272 * non-null document to this function.
274 * @param aSpec the string spec (from an HTML attribute, eg)
275 * @param aDocument the document we belong to
276 * @return the URI we want to be loading
278 nsresult StringToURI(const nsAString& aSpec, nsIDocument* aDocument,
279 nsIURI** aURI);
281 void CreateStaticImageClone(nsImageLoadingContent* aDest) const;
284 * Prepare and returns a reference to the "next request". If there's already
285 * a _usable_ current request (one with SIZE_AVAILABLE), this request is
286 * "pending" until it becomes usable. Otherwise, this becomes the current
287 * request.
289 * @param aImageLoadType The ImageLoadType for this request
291 nsRefPtr<imgRequestProxy>& PrepareNextRequest(ImageLoadType aImageLoadType);
294 * Called when we would normally call PrepareNextRequest(), but the request was
295 * blocked.
297 void SetBlockedRequest(nsIURI* aURI, int16_t aContentDecision);
300 * Returns a COMPtr reference to the current/pending image requests, cleaning
301 * up and canceling anything that was there before. Note that if you just want
302 * to get rid of one of the requests, you should call
303 * Clear*Request(NS_BINDING_ABORTED) instead, since it passes a more appropriate
304 * aReason than Prepare*Request() does (NS_ERROR_IMAGE_SRC_CHANGED).
306 * @param aImageLoadType The ImageLoadType for this request
308 nsRefPtr<imgRequestProxy>& PrepareCurrentRequest(ImageLoadType aImageLoadType);
309 nsRefPtr<imgRequestProxy>& PreparePendingRequest(ImageLoadType aImageLoadType);
312 * Switch our pending request to be our current request.
313 * mPendingRequest must be non-null!
315 void MakePendingRequestCurrent();
318 * Cancels and nulls-out the "current" and "pending" requests if they exist.
320 * @param aNonvisibleAction An action to take if the image is no longer
321 * visible as a result; see |UntrackImage|.
323 void ClearCurrentRequest(nsresult aReason, uint32_t aNonvisibleAction);
324 void ClearPendingRequest(nsresult aReason, uint32_t aNonvisibleAction);
327 * Retrieve a pointer to the 'registered with the refresh driver' flag for
328 * which a particular image request corresponds.
330 * @returns A pointer to the boolean flag for a given image request, or
331 * |nullptr| if the request is not either |mPendingRequest| or
332 * |mCurrentRequest|.
334 bool* GetRegisteredFlagForRequest(imgIRequest* aRequest);
337 * Reset animation of the current request if |mNewRequestsWillNeedAnimationReset|
338 * was true when the request was prepared.
340 void ResetAnimationIfNeeded();
343 * Static helper method to tell us if we have the size of a request. The
344 * image may be null.
346 static bool HaveSize(imgIRequest *aImage);
349 * Adds/Removes a given imgIRequest from our document's tracker.
351 * No-op if aImage is null.
353 * @param aNonvisibleAction What to do if the image's visibility count is now
354 * zero. If ON_NONVISIBLE_NO_ACTION, nothing will be
355 * done. If ON_NONVISIBLE_REQUEST_DISCARD, the image
356 * will be asked to discard its surfaces if possible.
358 void TrackImage(imgIRequest* aImage);
359 void UntrackImage(imgIRequest* aImage,
360 uint32_t aNonvisibleAction = ON_NONVISIBLE_NO_ACTION);
362 /* MEMBERS */
363 nsRefPtr<imgRequestProxy> mCurrentRequest;
364 nsRefPtr<imgRequestProxy> mPendingRequest;
365 uint32_t mCurrentRequestFlags;
366 uint32_t mPendingRequestFlags;
368 enum {
369 // Set if the request needs ResetAnimation called on it.
370 REQUEST_NEEDS_ANIMATION_RESET = 0x00000001U,
371 // Set if the request is blocking onload.
372 REQUEST_BLOCKS_ONLOAD = 0x00000002U,
373 // Set if the request is currently tracked with the document.
374 REQUEST_IS_TRACKED = 0x00000004U,
375 // Set if this is an imageset request, such as from <img srcset> or
376 // <picture>
377 REQUEST_IS_IMAGESET = 0x00000008U
380 // If the image was blocked or if there was an error loading, it's nice to
381 // still keep track of what the URI was despite not having an imgIRequest.
382 // We only maintain this in those situations (in the common case, this is
383 // always null).
384 nsCOMPtr<nsIURI> mCurrentURI;
386 private:
388 * Typically we will have only one observer (our frame in the screen
389 * prescontext), so we want to only make space for one and to
390 * heap-allocate anything past that (saves memory and malloc churn
391 * in the common case). The storage is a linked list, we just
392 * happen to actually hold the first observer instead of a pointer
393 * to it.
395 ImageObserver mObserverList;
398 * When mIsImageStateForced is true, this holds the ImageState that we'll
399 * return in ImageState().
401 mozilla::EventStates mForcedImageState;
403 int16_t mImageBlockingStatus;
404 bool mLoadingEnabled : 1;
407 * When true, we return mForcedImageState from ImageState().
409 bool mIsImageStateForced : 1;
412 * The state we had the last time we checked whether we needed to notify the
413 * document of a state change. These are maintained by UpdateImageState.
415 bool mLoading : 1;
416 bool mBroken : 1;
417 bool mUserDisabled : 1;
418 bool mSuppressed : 1;
419 bool mFireEventsOnDecode : 1;
421 protected:
423 * A hack to get animations to reset, see bug 594771. On requests
424 * that originate from setting .src, we mark them for needing their animation
425 * reset when they are ready. mNewRequestsWillNeedAnimationReset is set to
426 * true while preparing such requests (as a hack around needing to change an
427 * interface), and the other two booleans store which of the current
428 * and pending requests are of the sort that need their animation restarted.
430 bool mNewRequestsWillNeedAnimationReset : 1;
432 private:
433 /* The number of nested AutoStateChangers currently tracking our state. */
434 uint8_t mStateChangerDepth;
436 // Flags to indicate whether each of the current and pending requests are
437 // registered with the refresh driver.
438 bool mCurrentRequestRegistered;
439 bool mPendingRequestRegistered;
441 // True when FrameCreate has been called but FrameDestroy has not.
442 bool mFrameCreateCalled;
444 uint32_t mVisibleCount;
447 #endif // nsImageLoadingContent_h__