1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #ifndef _NS_FONTCACHE_H_
7 #define _NS_FONTCACHE_H_
10 #include <sys/types.h>
11 #include "mozilla/RefPtr.h"
13 #include "nsFontMetrics.h"
14 #include "nsIObserver.h"
15 #include "nsISupports.h"
17 #include "nsThreadUtils.h"
24 class nsFontCache final
: public nsIObserver
{
26 nsFontCache() : mContext(nullptr) {}
28 NS_DECL_THREADSAFE_ISUPPORTS
31 void Init(nsPresContext
* aContext
);
34 already_AddRefed
<nsFontMetrics
> GetMetricsFor(
35 const nsFont
& aFont
, const nsFontMetrics::Params
& aParams
);
37 void FontMetricsDeleted(const nsFontMetrics
* aFontMetrics
);
40 // Flush aFlushCount oldest entries, or all if aFlushCount is negative
41 void Flush(int32_t aFlushCount
= -1);
43 void UpdateUserFonts(gfxUserFontSet
* aUserFontSet
);
46 // If the array of cached entries is about to exceed this threshold,
47 // we'll discard the oldest ones so as to keep the size reasonable.
48 // In practice, the great majority of cache hits are among the last
49 // few entries; keeping thousands of older entries becomes counter-
50 // productive because it can then take too long to scan the cache.
51 static const int32_t kMaxCacheEntries
= 128;
53 ~nsFontCache() = default;
55 nsPresContext
* mContext
; // owner
56 RefPtr
<nsAtom
> mLocaleLanguage
;
58 // We may not flush older entries immediately the array reaches
59 // kMaxCacheEntries length, because this usually happens on a stylo
60 // thread where we can't safely delete metrics objects. So we allocate an
61 // oversized autoarray buffer here, so that we're unlikely to overflow
62 // it and need separate heap allocation before the flush happens on the
64 AutoTArray
<nsFontMetrics
*, kMaxCacheEntries
* 2> mFontMetrics
;
66 bool mFlushPending
= false;
68 class FlushFontMetricsTask
: public mozilla::Runnable
{
70 explicit FlushFontMetricsTask(nsFontCache
* aCache
)
71 : mozilla::Runnable("FlushFontMetricsTask"), mCache(aCache
) {}
72 NS_IMETHOD
Run() override
{
73 // Partially flush the cache, leaving the kMaxCacheEntries/2 most
75 mCache
->Flush(mCache
->mFontMetrics
.Length() - kMaxCacheEntries
/ 2);
76 mCache
->mFlushPending
= false;
81 RefPtr
<nsFontCache
> mCache
;
85 #endif /* _NS_FONTCACHE_H_ */