Flutter Engine
The Flutter Engine
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
SkShaper_coretext.cpp
Go to the documentation of this file.
1/*
2 * Copyright 2020 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
9
10#ifdef SK_BUILD_FOR_MAC
11#import <ApplicationServices/ApplicationServices.h>
12#endif
13
14#ifdef SK_BUILD_FOR_IOS
15#include <CoreText/CoreText.h>
16#include <CoreText/CTFontManager.h>
17#include <CoreGraphics/CoreGraphics.h>
18#include <CoreFoundation/CoreFoundation.h>
19#endif
20
23#include "src/base/SkUTF.h"
24#include "src/core/SkFontPriv.h"
27
28#include <vector>
29#include <utility>
30
31using namespace skia_private;
32
34public:
36private:
37#if !defined(SK_DISABLE_LEGACY_SKSHAPER_FUNCTIONS)
38 void shape(const char* utf8, size_t utf8Bytes,
39 const SkFont& srcFont,
40 bool leftToRight,
42 RunHandler*) const override;
43
44 void shape(const char* utf8, size_t utf8Bytes,
45 FontRunIterator&,
46 BiDiRunIterator&,
48 LanguageRunIterator&,
50 RunHandler*) const override;
51#endif
52
53 void shape(const char* utf8, size_t utf8Bytes,
54 FontRunIterator&,
55 BiDiRunIterator&,
57 LanguageRunIterator&,
58 const Feature*, size_t featureSize,
60 RunHandler*) const override;
61};
62
63// CTFramesetter/CTFrame can do this, but require version 10.14
65 CTTypesetterRef fTypesetter;
66 double fWidth;
67 CFIndex fStart;
68
69public:
70 LineBreakIter(CTTypesetterRef ts, SkScalar width) : fTypesetter(ts), fWidth(width) {
71 fStart = 0;
72 }
73
74 SkUniqueCFRef<CTLineRef> nextLine() {
75 CFRange stringRange {fStart, CTTypesetterSuggestLineBreak(fTypesetter, fStart, fWidth)};
76 if (stringRange.length == 0) {
77 return nullptr;
78 }
79 fStart += stringRange.length;
80 return SkUniqueCFRef<CTLineRef>(CTTypesetterCreateLine(fTypesetter, stringRange));
81 }
82};
83
84[[maybe_unused]] static void dict_add_double(CFMutableDictionaryRef d, const void* name, double value) {
85 SkUniqueCFRef<CFNumberRef> number(
86 CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &value));
87 CFDictionaryAddValue(d, name, number.get());
88}
89
90static SkUniqueCFRef<CTFontRef> create_ctfont_from_font(const SkFont& font) {
91 auto typeface = font.getTypeface();
92 auto ctfont = SkTypeface_GetCTFontRef(typeface);
93 if (!ctfont) {
94 return nullptr;
95 }
96 return SkUniqueCFRef<CTFontRef>(
97 CTFontCreateCopyWithAttributes(ctfont, font.getSize(), nullptr, nullptr));
98}
99
100static SkFont run_to_font(CTRunRef run, const SkFont& orig) {
101 CFDictionaryRef attr = CTRunGetAttributes(run);
102 CTFontRef ct = (CTFontRef)CFDictionaryGetValue(attr, kCTFontAttributeName);
103 if (!ct) {
104 SkDebugf("no ctfont in Run Attributes\n");
105 CFShow(attr);
106 return orig;
107 }
108 // Do I need to add a local cache, or allow the caller to manage this lookup?
109 SkFont font(orig);
110 font.setTypeface(SkMakeTypefaceFromCTFont(ct));
111 return font;
112}
113
114namespace {
115class UTF16ToUTF8IndicesMap {
116public:
117 /** Builds a UTF-16 to UTF-8 indices map; the text is not retained
118 * @return true if successful
119 */
120 bool setUTF8(const char* utf8, size_t size) {
121 SkASSERT(utf8 != nullptr);
122
123 if (!SkTFitsIn<int32_t>(size)) {
124 SkDEBUGF("UTF16ToUTF8IndicesMap: text too long");
125 return false;
126 }
127
128 auto utf16Size = SkUTF::UTF8ToUTF16(nullptr, 0, utf8, size);
129 if (utf16Size < 0) {
130 SkDEBUGF("UTF16ToUTF8IndicesMap: Invalid utf8 input");
131 return false;
132 }
133
134 // utf16Size+1 to also store the size
135 fUtf16ToUtf8Indices = std::vector<size_t>(utf16Size + 1);
136 auto utf16 = fUtf16ToUtf8Indices.begin();
137 auto utf8Begin = utf8, utf8End = utf8 + size;
138 while (utf8Begin < utf8End) {
139 *utf16 = utf8Begin - utf8;
140 utf16 += SkUTF::ToUTF16(SkUTF::NextUTF8(&utf8Begin, utf8End), nullptr);
141 }
142 *utf16 = size;
143
144 return true;
145 }
146
147 size_t mapIndex(size_t index) const {
148 SkASSERT(index < fUtf16ToUtf8Indices.size());
149 return fUtf16ToUtf8Indices[index];
150 }
151
152 std::pair<size_t, size_t> mapRange(size_t start, size_t size) const {
153 auto utf8Start = mapIndex(start);
154 return {utf8Start, mapIndex(start + size) - utf8Start};
155 }
156private:
157 std::vector<size_t> fUtf16ToUtf8Indices;
158};
159} // namespace
160
161// kCTTrackingAttributeName not available until 10.12
162const CFStringRef kCTTracking_AttributeName = CFSTR("CTTracking");
163
164#if !defined(SK_DISABLE_LEGACY_SKSHAPER_FUNCTIONS)
165void SkShaper_CoreText::shape(const char* utf8,
166 size_t utf8Bytes,
167 FontRunIterator& font,
168 BiDiRunIterator& bidi,
170 LanguageRunIterator& lang,
172 RunHandler* handler) const {
173 return this->shape(utf8, utf8Bytes, font, bidi, script, lang, nullptr, 0, width, handler);
174}
175
176void SkShaper_CoreText::shape(const char* utf8,
177 size_t utf8Bytes,
178 const SkFont& font,
179 bool,
181 RunHandler* handler) const {
182 std::unique_ptr<FontRunIterator> fontRuns(
183 MakeFontMgrRunIterator(utf8, utf8Bytes, font, nullptr));
184 if (!fontRuns) {
185 return;
186 }
187 // bidi, script, and lang are all unused so we can construct them with empty data.
188 TrivialBiDiRunIterator bidi{0, 0};
190 TrivialLanguageRunIterator lang{nullptr, 0};
191 return this->shape(utf8, utf8Bytes, *fontRuns, bidi, script, lang, nullptr, 0, width, handler);
192}
193#endif
194
195void SkShaper_CoreText::shape(const char* utf8,
196 size_t utf8Bytes,
197 FontRunIterator& fontRuns,
198 BiDiRunIterator&,
200 LanguageRunIterator&,
201 const Feature*,
202 size_t,
204 RunHandler* handler) const {
205 SkFont font;
206 if (!fontRuns.atEnd()) {
207 fontRuns.consume();
208 font = fontRuns.currentFont();
209 }
210
211 SkUniqueCFRef<CFStringRef> textString(
212 CFStringCreateWithBytes(kCFAllocatorDefault, (const uint8_t*)utf8, utf8Bytes,
213 kCFStringEncodingUTF8, false));
214
215 UTF16ToUTF8IndicesMap utf8IndicesMap;
216 if (!utf8IndicesMap.setUTF8(utf8, utf8Bytes)) {
217 return;
218 }
219
220 SkUniqueCFRef<CTFontRef> ctfont = create_ctfont_from_font(font);
221 if (!ctfont) {
222 return;
223 }
224
225 SkUniqueCFRef<CFMutableDictionaryRef> attr(
226 CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
227 &kCFTypeDictionaryKeyCallBacks,
228 &kCFTypeDictionaryValueCallBacks));
229 CFDictionaryAddValue(attr.get(), kCTFontAttributeName, ctfont.get());
230 if ((false)) {
231 // trying to see what these affect
233 dict_add_double(attr.get(), kCTKernAttributeName, 0.0);
234 }
235
236 SkUniqueCFRef<CFAttributedStringRef> attrString(
237 CFAttributedStringCreate(kCFAllocatorDefault, textString.get(), attr.get()));
238
239 SkUniqueCFRef<CTTypesetterRef> typesetter(
240 CTTypesetterCreateWithAttributedString(attrString.get()));
241
242 // We have to compute RunInfos in a loop, and then reuse them in a 2nd loop,
243 // so we store them in an array (we reuse the array's storage for each line).
244 std::vector<SkFont> fontStorage;
245 std::vector<SkShaper::RunHandler::RunInfo> infos;
246
247 LineBreakIter iter(typesetter.get(), width);
248 while (SkUniqueCFRef<CTLineRef> line = iter.nextLine()) {
249 CFArrayRef run_array = CTLineGetGlyphRuns(line.get());
250 CFIndex runCount = CFArrayGetCount(run_array);
251 if (runCount == 0) {
252 continue;
253 }
254 handler->beginLine();
255 fontStorage.clear();
256 fontStorage.reserve(runCount); // ensure the refs won't get invalidated
257 infos.clear();
258 for (CFIndex j = 0; j < runCount; ++j) {
259 CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(run_array, j);
260 CFIndex runGlyphs = CTRunGetGlyphCount(run);
261
262 SkASSERT(sizeof(CGGlyph) == sizeof(uint16_t));
263
264 AutoSTArray<4096, CGSize> advances(runGlyphs);
265 CTRunGetAdvances(run, {0, runGlyphs}, advances.data());
266 SkScalar adv = 0;
267 for (CFIndex k = 0; k < runGlyphs; ++k) {
268 adv += advances[k].width;
269 }
270
271 CFRange cfRange = CTRunGetStringRange(run);
272 auto range = utf8IndicesMap.mapRange(cfRange.location, cfRange.length);
273
274 fontStorage.push_back(run_to_font(run, font));
275 infos.push_back({
276 fontStorage.back(), // info just stores a ref to the font
277 0, // need fBidiLevel
278 {adv, 0},
279 (size_t)runGlyphs,
280 {range.first, range.second},
281 });
282 handler->runInfo(infos.back());
283 }
284 handler->commitRunInfo();
285
286 // Now loop through again and fill in the buffers
287 SkScalar lineAdvance = 0;
288 for (CFIndex j = 0; j < runCount; ++j) {
289 const auto& info = infos[j];
290 auto buffer = handler->runBuffer(info);
291
292 CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(run_array, j);
293 CFIndex runGlyphs = info.glyphCount;
294 SkASSERT(CTRunGetGlyphCount(run) == (CFIndex)info.glyphCount);
295
296 CTRunGetGlyphs(run, {0, runGlyphs}, buffer.glyphs);
297
298 AutoSTArray<4096, CGPoint> positions(runGlyphs);
299 CTRunGetPositions(run, {0, runGlyphs}, positions.data());
301 if (buffer.clusters) {
302 indices.reset(runGlyphs);
303 CTRunGetStringIndices(run, {0, runGlyphs}, indices.data());
304 }
305
306 for (CFIndex k = 0; k < runGlyphs; ++k) {
307 buffer.positions[k] = {
308 buffer.point.fX + SkScalarFromCGFloat(positions[k].x) - lineAdvance,
309 buffer.point.fY,
310 };
311 if (buffer.offsets) {
312 buffer.offsets[k] = {0, 0}; // offset relative to the origin for this glyph
313 }
314 if (buffer.clusters) {
315 buffer.clusters[k] = utf8IndicesMap.mapIndex(indices[k]);
316 }
317 }
318 handler->commitRunBuffer(info);
319 lineAdvance += info.fAdvance.fX;
320 }
321 handler->commitLine();
322 }
323}
324
325namespace SkShapers::CT {
326std::unique_ptr<SkShaper> CoreText() { return std::make_unique<SkShaper_CoreText>(); }
327} // namespace SkShapers::CT
static void info(const char *fmt,...) SK_PRINTF_LIKE(1
Definition: DM.cpp:213
#define SkASSERT(cond)
Definition: SkAssert.h:116
void SK_SPI SkDebugf(const char format[],...) SK_PRINTF_LIKE(1
#define SkDEBUGF(...)
Definition: SkDebug.h:24
static void dict_add_double(CFMutableDictionaryRef d, const void *name, double value)
static SkUniqueCFRef< CTFontRef > create_ctfont_from_font(const SkFont &font)
const CFStringRef kCTTracking_AttributeName
static SkFont run_to_font(CTRunRef run, const SkFont &orig)
LineBreakIter(CTTypesetterRef ts, SkScalar width)
SkUniqueCFRef< CTLineRef > nextLine()
Definition: SkFont.h:35
static std::unique_ptr< FontRunIterator > MakeFontMgrRunIterator(const char *utf8, size_t utf8Bytes, const SkFont &font, sk_sp< SkFontMgr > fallback)
Definition: SkShaper.cpp:187
void reset(int count)
Definition: SkTemplates.h:195
const T * data() const
Definition: SkTemplates.h:251
VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE auto & d
Definition: main.cc:19
float SkScalar
Definition: extension.cpp:12
uint8_t value
double x
SKSHAPER_API std::unique_ptr< SkShaper > CoreText()
SKSHAPER_API std::unique_ptr< SkShaper::ScriptRunIterator > ScriptRunIterator(const char *utf8, size_t utf8Bytes)
SKSHAPER_API std::unique_ptr< SkShaper::BiDiRunIterator > TrivialBiDiRunIterator(size_t utf8Bytes, uint8_t bidiLevel)
SKSHAPER_API std::unique_ptr< SkShaper::ScriptRunIterator > TrivialScriptRunIterator(size_t utf8Bytes, SkFourByteTag scriptTag)
SK_SPI int UTF8ToUTF16(uint16_t dst[], int dstCapacity, const char src[], size_t srcByteLength)
Definition: SkUTF.cpp:259
SK_SPI SkUnichar NextUTF8(const char **ptr, const char *end)
Definition: SkUTF.cpp:118
SK_SPI size_t ToUTF16(SkUnichar uni, uint16_t utf16[2]=nullptr)
Definition: SkUTF.cpp:243
DEF_SWITCHES_START aot vmservice shared library name
Definition: switches.h:32
DEF_SWITCHES_START aot vmservice shared library Name of the *so containing AOT compiled Dart assets for launching the service isolate vm snapshot The VM snapshot data that will be memory mapped as read only SnapshotAssetPath must be present isolate snapshot The isolate snapshot data that will be memory mapped as read only SnapshotAssetPath must be present cache dir Path to the cache directory This is different from the persistent_cache_path in embedder which is used for Skia shader cache icu native lib Path to the library file that exports the ICU data vm service The hostname IP address on which the Dart VM Service should be served If not defaults to or::depending on whether ipv6 is specified vm service A custom Dart VM Service port The default is to pick a randomly available open port disable vm Disable the Dart VM Service The Dart VM Service is never available in release mode disable vm service Disable mDNS Dart VM Service publication Bind to the IPv6 localhost address for the Dart VM Service Ignored if vm service host is set endless trace buffer
Definition: switches.h:126
it will be possible to load the file into Perfetto s trace viewer disable asset Prevents usage of any non test fonts unless they were explicitly Loaded via prefetched default font Indicates whether the embedding started a prefetch of the default font manager before creating the engine run In non interactive keep the shell running after the Dart script has completed enable serial On low power devices with low core running concurrent GC tasks on threads can cause them to contend with the UI thread which could potentially lead to jank This option turns off all concurrent GC activities domain network JSON encoded network policy per domain This overrides the DisallowInsecureConnections switch Embedder can specify whether to allow or disallow insecure connections at a domain level old gen heap size
Definition: switches.h:259
font
Font Metadata and Metrics.
Definition: run.py:1
int32_t width