WakeLockJS.h (2732B)
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* vim:set ts=2 sw=2 sts=2 et cindent: */ 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/. */ 6 7 #ifndef DOM_WAKELOCKJS_H_ 8 #define DOM_WAKELOCKJS_H_ 9 10 #include "js/TypeDecls.h" 11 #include "mozilla/Attributes.h" 12 #include "mozilla/HalBatteryInformation.h" 13 #include "mozilla/dom/WakeLockBinding.h" 14 #include "nsCycleCollectionParticipant.h" 15 #include "nsIDOMEventListener.h" 16 #include "nsIDocumentActivity.h" 17 #include "nsIObserver.h" 18 #include "nsWeakReference.h" 19 #include "nsWrapperCache.h" 20 21 class nsPIDOMWindowInner; 22 23 namespace mozilla::dom { 24 25 class Promise; 26 class Document; 27 class WakeLockSentinel; 28 29 } // namespace mozilla::dom 30 31 namespace mozilla::dom { 32 33 /** 34 * Management class for wake locks held from client scripts. 35 * Instances of this class have two purposes: 36 * - Implement navigator.wakeLock.request which creates a WakeLockSentinel 37 * - Listen for state changes that require all WakeLockSentinel to be released 38 * The WakeLockSentinel objects are held in document.mActiveLocks. 39 * 40 * https://www.w3.org/TR/screen-wake-lock/#the-wakelock-interface 41 */ 42 class WakeLockJS final : public nsIObserver, 43 public nsWrapperCache, 44 public hal::BatteryObserver, 45 public nsSupportsWeakReference { 46 public: 47 NS_DECL_NSIOBSERVER 48 49 NS_DECL_CYCLE_COLLECTING_ISUPPORTS 50 NS_DECL_CYCLE_COLLECTION_WRAPPERCACHE_CLASS_AMBIGUOUS(WakeLockJS, nsIObserver) 51 52 public: 53 explicit WakeLockJS(nsPIDOMWindowInner* aWindow); 54 55 protected: 56 ~WakeLockJS(); 57 58 public: 59 nsISupports* GetParentObject() const; 60 61 JSObject* WrapObject(JSContext* aCx, 62 JS::Handle<JSObject*> aGivenProto) override; 63 64 void Notify(const hal::BatteryInformation& aBatteryInfo) override; 65 66 already_AddRefed<Promise> Request(WakeLockType aType, ErrorResult& aRv); 67 68 private: 69 enum class RequestError { 70 Success, 71 DocInactive, 72 DocHidden, 73 PolicyDisallowed, 74 PrefDisabled, 75 InternalFailure, 76 PermissionDenied 77 }; 78 79 static nsLiteralCString GetRequestErrorMessage(RequestError aRv); 80 81 static RequestError WakeLockAllowedForDocument(Document* aDoc); 82 83 void AttachListeners(); 84 void DetachListeners(); 85 86 Result<already_AddRefed<WakeLockSentinel>, RequestError> Obtain( 87 WakeLockType aType, Document* aDoc); 88 89 RefPtr<nsPIDOMWindowInner> mWindow; 90 }; 91 92 MOZ_CAN_RUN_SCRIPT 93 void ReleaseWakeLock(Document* aDoc, WakeLockSentinel* aLock, 94 WakeLockType aType); 95 96 } // namespace mozilla::dom 97 98 #endif // DOM_WAKELOCKJS_H_