Bug 1764201 Part 3: Remove screen info stuff from gfxPlatform. r=jgilbert,geckoview...
[gecko.git] / gfx / layers / MemoryPressureObserver.cpp
blob16c9ea4b1eeff0ff32d97ec30a279d5aa3d3718c
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"
10 #include "nsCOMPtr.h"
11 #include "nsDependentString.h"
12 #include "nsIObserverService.h"
13 #include "nsLiteralString.h"
15 namespace mozilla {
16 namespace layers {
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();
31 if (!service) {
32 return nullptr;
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() {
45 if (!mListener) {
46 return;
49 nsCOMPtr<nsIObserverService> service = services::GetObserverService();
50 if (service) {
51 service->RemoveObserver(this, "memory-pressure");
54 mListener = nullptr;
57 NS_IMETHODIMP
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);
71 return NS_OK;
74 NS_IMPL_ISUPPORTS(MemoryPressureObserver, nsIObserver)
76 } // namespace layers
77 } // namespace mozilla