1 /*
2  * Copyright 2006 The Android Open Source Project
3  *
4  * Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
5  */
6 
7 #ifndef SkStrike_DEFINED
8 #define SkStrike_DEFINED
9 
10 #include "include/core/SkFontMetrics.h"
11 #include "include/core/SkFontTypes.h"
12 #include "include/core/SkPaint.h"
13 #include "include/private/SkTHash.h"
14 #include "include/private/SkTemplates.h"
15 #include "src/core/SkArenaAlloc.h"
16 #include "src/core/SkDescriptor.h"
17 #include "src/core/SkGlyph.h"
18 #include "src/core/SkGlyphRunPainter.h"
19 #include "src/core/SkScalerContext.h"
20 #include "src/core/SkStrikeForGPU.h"
21 #include <memory>
22 
23 /** \class SkGlyphCache
24 
25     This class represents a strike: a specific combination of typeface, size, matrix, etc., and
26     holds the glyphs for that strike. Calling any of the getGlyphID... methods will
27     return the requested glyph, either instantly if it is already cached, or by first generating
28     it and then adding it to the strike.
29 
30     The strikes are held in a global list, available to all threads. To interact with one, call
31     either Find{OrCreate}Exclusive().
32 
33     The Find*Exclusive() method returns SkExclusiveStrikePtr, which releases exclusive ownership
34     when they go out of scope.
35 */
36 class SkStrike final : public SkStrikeForGPU {
37 public:
38     SkStrike(const SkDescriptor& desc,
39              std::unique_ptr<SkScalerContext> scaler,
40              const SkFontMetrics&);
41 
42     // Return a glyph. Create it if it doesn't exist, and initialize the glyph with metrics and
43     // advances using a scaler.
44     SkGlyph* glyph(SkPackedGlyphID packedID);
45     SkGlyph* glyph(SkGlyphID glyphID);
46     SkGlyph* glyph(SkGlyphID, SkPoint);
47 
48     // Return a glyph.  Create it if it doesn't exist, and initialize with the prototype.
49     SkGlyph* glyphFromPrototype(const SkGlyphPrototype& p, void* image = nullptr);
50 
51     // Return a glyph or nullptr if it does not exits in the strike.
52     SkGlyph* glyphOrNull(SkPackedGlyphID id) const;
53 
54     const void* prepareImage(SkGlyph* glyph);
55 
56     // Lookup (or create if needed) the toGlyph using toID. If that glyph is not initialized with
57     // an image, then use the information in from to initialize the width, height top, left,
58     // format and image of the toGlyph. This is mainly used preserving the glyph if it was
59     // created by a search of desperation.
60     SkGlyph* mergeGlyphAndImage(SkPackedGlyphID toID, const SkGlyph& from);
61 
62     // If the path has never been set, then use the scaler context to add the glyph.
63     const SkPath* preparePath(SkGlyph*);
64 
65     // If the path has never been set, then add a path to glyph.
66     const SkPath* preparePath(SkGlyph* glyph, const SkPath* path);
67 
68     /** Returns the number of glyphs for this strike.
69     */
70     unsigned getGlyphCount() const;
71 
72     /** Return the number of glyphs currently cached. */
73     int countCachedGlyphs() const;
74 
75     /** If the advance axis intersects the glyph's path, append the positions scaled and offset
76         to the array (if non-null), and set the count to the updated array length.
77     */
78     void findIntercepts(const SkScalar bounds[2], SkScalar scale, SkScalar xPos,
79                         SkGlyph* , SkScalar* array, int* count);
80 
81     /** Fallback glyphs used during font remoting if the original glyph can't be found.
82      */
83     bool belongsToCache(const SkGlyph* glyph) const;
84     /** Find any glyph in this cache with the given ID, regardless of subpixel positioning.
85      *  If set and present, skip over the glyph with vetoID.
86      */
87     const SkGlyph* getCachedGlyphAnySubPix(SkGlyphID,
88                                            SkPackedGlyphID vetoID = SkPackedGlyphID()) const;
89 
90     /** Return the vertical metrics for this strike.
91     */
getFontMetrics()92     const SkFontMetrics& getFontMetrics() const {
93         return fFontMetrics;
94     }
95 
getMaskFormat()96     SkMask::Format getMaskFormat() const {
97         return fScalerContext->getMaskFormat();
98     }
99 
roundingSpec()100     const SkGlyphPositionRoundingSpec& roundingSpec() const override {
101         return fRoundingSpec;
102     }
103 
104     const SkDescriptor& getDescriptor() const override;
105 
106     SkSpan<const SkGlyph*> metrics(SkSpan<const SkGlyphID> glyphIDs,
107                                    const SkGlyph* results[]);
108 
109     SkSpan<const SkGlyph*> preparePaths(SkSpan<const SkGlyphID> glyphIDs,
110                                         const SkGlyph* results[]);
111 
112     SkSpan<const SkGlyph*> prepareImages(SkSpan<const SkPackedGlyphID> glyphIDs,
113                                          const SkGlyph* results[]);
114 
115     void prepareForDrawingMasksCPU(SkDrawableGlyphBuffer* drawables);
116 
117     void prepareForDrawingPathsCPU(SkDrawableGlyphBuffer* drawables);
118     SkSpan<const SkGlyphPos> prepareForDrawingRemoveEmpty(const SkPackedGlyphID packedGlyphIDs[],
119                                                           const SkPoint positions[],
120                                                           size_t n,
121                                                           int maxDimension,
122                                                           SkGlyphPos results[]) override;
123 
124     void onAboutToExitScope() override;
125 
126     /** Return the approx RAM usage for this cache. */
getMemoryUsed()127     size_t getMemoryUsed() const { return fMemoryUsed; }
128 
129     void dump() const;
130 
getScalerContext()131     SkScalerContext* getScalerContext() const { return fScalerContext.get(); }
132 
133 #ifdef SK_DEBUG
134     void forceValidate() const;
135     void validate() const;
136 #else
validate()137     void validate() const {}
138 #endif
139 
140     class AutoValidate : SkNoncopyable {
141     public:
AutoValidate(const SkStrike * cache)142         AutoValidate(const SkStrike* cache) : fCache(cache) {
143             if (fCache) {
144                 fCache->validate();
145             }
146         }
~AutoValidate()147         ~AutoValidate() {
148             if (fCache) {
149                 fCache->validate();
150             }
151         }
forget()152         void forget() {
153             fCache = nullptr;
154         }
155     private:
156         const SkStrike* fCache;
157     };
158 
159 private:
160     class GlyphMapHashTraits {
161     public:
GetKey(const SkGlyph * glyph)162         static SkPackedGlyphID GetKey(const SkGlyph* glyph) {
163             return glyph->getPackedID();
164         }
Hash(SkPackedGlyphID glyphId)165         static uint32_t Hash(SkPackedGlyphID glyphId) {
166             return glyphId.hash();
167         }
168     };
169 
170     SkGlyph* makeGlyph(SkPackedGlyphID);
171 
172     enum PathDetail {
173         kMetricsOnly,
174         kMetricsAndPath
175     };
176 
177     // internalPrepare will only be called with a mutex already held.
178     SkSpan<const SkGlyph*> internalPrepare(
179             SkSpan<const SkGlyphID> glyphIDs,
180             PathDetail pathDetail,
181             const SkGlyph** results);
182 
183     const SkAutoDescriptor                 fDesc;
184     const std::unique_ptr<SkScalerContext> fScalerContext;
185     SkFontMetrics                          fFontMetrics;
186 
187     // Map from a combined GlyphID and sub-pixel position to a SkGlyph*.
188     // The actual glyph is stored in the fAlloc. This structure provides an
189     // unchanging pointer as long as the strike is alive.
190     SkTHashTable<SkGlyph*, SkPackedGlyphID, GlyphMapHashTraits> fGlyphMap;
191 
192     // so we don't grow our arrays a lot
193     static constexpr size_t kMinGlyphCount = 8;
194     static constexpr size_t kMinGlyphImageSize = 16 /* height */ * 8 /* width */;
195     static constexpr size_t kMinAllocAmount = kMinGlyphImageSize * kMinGlyphCount;
196 
197     SkArenaAlloc            fAlloc {kMinAllocAmount};
198 
199     // Tracks (approx) how much ram is tied-up in this strike.
200     size_t                  fMemoryUsed;
201 
202     const SkGlyphPositionRoundingSpec fRoundingSpec;
203 };
204 
205 #endif  // SkStrike_DEFINED
206