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/. */
7 #include "MemoryPressureObserver.h"
9 #include "mozilla/Services.h"
11 #include "nsDependentString.h"
12 #include "nsIObserverService.h"
13 #include "nsLiteralString.h"
18 MemoryPressureObserver::MemoryPressureObserver(
19 MemoryPressureListener
* aListener
)
20 : mListener(aListener
) {}
22 MemoryPressureObserver::~MemoryPressureObserver() {
23 // If this assertion is hit we probably forgot to unregister the observer.
24 MOZ_ASSERT(!mListener
);
27 already_AddRefed
<MemoryPressureObserver
> MemoryPressureObserver::Create(
28 MemoryPressureListener
* aListener
) {
29 nsCOMPtr
<nsIObserverService
> service
= services::GetObserverService();
35 RefPtr
<MemoryPressureObserver
> observer
=
36 new MemoryPressureObserver(aListener
);
38 bool useWeakRef
= false;
39 service
->AddObserver(observer
, "memory-pressure", useWeakRef
);
41 return observer
.forget();
44 void MemoryPressureObserver::Unregister() {
49 nsCOMPtr
<nsIObserverService
> service
= services::GetObserverService();
51 service
->RemoveObserver(this, "memory-pressure");
58 MemoryPressureObserver::Observe(nsISupports
* aSubject
, const char* aTopic
,
59 const char16_t
* aData
) {
60 if (mListener
&& strcmp(aTopic
, "memory-pressure") == 0) {
61 MemoryPressureReason reason
= MemoryPressureReason::LOW_MEMORY
;
62 auto reason_string
= nsDependentString(aData
);
63 if (StringBeginsWith(reason_string
, u
"low-memory-ongoing"_ns
)) {
64 reason
= MemoryPressureReason::LOW_MEMORY_ONGOING
;
65 } else if (StringBeginsWith(reason_string
, u
"heap-minimize"_ns
)) {
66 reason
= MemoryPressureReason::HEAP_MINIMIZE
;
68 mListener
->OnMemoryPressure(reason
);
74 NS_IMPL_ISUPPORTS(MemoryPressureObserver
, nsIObserver
)
77 } // namespace mozilla