1 // Copyright 2019 Google LLC.
2 #include <memory>
3
4 #include "modules/skparagraph/include/ParagraphCache.h"
5 #include "modules/skparagraph/src/ParagraphImpl.h"
6
7 namespace skia {
8 namespace textlayout {
9
10 namespace {
relax(SkScalar a)11 SkScalar relax(SkScalar a) {
12 // This rounding is done to match Flutter tests. Must be removed..
13 if (SkScalarIsFinite(a)) {
14 auto threshold = SkIntToScalar(1 << 12);
15 return SkScalarRoundToScalar(a * threshold)/threshold;
16 } else {
17 return a;
18 }
19 }
20
exactlyEqual(SkScalar x,SkScalar y)21 bool exactlyEqual(SkScalar x, SkScalar y) {
22 return x == y || (x != x && y != y);
23 }
24 } // namespace
25
26 class ParagraphCacheKey {
27 public:
ParagraphCacheKey(const ParagraphImpl * paragraph)28 ParagraphCacheKey(const ParagraphImpl* paragraph)
29 : fText(paragraph->fText.c_str(), paragraph->fText.size())
30 , fPlaceholders(paragraph->fPlaceholders)
31 , fTextStyles(paragraph->fTextStyles)
32 , fParagraphStyle(paragraph->paragraphStyle()) { }
33
34 SkString fText;
35 SkTArray<Placeholder, true> fPlaceholders;
36 SkTArray<Block, true> fTextStyles;
37 ParagraphStyle fParagraphStyle;
38 };
39
40 class ParagraphCacheValue {
41 public:
ParagraphCacheValue(const ParagraphImpl * paragraph)42 ParagraphCacheValue(const ParagraphImpl* paragraph)
43 : fKey(ParagraphCacheKey(paragraph))
44 , fRuns(paragraph->fRuns)
45 , fCodeUnitProperties(paragraph->fCodeUnitProperties)
46 , fWords(paragraph->fWords)
47 , fBidiRegions(paragraph->fBidiRegions)
48 , fUTF8IndexForUTF16Index(paragraph->fUTF8IndexForUTF16Index)
49 , fUTF16IndexForUTF8Index(paragraph->fUTF16IndexForUTF8Index) { }
50
51 // Input == key
52 ParagraphCacheKey fKey;
53
54 // Shaped results
55 SkTArray<Run, false> fRuns;
56 // ICU results
57 SkTArray<CodeUnitFlags> fCodeUnitProperties;
58 std::vector<size_t> fWords;
59 std::vector<SkUnicode::BidiRegion> fBidiRegions;
60 SkTArray<TextIndex, true> fUTF8IndexForUTF16Index;
61 SkTArray<size_t, true> fUTF16IndexForUTF8Index;
62 };
63
mix(uint32_t hash,uint32_t data) const64 uint32_t ParagraphCache::KeyHash::mix(uint32_t hash, uint32_t data) const {
65 hash += data;
66 hash += (hash << 10);
67 hash ^= (hash >> 6);
68 return hash;
69 }
70
operator ()(const ParagraphCacheKey & key) const71 uint32_t ParagraphCache::KeyHash::operator()(const ParagraphCacheKey& key) const {
72 uint32_t hash = 0;
73 for (auto& ph : key.fPlaceholders) {
74 if (ph.fRange.width() == 0) {
75 continue;
76 }
77 hash = mix(hash, SkGoodHash()(ph.fRange.start));
78 hash = mix(hash, SkGoodHash()(ph.fRange.end));
79 hash = mix(hash, SkGoodHash()(relax(ph.fStyle.fHeight)));
80 hash = mix(hash, SkGoodHash()(relax(ph.fStyle.fWidth)));
81 hash = mix(hash, SkGoodHash()(ph.fStyle.fAlignment));
82 hash = mix(hash, SkGoodHash()(ph.fStyle.fBaseline));
83 if (ph.fStyle.fAlignment == PlaceholderAlignment::kBaseline) {
84 hash = mix(hash, SkGoodHash()(relax(ph.fStyle.fBaselineOffset)));
85 }
86 }
87
88 for (auto& ts : key.fTextStyles) {
89 if (ts.fStyle.isPlaceholder()) {
90 continue;
91 }
92 hash = mix(hash, SkGoodHash()(relax(ts.fStyle.getLetterSpacing())));
93 hash = mix(hash, SkGoodHash()(relax(ts.fStyle.getWordSpacing())));
94 hash = mix(hash, SkGoodHash()(ts.fStyle.getLocale()));
95 hash = mix(hash, SkGoodHash()(relax(ts.fStyle.getHeight())));
96 for (auto& ff : ts.fStyle.getFontFamilies()) {
97 hash = mix(hash, SkGoodHash()(ff));
98 }
99 for (auto& ff : ts.fStyle.getFontFeatures()) {
100 hash = mix(hash, SkGoodHash()(ff.fValue));
101 hash = mix(hash, SkGoodHash()(ff.fName));
102 }
103 hash = mix(hash, SkGoodHash()(ts.fStyle.getFontStyle()));
104 hash = mix(hash, SkGoodHash()(relax(ts.fStyle.getFontSize())));
105 hash = mix(hash, SkGoodHash()(ts.fRange));
106 }
107
108 hash = mix(hash, SkGoodHash()(relax(key.fParagraphStyle.getHeight())));
109 hash = mix(hash, SkGoodHash()(key.fParagraphStyle.getTextDirection()));
110
111 auto& strutStyle = key.fParagraphStyle.getStrutStyle();
112 if (strutStyle.getStrutEnabled()) {
113 hash = mix(hash, SkGoodHash()(relax(strutStyle.getHeight())));
114 hash = mix(hash, SkGoodHash()(relax(strutStyle.getLeading())));
115 hash = mix(hash, SkGoodHash()(relax(strutStyle.getFontSize())));
116 hash = mix(hash, SkGoodHash()(strutStyle.getHeightOverride()));
117 hash = mix(hash, SkGoodHash()(strutStyle.getFontStyle()));
118 hash = mix(hash, SkGoodHash()(strutStyle.getForceStrutHeight()));
119 for (auto& ff : strutStyle.getFontFamilies()) {
120 hash = mix(hash, SkGoodHash()(ff));
121 }
122 }
123
124 hash = mix(hash, SkGoodHash()(key.fText));
125 return hash;
126 }
127
operator ==(const ParagraphCacheKey & a,const ParagraphCacheKey & b)128 bool operator==(const ParagraphCacheKey& a, const ParagraphCacheKey& b) {
129 if (a.fText.size() != b.fText.size()) {
130 return false;
131 }
132 if (a.fPlaceholders.count() != b.fPlaceholders.count()) {
133 return false;
134 }
135 if (a.fText != b.fText) {
136 return false;
137 }
138 if (a.fTextStyles.size() != b.fTextStyles.size()) {
139 return false;
140 }
141
142 // There is no need to compare default paragraph styles - they are included into fTextStyles
143 if (!exactlyEqual(a.fParagraphStyle.getHeight(), b.fParagraphStyle.getHeight())) {
144 return false;
145 }
146 if (a.fParagraphStyle.getTextDirection() != b.fParagraphStyle.getTextDirection()) {
147 return false;
148 }
149
150 if (!(a.fParagraphStyle.getStrutStyle() == b.fParagraphStyle.getStrutStyle())) {
151 return false;
152 }
153
154 for (size_t i = 0; i < a.fTextStyles.size(); ++i) {
155 auto& tsa = a.fTextStyles[i];
156 auto& tsb = b.fTextStyles[i];
157 if (tsa.fStyle.isPlaceholder()) {
158 continue;
159 }
160 if (!(tsa.fStyle.equalsByFonts(tsb.fStyle))) {
161 return false;
162 }
163 if (tsa.fRange.width() != tsb.fRange.width()) {
164 return false;
165 }
166 if (tsa.fRange.start != tsb.fRange.start) {
167 return false;
168 }
169 }
170 for (size_t i = 0; i < a.fPlaceholders.size(); ++i) {
171 auto& tsa = a.fPlaceholders[i];
172 auto& tsb = b.fPlaceholders[i];
173 if (tsa.fRange.width() == 0 && tsb.fRange.width() == 0) {
174 continue;
175 }
176 if (!(tsa.fStyle.equals(tsb.fStyle))) {
177 return false;
178 }
179 if (tsa.fRange.width() != tsb.fRange.width()) {
180 return false;
181 }
182 if (tsa.fRange.start != tsb.fRange.start) {
183 return false;
184 }
185 }
186
187 return true;
188 }
189
190 struct ParagraphCache::Entry {
191
Entryskia::textlayout::ParagraphCache::Entry192 Entry(ParagraphCacheValue* value) : fValue(value) {}
193 std::unique_ptr<ParagraphCacheValue> fValue;
194 };
195
ParagraphCache()196 ParagraphCache::ParagraphCache()
197 : fChecker([](ParagraphImpl* impl, const char*, bool){ })
198 , fLRUCacheMap(kMaxEntries)
199 , fCacheIsOn(true)
200 , fLastCachedValue(nullptr)
201 #ifdef PARAGRAPH_CACHE_STATS
202 , fTotalRequests(0)
203 , fCacheMisses(0)
204 , fHashMisses(0)
205 #endif
206 { }
207
~ParagraphCache()208 ParagraphCache::~ParagraphCache() { }
209
updateTo(ParagraphImpl * paragraph,const Entry * entry)210 void ParagraphCache::updateTo(ParagraphImpl* paragraph, const Entry* entry) {
211
212 paragraph->fRuns.reset();
213 paragraph->fRuns = entry->fValue->fRuns;
214 paragraph->fCodeUnitProperties = entry->fValue->fCodeUnitProperties;
215 paragraph->fWords = entry->fValue->fWords;
216 paragraph->fBidiRegions = entry->fValue->fBidiRegions;
217 paragraph->fUTF8IndexForUTF16Index = entry->fValue->fUTF8IndexForUTF16Index;
218 paragraph->fUTF16IndexForUTF8Index = entry->fValue->fUTF16IndexForUTF8Index;
219 for (auto& run : paragraph->fRuns) {
220 run.setOwner(paragraph);
221 }
222 }
223
printStatistics()224 void ParagraphCache::printStatistics() {
225 SkDebugf("--- Paragraph Cache ---\n");
226 SkDebugf("Total requests: %d\n", fTotalRequests);
227 SkDebugf("Cache misses: %d\n", fCacheMisses);
228 SkDebugf("Cache miss %%: %f\n", (fTotalRequests > 0) ? 100.f * fCacheMisses / fTotalRequests : 0.f);
229 int cacheHits = fTotalRequests - fCacheMisses;
230 SkDebugf("Hash miss %%: %f\n", (cacheHits > 0) ? 100.f * fHashMisses / cacheHits : 0.f);
231 SkDebugf("---------------------\n");
232 }
233
abandon()234 void ParagraphCache::abandon() {
235 this->reset();
236 }
237
reset()238 void ParagraphCache::reset() {
239 SkAutoMutexExclusive lock(fParagraphMutex);
240 #ifdef PARAGRAPH_CACHE_STATS
241 fTotalRequests = 0;
242 fCacheMisses = 0;
243 fHashMisses = 0;
244 #endif
245 fLRUCacheMap.reset();
246 fLastCachedValue = nullptr;
247 }
248
findParagraph(ParagraphImpl * paragraph)249 bool ParagraphCache::findParagraph(ParagraphImpl* paragraph) {
250 if (!fCacheIsOn) {
251 return false;
252 }
253 #ifdef PARAGRAPH_CACHE_STATS
254 ++fTotalRequests;
255 #endif
256 SkAutoMutexExclusive lock(fParagraphMutex);
257 ParagraphCacheKey key(paragraph);
258 std::unique_ptr<Entry>* entry = fLRUCacheMap.find(key);
259
260 if (!entry) {
261 // We have a cache miss
262 #ifdef PARAGRAPH_CACHE_STATS
263 ++fCacheMisses;
264 #endif
265 fChecker(paragraph, "missingParagraph", true);
266 return false;
267 }
268 updateTo(paragraph, entry->get());
269 fChecker(paragraph, "foundParagraph", true);
270 return true;
271 }
272
updateParagraph(ParagraphImpl * paragraph)273 bool ParagraphCache::updateParagraph(ParagraphImpl* paragraph) {
274 if (!fCacheIsOn) {
275 return false;
276 }
277 #ifdef PARAGRAPH_CACHE_STATS
278 ++fTotalRequests;
279 #endif
280 SkAutoMutexExclusive lock(fParagraphMutex);
281
282 ParagraphCacheKey key(paragraph);
283 std::unique_ptr<Entry>* entry = fLRUCacheMap.find(key);
284 if (!entry) {
285 // isTooMuchMemoryWasted(paragraph) not needed for now
286 if (isPossiblyTextEditing(paragraph)) {
287 // Skip this paragraph
288 return false;
289 }
290 ParagraphCacheValue* value = new ParagraphCacheValue(paragraph);
291 fLRUCacheMap.insert(key, std::make_unique<Entry>(value));
292 fChecker(paragraph, "addedParagraph", true);
293 fLastCachedValue = value;
294 return true;
295 } else {
296 // We do not have to update the paragraph
297 return false;
298 }
299 }
300
301 // Special situation: (very) long paragraph that is close to the last formatted paragraph
302 #define NOCACHE_PREFIX_LENGTH 40
isPossiblyTextEditing(ParagraphImpl * paragraph)303 bool ParagraphCache::isPossiblyTextEditing(ParagraphImpl* paragraph) {
304 if (fLastCachedValue == nullptr) {
305 return false;
306 }
307
308 auto& lastText = fLastCachedValue->fKey.fText;
309 auto& text = paragraph->fText;
310
311 if ((lastText.size() < NOCACHE_PREFIX_LENGTH) || (text.size() < NOCACHE_PREFIX_LENGTH)) {
312 // Either last text or the current are too short
313 return false;
314 }
315
316 if (std::strncmp(lastText.c_str(), text.c_str(), NOCACHE_PREFIX_LENGTH) == 0) {
317 // Texts have the same starts
318 return true;
319 }
320
321 if (std::strncmp(&lastText[lastText.size() - NOCACHE_PREFIX_LENGTH], &text[text.size() - NOCACHE_PREFIX_LENGTH], NOCACHE_PREFIX_LENGTH) == 0) {
322 // Texts have the same ends
323 return true;
324 }
325
326 // It does not look like editing the text
327 return false;
328 }
329 } // namespace textlayout
330 } // namespace skia
331