• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 
2 /*
3  * Copyright 2011 Google Inc.
4  *
5  * Use of this source code is governed by a BSD-style license that can be
6  * found in the LICENSE file.
7  */
8 
9 
10 
11 #ifndef SkTypefaceCache_DEFINED
12 #define SkTypefaceCache_DEFINED
13 
14 #include "SkTypeface.h"
15 #include "SkTDArray.h"
16 
17 /*  TODO
18  *  Provide std way to cache name+requestedStyle aliases to the same typeface.
19  *
20  *  The current mechanism ends up create a diff typeface for each one, even if
21  *  they map to the same internal obj (e.g. CTFontRef on the mac)
22  */
23 
24 class SkTypefaceCache {
25 public:
26     SkTypefaceCache();
27     ~SkTypefaceCache();
28 
29     /**
30      * Callback for FindByProc. Returns true if the given typeface is a match
31      * for the given context. The passed typeface is owned by the cache and is
32      * not additionally ref()ed. The typeface may be in the disposed state.
33      */
34     typedef bool(*FindProc)(SkTypeface*, const SkFontStyle&, void* context);
35 
36     /**
37      *  Add a typeface to the cache. This ref()s the typeface, so that the
38      *  cache is also an owner. Later, if we need to purge the cache, typefaces
39      *  whose refcnt is 1 (meaning only the cache is an owner) will be
40      *  unref()ed.
41      */
42     void add(SkTypeface*, const SkFontStyle& requested);
43 
44     /**
45      *  Iterate through the cache, calling proc(typeface, ctx) with each
46      *  typeface. If proc returns true, then we return that typeface (this
47      *  ref()s the typeface). If it never returns true, we return nullptr.
48      */
49     SkTypeface* findByProcAndRef(FindProc proc, void* ctx) const;
50 
51     /**
52      *  This will unref all of the typefaces in the cache for which the cache
53      *  is the only owner. Normally this is handled automatically as needed.
54      *  This function is exposed for clients that explicitly want to purge the
55      *  cache (e.g. to look for leaks).
56      */
57     void purgeAll();
58 
59     /**
60      *  Helper: returns a unique fontID to pass to the constructor of
61      *  your subclass of SkTypeface
62      */
63     static SkFontID NewFontID();
64 
65     // These are static wrappers around a global instance of a cache.
66 
67     static void Add(SkTypeface*, const SkFontStyle& requested);
68     static SkTypeface* FindByProcAndRef(FindProc proc, void* ctx);
69     static void PurgeAll();
70 
71     /**
72      *  Debugging only: dumps the status of the typefaces in the cache
73      */
74     static void Dump();
75 
76 private:
77     static SkTypefaceCache& Get();
78 
79     void purge(int count);
80 
81     struct Rec {
82         SkTypeface* fFace;
83         SkFontStyle fRequestedStyle;
84     };
85     SkTDArray<Rec> fArray;
86 };
87 
88 #endif
89