FetchImageHelper.h (2861B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 #ifndef DOM_MEDIA_MEDIACONTROL_FETCHIMAGEHELPER_H_ 6 #define DOM_MEDIA_MEDIACONTROL_FETCHIMAGEHELPER_H_ 7 8 #include "imgIContainer.h" 9 #include "imgITools.h" 10 #include "mozilla/MozPromise.h" 11 #include "mozilla/dom/MediaSessionBinding.h" 12 13 namespace mozilla::dom { 14 /** 15 * FetchImageHelper is used to fetch image data from MediaImage, and the fetched 16 * image data would be used to show on the virtual control inferface. The URL of 17 * MediaImage is defined by websites by using MediaSession API [1]. 18 * 19 * By using `FetchImage()`, it would return a promise that would resolve with a 20 * `imgIContainer`, then we can get the image data from the container. 21 * 22 * [1] https://w3c.github.io/mediasession/#dictdef-mediaimage 23 */ 24 using ImagePromise = MozPromise<nsCOMPtr<imgIContainer>, bool, 25 /* IsExclusive = */ true>; 26 class FetchImageHelper final { 27 public: 28 explicit FetchImageHelper(const MediaImage& aImage); 29 ~FetchImageHelper(); 30 31 // Return a promise which would be resolved with the decoded image surface 32 // when we finish fetching and decoding image data, and it would be rejected 33 // when we fail to fecth the image. 34 RefPtr<ImagePromise> FetchImage(); 35 36 // Stop fetching and decoding image and reject the image promise. If we have 37 // not started yet fetching image, then nothing would happen. 38 void AbortFetchingImage(); 39 40 // Return true if we're fecthing image. 41 bool IsFetchingImage() const; 42 43 private: 44 /** 45 * ImageFetchListener is used to listen the notification of finishing fetching 46 * image data (via `OnImageReady()`) and finishing decoding image data (via 47 * `Notify()`). 48 */ 49 class ImageFetchListener final : public imgIContainerCallback { 50 public: 51 NS_DECL_ISUPPORTS 52 ImageFetchListener() = default; 53 54 // Start an async channel to load the image, and return error if the channel 55 // opens failed. It would use `aHelper::HandleFetchSuccess/Fail()` to notify 56 // the result asynchronously. 57 nsresult FetchDecodedImageFromURI(nsIURI* aURI, FetchImageHelper* aHelper); 58 void Clear(); 59 bool IsFetchingImage() const; 60 61 // Method of imgIContainerCallback 62 NS_IMETHOD OnImageReady(imgIContainer* aImage, nsresult aStatus) override; 63 64 private: 65 ~ImageFetchListener(); 66 67 FetchImageHelper* MOZ_NON_OWNING_REF mHelper = nullptr; 68 nsCOMPtr<nsIChannel> mChannel; 69 }; 70 71 void ClearListenerIfNeeded(); 72 void HandleFetchSuccess(imgIContainer* aImage); 73 void HandleFetchFail(); 74 75 nsString mSrc; 76 MozPromiseHolder<ImagePromise> mPromise; 77 RefPtr<ImageFetchListener> mListener; 78 }; 79 80 } // namespace mozilla::dom 81 82 #endif // DOM_MEDIA_MEDIACONTROL_FETCHIMAGEHELPER_H_