Bug 1728955: part 8) Refactor `DisplayErrCode` in Windows' `nsClipboard`. r=masayuki
[gecko.git] / image / imgLoader.h
blob153b45ebbb5e911eb5467815b1b2cd824315e0e1
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 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 #ifndef mozilla_image_imgLoader_h
8 #define mozilla_image_imgLoader_h
10 #include "mozilla/Attributes.h"
11 #include "mozilla/CORSMode.h"
12 #include "mozilla/Mutex.h"
13 #include "mozilla/UniquePtr.h"
15 #include "imgILoader.h"
16 #include "imgICache.h"
17 #include "nsWeakReference.h"
18 #include "nsIContentSniffer.h"
19 #include "nsRefPtrHashtable.h"
20 #include "nsTHashSet.h"
21 #include "nsExpirationTracker.h"
22 #include "ImageCacheKey.h"
23 #include "imgRequest.h"
24 #include "nsIProgressEventSink.h"
25 #include "nsIChannel.h"
26 #include "nsIThreadRetargetableStreamListener.h"
27 #include "imgIRequest.h"
29 class imgLoader;
30 class imgRequestProxy;
31 class imgINotificationObserver;
32 class nsILoadGroup;
33 class imgCacheExpirationTracker;
34 class imgMemoryReporter;
36 namespace mozilla {
37 namespace dom {
38 class Document;
40 } // namespace mozilla
42 class imgCacheEntry {
43 public:
44 imgCacheEntry(imgLoader* loader, imgRequest* request,
45 bool aForcePrincipalCheck);
46 ~imgCacheEntry();
48 nsrefcnt AddRef() {
49 MOZ_ASSERT(int32_t(mRefCnt) >= 0, "illegal refcnt");
50 NS_ASSERT_OWNINGTHREAD(imgCacheEntry);
51 ++mRefCnt;
52 NS_LOG_ADDREF(this, mRefCnt, "imgCacheEntry", sizeof(*this));
53 return mRefCnt;
56 nsrefcnt Release() {
57 MOZ_ASSERT(0 != mRefCnt, "dup release");
58 NS_ASSERT_OWNINGTHREAD(imgCacheEntry);
59 --mRefCnt;
60 NS_LOG_RELEASE(this, mRefCnt, "imgCacheEntry");
61 if (mRefCnt == 0) {
62 mRefCnt = 1; /* stabilize */
63 delete this;
64 return 0;
66 return mRefCnt;
69 uint32_t GetDataSize() const { return mDataSize; }
70 void SetDataSize(uint32_t aDataSize) {
71 int32_t oldsize = mDataSize;
72 mDataSize = aDataSize;
73 UpdateCache(mDataSize - oldsize);
76 int32_t GetTouchedTime() const { return mTouchedTime; }
77 void SetTouchedTime(int32_t time) {
78 mTouchedTime = time;
79 Touch(/* updateTime = */ false);
82 uint32_t GetLoadTime() const { return mLoadTime; }
84 void UpdateLoadTime();
86 uint32_t GetExpiryTime() const { return mExpiryTime; }
87 void SetExpiryTime(uint32_t aExpiryTime) {
88 mExpiryTime = aExpiryTime;
89 Touch();
92 bool GetMustValidate() const { return mMustValidate; }
93 void SetMustValidate(bool aValidate) {
94 mMustValidate = aValidate;
95 Touch();
98 already_AddRefed<imgRequest> GetRequest() const {
99 RefPtr<imgRequest> req = mRequest;
100 return req.forget();
103 bool Evicted() const { return mEvicted; }
105 nsExpirationState* GetExpirationState() { return &mExpirationState; }
107 bool HasNoProxies() const { return mHasNoProxies; }
109 bool ForcePrincipalCheck() const { return mForcePrincipalCheck; }
111 imgLoader* Loader() const { return mLoader; }
113 private: // methods
114 friend class imgLoader;
115 friend class imgCacheQueue;
116 void Touch(bool updateTime = true);
117 void UpdateCache(int32_t diff = 0);
118 void SetEvicted(bool evict) { mEvicted = evict; }
119 void SetHasNoProxies(bool hasNoProxies);
121 // Private, unimplemented copy constructor.
122 imgCacheEntry(const imgCacheEntry&);
124 private: // data
125 nsAutoRefCnt mRefCnt;
126 NS_DECL_OWNINGTHREAD
128 imgLoader* mLoader;
129 RefPtr<imgRequest> mRequest;
130 uint32_t mDataSize;
131 int32_t mTouchedTime;
132 uint32_t mLoadTime;
133 uint32_t mExpiryTime;
134 nsExpirationState mExpirationState;
135 bool mMustValidate : 1;
136 bool mEvicted : 1;
137 bool mHasNoProxies : 1;
138 bool mForcePrincipalCheck : 1;
141 #include <vector>
143 #define NS_IMGLOADER_CID \
144 { /* c1354898-e3fe-4602-88a7-c4520c21cb4e */ \
145 0xc1354898, 0xe3fe, 0x4602, { \
146 0x88, 0xa7, 0xc4, 0x52, 0x0c, 0x21, 0xcb, 0x4e \
150 class imgCacheQueue {
151 public:
152 imgCacheQueue();
153 void Remove(imgCacheEntry*);
154 void Push(imgCacheEntry*);
155 void MarkDirty();
156 bool IsDirty();
157 already_AddRefed<imgCacheEntry> Pop();
158 void Refresh();
159 uint32_t GetSize() const;
160 void UpdateSize(int32_t diff);
161 uint32_t GetNumElements() const;
162 bool Contains(imgCacheEntry* aEntry) const;
163 typedef nsTArray<RefPtr<imgCacheEntry>> queueContainer;
164 typedef queueContainer::iterator iterator;
165 typedef queueContainer::const_iterator const_iterator;
167 iterator begin();
168 const_iterator begin() const;
169 iterator end();
170 const_iterator end() const;
172 private:
173 queueContainer mQueue;
174 bool mDirty;
175 uint32_t mSize;
178 enum class AcceptedMimeTypes : uint8_t {
179 IMAGES,
180 IMAGES_AND_DOCUMENTS,
183 class imgLoader final : public imgILoader,
184 public nsIContentSniffer,
185 public imgICache,
186 public nsSupportsWeakReference,
187 public nsIObserver {
188 virtual ~imgLoader();
190 public:
191 typedef mozilla::image::ImageCacheKey ImageCacheKey;
192 typedef nsRefPtrHashtable<nsGenericHashKey<ImageCacheKey>, imgCacheEntry>
193 imgCacheTable;
194 typedef nsTHashSet<imgRequest*> imgSet;
195 typedef mozilla::Mutex Mutex;
197 NS_DECL_ISUPPORTS
198 NS_DECL_IMGILOADER
199 NS_DECL_NSICONTENTSNIFFER
200 NS_DECL_IMGICACHE
201 NS_DECL_NSIOBSERVER
204 * Get the normal image loader instance that is used by gecko code, creating
205 * it if necessary.
207 static imgLoader* NormalLoader();
210 * Get the Private Browsing image loader instance that is used by gecko code,
211 * creating it if necessary.
213 static imgLoader* PrivateBrowsingLoader();
216 * Gecko code should use NormalLoader() or PrivateBrowsingLoader() to get the
217 * appropriate image loader.
219 * This constructor is public because the XPCOM module code that creates
220 * instances of "@mozilla.org/image/loader;1" / "@mozilla.org/image/cache;1"
221 * for nsIComponentManager.createInstance()/nsIServiceManager.getService()
222 * calls (now only made by add-ons) needs access to it.
224 * XXX We would like to get rid of the nsIServiceManager.getService (and
225 * nsIComponentManager.createInstance) method of creating imgLoader objects,
226 * but there are add-ons that are still using it. These add-ons don't
227 * actually do anything useful with the loaders that they create since nobody
228 * who creates an imgLoader using this method actually QIs to imgILoader and
229 * loads images. They all just QI to imgICache and either call clearCache()
230 * or findEntryProperties(). Since they're doing this on an imgLoader that
231 * has never loaded images, these calls are useless. It seems likely that
232 * the code that is doing this is just legacy code left over from a time when
233 * there was only one imgLoader instance for the entire process. (Nowadays
234 * the correct method to get an imgILoader/imgICache is to call
235 * imgITools::getImgCacheForDocument/imgITools::getImgLoaderForDocument.)
236 * All the same, even though what these add-ons are doing is a no-op,
237 * removing the nsIServiceManager.getService method of creating/getting an
238 * imgLoader objects would cause an exception in these add-ons that could
239 * break things.
241 imgLoader();
242 nsresult Init();
244 bool IsImageAvailable(nsIURI*, nsIPrincipal* aTriggeringPrincipal,
245 mozilla::CORSMode, mozilla::dom::Document*);
247 [[nodiscard]] nsresult LoadImage(
248 nsIURI* aURI, nsIURI* aInitialDocumentURI, nsIReferrerInfo* aReferrerInfo,
249 nsIPrincipal* aLoadingPrincipal, uint64_t aRequestContextID,
250 nsILoadGroup* aLoadGroup, imgINotificationObserver* aObserver,
251 nsINode* aContext, mozilla::dom::Document* aLoadingDocument,
252 nsLoadFlags aLoadFlags, nsISupports* aCacheKey,
253 nsContentPolicyType aContentPolicyType, const nsAString& initiatorType,
254 bool aUseUrgentStartForChannel, bool aLinkPreload,
255 imgRequestProxy** _retval);
257 [[nodiscard]] nsresult LoadImageWithChannel(
258 nsIChannel* channel, imgINotificationObserver* aObserver,
259 mozilla::dom::Document* aLoadingDocument, nsIStreamListener** listener,
260 imgRequestProxy** _retval);
262 static nsresult GetMimeTypeFromContent(const char* aContents,
263 uint32_t aLength,
264 nsACString& aContentType);
267 * Returns true if the given mime type may be interpreted as an image.
269 * Some MIME types may be interpreted as both images and documents. (At the
270 * moment only "image/svg+xml" falls into this category, but there may be more
271 * in the future.) Callers which want this function to return true for such
272 * MIME types should pass AcceptedMimeTypes::IMAGES_AND_DOCUMENTS for
273 * @aAccept.
275 * @param aMimeType The MIME type to evaluate.
276 * @param aAcceptedMimeTypes Which kinds of MIME types to treat as images.
278 static bool SupportImageWithMimeType(
279 const nsACString&, AcceptedMimeTypes aAccept = AcceptedMimeTypes::IMAGES);
281 static void GlobalInit(); // for use by the factory
282 static void Shutdown(); // for use by the factory
283 static void ShutdownMemoryReporter();
285 nsresult ClearChromeImageCache();
286 nsresult ClearImageCache();
287 void MinimizeCaches();
289 nsresult InitCache();
291 bool RemoveFromCache(const ImageCacheKey& aKey);
293 // Enumeration describing if a given entry is in the cache queue or not.
294 // There are some cases we know the entry is definitely not in the queue.
295 enum class QueueState { MaybeExists, AlreadyRemoved };
297 bool RemoveFromCache(imgCacheEntry* entry,
298 QueueState aQueueState = QueueState::MaybeExists);
300 bool PutIntoCache(const ImageCacheKey& aKey, imgCacheEntry* aEntry);
302 void AddToUncachedImages(imgRequest* aRequest);
303 void RemoveFromUncachedImages(imgRequest* aRequest);
305 // Returns true if we should prefer evicting cache entry |two| over cache
306 // entry |one|.
307 // This mixes units in the worst way, but provides reasonable results.
308 inline static bool CompareCacheEntries(const RefPtr<imgCacheEntry>& one,
309 const RefPtr<imgCacheEntry>& two) {
310 if (!one) {
311 return false;
313 if (!two) {
314 return true;
317 const double sizeweight = 1.0 - sCacheTimeWeight;
319 // We want large, old images to be evicted first (depending on their
320 // relative weights). Since a larger time is actually newer, we subtract
321 // time's weight, so an older image has a larger weight.
322 double oneweight = double(one->GetDataSize()) * sizeweight -
323 double(one->GetTouchedTime()) * sCacheTimeWeight;
324 double twoweight = double(two->GetDataSize()) * sizeweight -
325 double(two->GetTouchedTime()) * sCacheTimeWeight;
327 return oneweight < twoweight;
330 void VerifyCacheSizes();
332 nsresult RemoveEntriesInternal(nsIPrincipal* aPrincipal,
333 const nsACString* aBaseDomain);
335 // The image loader maintains a hash table of all imgCacheEntries. However,
336 // only some of them will be evicted from the cache: those who have no
337 // imgRequestProxies watching their imgRequests.
339 // Once an imgRequest has no imgRequestProxies, it should notify us by
340 // calling HasNoObservers(), and null out its cache entry pointer.
342 // Upon having a proxy start observing again, it should notify us by calling
343 // HasObservers(). The request's cache entry will be re-set before this
344 // happens, by calling imgRequest::SetCacheEntry() when an entry with no
345 // observers is re-requested.
346 bool SetHasNoProxies(imgRequest* aRequest, imgCacheEntry* aEntry);
347 bool SetHasProxies(imgRequest* aRequest);
349 private: // methods
350 static already_AddRefed<imgLoader> CreateImageLoader();
352 bool PreferLoadFromCache(nsIURI* aURI) const;
354 bool ValidateEntry(
355 imgCacheEntry* aEntry, nsIURI* aURI, nsIURI* aInitialDocumentURI,
356 nsIReferrerInfo* aReferrerInfo, nsILoadGroup* aLoadGroup,
357 imgINotificationObserver* aObserver,
358 mozilla::dom::Document* aLoadingDocument, nsLoadFlags aLoadFlags,
359 nsContentPolicyType aLoadPolicyType, bool aCanMakeNewChannel,
360 bool* aNewChannelCreated, imgRequestProxy** aProxyRequest,
361 nsIPrincipal* aTriggeringPrincipal, mozilla::CORSMode, bool aLinkPreload);
363 bool ValidateRequestWithNewChannel(
364 imgRequest* request, nsIURI* aURI, nsIURI* aInitialDocumentURI,
365 nsIReferrerInfo* aReferrerInfo, nsILoadGroup* aLoadGroup,
366 imgINotificationObserver* aObserver,
367 mozilla::dom::Document* aLoadingDocument, uint64_t aInnerWindowId,
368 nsLoadFlags aLoadFlags, nsContentPolicyType aContentPolicyType,
369 imgRequestProxy** aProxyRequest, nsIPrincipal* aLoadingPrincipal,
370 mozilla::CORSMode, bool aLinkPreload, bool* aNewChannelCreated);
372 // aURI may be different from imgRequest's URI in the case of blob URIs, as we
373 // can share requests with different URIs.
374 nsresult CreateNewProxyForRequest(imgRequest* aRequest, nsIURI* aURI,
375 nsILoadGroup* aLoadGroup,
376 mozilla::dom::Document* aLoadingDocument,
377 imgINotificationObserver* aObserver,
378 nsLoadFlags aLoadFlags,
379 imgRequestProxy** _retval);
381 nsresult EvictEntries(imgCacheTable& aCacheToClear);
382 nsresult EvictEntries(imgCacheQueue& aQueueToClear);
384 imgCacheTable& GetCache(bool aForChrome);
385 imgCacheTable& GetCache(const ImageCacheKey& aKey);
386 imgCacheQueue& GetCacheQueue(bool aForChrome);
387 imgCacheQueue& GetCacheQueue(const ImageCacheKey& aKey);
388 void CacheEntriesChanged(bool aForChrome, int32_t aSizeDiff = 0);
389 void CheckCacheLimits(imgCacheTable& cache, imgCacheQueue& queue);
391 private: // data
392 friend class imgCacheEntry;
393 friend class imgMemoryReporter;
395 imgCacheTable mCache;
396 imgCacheQueue mCacheQueue;
398 imgCacheTable mChromeCache;
399 imgCacheQueue mChromeCacheQueue;
401 // Hash set of every imgRequest for this loader that isn't in mCache or
402 // mChromeCache. The union over all imgLoader's of mCache, mChromeCache, and
403 // mUncachedImages should be every imgRequest that is alive. These are weak
404 // pointers so we rely on the imgRequest destructor to remove itself.
405 imgSet mUncachedImages;
406 // The imgRequest can have refs to them held on non-main thread, so we need
407 // a mutex because we modify the uncached images set from the imgRequest
408 // destructor.
409 Mutex mUncachedImagesMutex;
411 static double sCacheTimeWeight;
412 static uint32_t sCacheMaxSize;
413 static imgMemoryReporter* sMemReporter;
415 mozilla::UniquePtr<imgCacheExpirationTracker> mCacheTracker;
416 bool mRespectPrivacy;
420 * proxy stream listener class used to handle multipart/x-mixed-replace
423 #include "nsCOMPtr.h"
424 #include "nsIStreamListener.h"
425 #include "nsIThreadRetargetableStreamListener.h"
427 class ProxyListener : public nsIStreamListener,
428 public nsIThreadRetargetableStreamListener {
429 public:
430 explicit ProxyListener(nsIStreamListener* dest);
432 /* additional members */
433 NS_DECL_THREADSAFE_ISUPPORTS
434 NS_DECL_NSISTREAMLISTENER
435 NS_DECL_NSITHREADRETARGETABLESTREAMLISTENER
436 NS_DECL_NSIREQUESTOBSERVER
438 private:
439 virtual ~ProxyListener();
441 nsCOMPtr<nsIStreamListener> mDestListener;
445 * A class that implements nsIProgressEventSink and forwards all calls to it to
446 * the original notification callbacks of the channel. Also implements
447 * nsIInterfaceRequestor and gives out itself for nsIProgressEventSink calls,
448 * and forwards everything else to the channel's notification callbacks.
450 class nsProgressNotificationProxy final : public nsIProgressEventSink,
451 public nsIChannelEventSink,
452 public nsIInterfaceRequestor {
453 public:
454 nsProgressNotificationProxy(nsIChannel* channel, imgIRequest* proxy)
455 : mImageRequest(proxy) {
456 channel->GetNotificationCallbacks(getter_AddRefs(mOriginalCallbacks));
459 NS_DECL_ISUPPORTS
460 NS_DECL_NSIPROGRESSEVENTSINK
461 NS_DECL_NSICHANNELEVENTSINK
462 NS_DECL_NSIINTERFACEREQUESTOR
463 private:
464 ~nsProgressNotificationProxy() = default;
466 nsCOMPtr<nsIInterfaceRequestor> mOriginalCallbacks;
467 nsCOMPtr<nsIRequest> mImageRequest;
471 * validate checker
474 #include "nsCOMArray.h"
476 class imgCacheValidator : public nsIStreamListener,
477 public nsIThreadRetargetableStreamListener,
478 public nsIChannelEventSink,
479 public nsIInterfaceRequestor,
480 public nsIAsyncVerifyRedirectCallback {
481 public:
482 imgCacheValidator(nsProgressNotificationProxy* progress, imgLoader* loader,
483 imgRequest* aRequest, mozilla::dom::Document* aDocument,
484 uint64_t aInnerWindowId,
485 bool forcePrincipalCheckForCacheEntry);
487 void AddProxy(imgRequestProxy* aProxy);
488 void RemoveProxy(imgRequestProxy* aProxy);
490 NS_DECL_THREADSAFE_ISUPPORTS
491 NS_DECL_NSITHREADRETARGETABLESTREAMLISTENER
492 NS_DECL_NSISTREAMLISTENER
493 NS_DECL_NSIREQUESTOBSERVER
494 NS_DECL_NSICHANNELEVENTSINK
495 NS_DECL_NSIINTERFACEREQUESTOR
496 NS_DECL_NSIASYNCVERIFYREDIRECTCALLBACK
498 private:
499 void UpdateProxies(bool aCancelRequest, bool aSyncNotify);
500 virtual ~imgCacheValidator();
502 nsCOMPtr<nsIStreamListener> mDestListener;
503 RefPtr<nsProgressNotificationProxy> mProgressProxy;
504 nsCOMPtr<nsIAsyncVerifyRedirectCallback> mRedirectCallback;
505 nsCOMPtr<nsIChannel> mRedirectChannel;
507 RefPtr<imgRequest> mRequest;
508 AutoTArray<RefPtr<imgRequestProxy>, 4> mProxies;
510 RefPtr<imgRequest> mNewRequest;
511 RefPtr<imgCacheEntry> mNewEntry;
513 RefPtr<mozilla::dom::Document> mDocument;
514 uint64_t mInnerWindowId;
516 imgLoader* mImgLoader;
518 bool mHadInsecureRedirect;
521 #endif // mozilla_image_imgLoader_h