Source code

Revision control

Other Tools

1
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
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
#include "MemoryPressureObserver.h"
8
9
namespace mozilla {
10
namespace layers {
11
12
MemoryPressureObserver::MemoryPressureObserver(
13
MemoryPressureListener* aListener)
14
: mListener(aListener) {}
15
16
MemoryPressureObserver::~MemoryPressureObserver() {
17
// If this assertion is hit we probably forgot to unregister the observer.
18
MOZ_ASSERT(!mListener);
19
}
20
21
already_AddRefed<MemoryPressureObserver> MemoryPressureObserver::Create(
22
MemoryPressureListener* aListener) {
23
nsCOMPtr<nsIObserverService> service = services::GetObserverService();
24
25
if (!service) {
26
return nullptr;
27
}
28
29
RefPtr<MemoryPressureObserver> observer =
30
new MemoryPressureObserver(aListener);
31
32
bool useWeakRef = false;
33
service->AddObserver(observer, "memory-pressure", useWeakRef);
34
35
return observer.forget();
36
}
37
38
void MemoryPressureObserver::Unregister() {
39
if (!mListener) {
40
return;
41
}
42
43
nsCOMPtr<nsIObserverService> service = services::GetObserverService();
44
if (service) {
45
service->RemoveObserver(this, "memory-pressure");
46
}
47
48
mListener = nullptr;
49
}
50
51
NS_IMETHODIMP
52
MemoryPressureObserver::Observe(nsISupports* aSubject, const char* aTopic,
53
const char16_t* aData) {
54
if (mListener && strcmp(aTopic, "memory-pressure") == 0) {
55
MemoryPressureReason reason = MemoryPressureReason::LOW_MEMORY;
56
auto reason_string = nsDependentString(aData);
57
if (StringBeginsWith(reason_string,
58
NS_LITERAL_STRING("low-memory-ongoing"))) {
59
reason = MemoryPressureReason::LOW_MEMORY_ONGOING;
60
} else if (StringBeginsWith(reason_string,
61
NS_LITERAL_STRING("heap-minimize"))) {
62
reason = MemoryPressureReason::HEAP_MINIMIZE;
63
}
64
mListener->OnMemoryPressure(reason);
65
}
66
67
return NS_OK;
68
}
69
70
NS_IMPL_ISUPPORTS(MemoryPressureObserver, nsIObserver)
71
72
} // namespace layers
73
} // namespace mozilla