summaryrefslogtreecommitdiffstats
path: root/dom/power/WakeLock.cpp
blob: bdfcfeaccd26130fc4a08a772f4f31110d505ed8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
/* -*- 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 "WakeLock.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/dom/Event.h"  // for Event
#include "mozilla/Hal.h"
#include "mozilla/HalWakeLock.h"
#include "nsError.h"
#include "mozilla/dom/Document.h"
#include "nsPIDOMWindow.h"
#include "nsIPropertyBag2.h"

using namespace mozilla::hal;

namespace mozilla::dom {

NS_INTERFACE_MAP_BEGIN(WakeLock)
  NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIDOMEventListener)
  NS_INTERFACE_MAP_ENTRY(nsIDOMEventListener)
  NS_INTERFACE_MAP_ENTRY(nsIObserver)
  NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
  NS_INTERFACE_MAP_ENTRY(nsIWakeLock)
NS_INTERFACE_MAP_END

NS_IMPL_ADDREF(WakeLock)
NS_IMPL_RELEASE(WakeLock)

WakeLock::WakeLock()
    : mLocked(false),
      mHidden(true),
      mContentParentID(CONTENT_PROCESS_ID_UNKNOWN) {}

WakeLock::~WakeLock() {
  DoUnlock();
  DetachEventListener();
}

nsresult WakeLock::Init(const nsAString& aTopic, nsPIDOMWindowInner* aWindow) {
  // Don't Init() a WakeLock twice.
  MOZ_ASSERT(mTopic.IsEmpty());

  if (aTopic.IsEmpty()) {
    return NS_ERROR_INVALID_ARG;
  }

  mTopic.Assign(aTopic);

  mWindow = do_GetWeakReference(aWindow);

  /**
   * Null windows are allowed. A wake lock without associated window
   * is always considered invisible.
   */
  if (aWindow) {
    nsCOMPtr<Document> doc = aWindow->GetExtantDoc();
    NS_ENSURE_STATE(doc);
    mHidden = IsDocumentInvisible(*doc);
  }

  AttachEventListener();
  DoLock();

  return NS_OK;
}

NS_IMETHODIMP
WakeLock::Observe(nsISupports* aSubject, const char* aTopic,
                  const char16_t* data) {
  // If this wake lock was acquired on behalf of another process, unlock it
  // when that process dies.
  //
  // Note that we do /not/ call DoUnlock() here!  The wake lock back-end is
  // already listening for ipc:content-shutdown messages and will clear out its
  // tally for the process when it dies.  All we need to do here is ensure that
  // unlock() becomes a nop.

  MOZ_ASSERT(!strcmp(aTopic, "ipc:content-shutdown"));

  nsCOMPtr<nsIPropertyBag2> props = do_QueryInterface(aSubject);
  if (!props) {
    NS_WARNING("ipc:content-shutdown message without property bag as subject");
    return NS_OK;
  }

  uint64_t childID = 0;
  nsresult rv = props->GetPropertyAsUint64(u"childID"_ns, &childID);
  if (NS_SUCCEEDED(rv)) {
    if (childID == mContentParentID) {
      mLocked = false;
    }
  } else {
    NS_WARNING("ipc:content-shutdown message without childID property");
  }
  return NS_OK;
}

void WakeLock::DoLock() {
  if (!mLocked) {
    // Change the flag immediately to prevent recursive reentering
    mLocked = true;

    hal::ModifyWakeLock(
        mTopic, hal::WAKE_LOCK_ADD_ONE,
        mHidden ? hal::WAKE_LOCK_ADD_ONE : hal::WAKE_LOCK_NO_CHANGE,
        mContentParentID);
  }
}

void WakeLock::DoUnlock() {
  if (mLocked) {
    // Change the flag immediately to prevent recursive reentering
    mLocked = false;

    hal::ModifyWakeLock(
        mTopic, hal::WAKE_LOCK_REMOVE_ONE,
        mHidden ? hal::WAKE_LOCK_REMOVE_ONE : hal::WAKE_LOCK_NO_CHANGE,
        mContentParentID);
  }
}

void WakeLock::AttachEventListener() {
  if (nsCOMPtr<nsPIDOMWindowInner> window = do_QueryReferent(mWindow)) {
    nsCOMPtr<Document> doc = window->GetExtantDoc();
    if (doc) {
      doc->AddSystemEventListener(u"visibilitychange"_ns, this,
                                  /* useCapture = */ true,
                                  /* wantsUntrusted = */ false);

      nsCOMPtr<EventTarget> target = do_QueryInterface(window);
      target->AddSystemEventListener(u"pagehide"_ns, this,
                                     /* useCapture = */ true,
                                     /* wantsUntrusted = */ false);
      target->AddSystemEventListener(u"pageshow"_ns, this,
                                     /* useCapture = */ true,
                                     /* wantsUntrusted = */ false);
    }
  }
}

void WakeLock::DetachEventListener() {
  if (nsCOMPtr<nsPIDOMWindowInner> window = do_QueryReferent(mWindow)) {
    nsCOMPtr<Document> doc = window->GetExtantDoc();
    if (doc) {
      doc->RemoveSystemEventListener(u"visibilitychange"_ns, this,
                                     /* useCapture = */ true);
      nsCOMPtr<EventTarget> target = do_QueryInterface(window);
      target->RemoveSystemEventListener(u"pagehide"_ns, this,
                                        /* useCapture = */ true);
      target->RemoveSystemEventListener(u"pageshow"_ns, this,
                                        /* useCapture = */ true);
    }
  }
}

void WakeLock::Unlock(ErrorResult& aRv) {
  /*
   * We throw NS_ERROR_DOM_INVALID_STATE_ERR on double unlock.
   */
  if (!mLocked) {
    aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
    return;
  }

  DoUnlock();
  DetachEventListener();
}

void WakeLock::GetTopic(nsAString& aTopic) { aTopic.Assign(mTopic); }

bool WakeLock::IsDocumentInvisible(const Document& aDocument) const {
  // If document has a child element being used in the picture in picture
  // mode, which is always visible to users, then we would consider the
  // document as visible as well.
  return aDocument.Hidden() && !aDocument.HasPictureInPictureChildElement();
}

NS_IMETHODIMP
WakeLock::HandleEvent(Event* aEvent) {
  nsAutoString type;
  aEvent->GetType(type);

  if (type.EqualsLiteral("visibilitychange")) {
    nsCOMPtr<Document> doc = do_QueryInterface(aEvent->GetTarget());
    NS_ENSURE_STATE(doc);

    bool oldHidden = mHidden;
    mHidden = IsDocumentInvisible(*doc);

    if (mLocked && oldHidden != mHidden) {
      hal::ModifyWakeLock(
          mTopic, hal::WAKE_LOCK_NO_CHANGE,
          mHidden ? hal::WAKE_LOCK_ADD_ONE : hal::WAKE_LOCK_REMOVE_ONE,
          mContentParentID);
    }

    return NS_OK;
  }

  if (type.EqualsLiteral("pagehide")) {
    DoUnlock();
    return NS_OK;
  }

  if (type.EqualsLiteral("pageshow")) {
    DoLock();
    return NS_OK;
  }

  return NS_OK;
}

NS_IMETHODIMP
WakeLock::Unlock() {
  ErrorResult error;
  Unlock(error);
  return error.StealNSResult();
}

nsPIDOMWindowInner* WakeLock::GetParentObject() const {
  nsCOMPtr<nsPIDOMWindowInner> window = do_QueryInterface(mWindow);
  return window;
}

}  // namespace mozilla::dom