Bug 1776680 [wpt PR 34603] - [@container] Test invalidation of font-relative units...
[gecko.git] / gfx / src / nsFontCache.h
blob2d84e1f12f6c9359c59e51cd130316be95d6cc0f
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_
9 #include <stdint.h>
10 #include <sys/types.h>
11 #include "mozilla/RefPtr.h"
12 #include "nsCOMPtr.h"
13 #include "nsFontMetrics.h"
14 #include "nsIObserver.h"
15 #include "nsISupports.h"
16 #include "nsTArray.h"
17 #include "nsThreadUtils.h"
19 class gfxUserFontSet;
20 class nsAtom;
21 class nsPresContext;
22 struct nsFont;
24 class nsFontCache final : public nsIObserver {
25 public:
26 nsFontCache() : mContext(nullptr) {}
28 NS_DECL_THREADSAFE_ISUPPORTS
29 NS_DECL_NSIOBSERVER
31 void Init(nsPresContext* aContext);
32 void Destroy();
34 already_AddRefed<nsFontMetrics> GetMetricsFor(
35 const nsFont& aFont, const nsFontMetrics::Params& aParams);
37 void FontMetricsDeleted(const nsFontMetrics* aFontMetrics);
38 void Compact();
40 // Flush aFlushCount oldest entries, or all if aFlushCount is negative
41 void Flush(int32_t aFlushCount = -1);
43 void UpdateUserFonts(gfxUserFontSet* aUserFontSet);
45 protected:
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
63 // main thread.
64 AutoTArray<nsFontMetrics*, kMaxCacheEntries * 2> mFontMetrics;
66 bool mFlushPending = false;
68 class FlushFontMetricsTask : public mozilla::Runnable {
69 public:
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
74 // recent entries.
75 mCache->Flush(mCache->mFontMetrics.Length() - kMaxCacheEntries / 2);
76 mCache->mFlushPending = false;
77 return NS_OK;
80 private:
81 RefPtr<nsFontCache> mCache;
85 #endif /* _NS_FONTCACHE_H_ */