blob: 750c51621e86e7a2f7bdc70e364aaf922a2cf957 [file] [log] [blame]
halcanary13cba492016-08-03 10:43:55 -07001/*
2 * Copyright 2016 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#include "SkShaper.h"
8#include "SkStream.h"
9#include "SkTextBlob.h"
10#include "SkTypeface.h"
11
12struct SkShaper::Impl {
13 sk_sp<SkTypeface> fTypeface;
14};
15
16SkShaper::SkShaper(sk_sp<SkTypeface> tf) : fImpl(new Impl) {
17 fImpl->fTypeface = tf ? std::move(tf) : SkTypeface::MakeDefault();
18}
19
20SkShaper::~SkShaper() {}
21
22bool SkShaper::good() const { return true; }
23
halcanary3eee9d92016-09-10 07:01:53 -070024// This example only uses public API, so we don't use SkUTF8_NextUnichar.
25unsigned utf8_lead_byte_to_count(const char* ptr) {
26 uint8_t c = *(const uint8_t*)ptr;
27 SkASSERT(c <= 0xF7);
28 SkASSERT((c & 0xC0) != 0x80);
29 return (((0xE5 << 24) >> ((unsigned)c >> 4 << 1)) & 3) + 1;
30}
31
halcanary13cba492016-08-03 10:43:55 -070032SkScalar SkShaper::shape(SkTextBlobBuilder* builder,
33 const SkPaint& srcPaint,
34 const char* utf8text,
35 size_t textBytes,
Ben Wagnera25fbef2017-08-30 13:56:19 -040036 bool leftToRight,
halcanary13cba492016-08-03 10:43:55 -070037 SkPoint point) const {
Ben Wagnera25fbef2017-08-30 13:56:19 -040038 sk_ignore_unused_variable(leftToRight);
39
halcanary13cba492016-08-03 10:43:55 -070040 SkPaint paint(srcPaint);
41 paint.setTypeface(fImpl->fTypeface);
42 paint.setTextEncoding(SkPaint::kUTF8_TextEncoding);
43 int glyphCount = paint.countText(utf8text, textBytes);
44 if (glyphCount <= 0) {
45 return 0;
46 }
47 SkRect bounds;
48 (void)paint.measureText(utf8text, textBytes, &bounds);
49 paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
halcanary3eee9d92016-09-10 07:01:53 -070050 const SkTextBlobBuilder::RunBuffer& runBuffer =
51 builder->allocRunTextPosH(paint, glyphCount, point.y(), textBytes, SkString(), &bounds);
52 memcpy(runBuffer.utf8text, utf8text, textBytes);
53 const char* txtPtr = utf8text;
54 for (int i = 0; i < glyphCount; ++i) {
55 // Each charater maps to exactly one glyph via SkGlyphCache::unicharToGlyph().
56 runBuffer.clusters[i] = SkToU32(txtPtr - utf8text);
57 txtPtr += utf8_lead_byte_to_count(txtPtr);
58 SkASSERT(txtPtr <= utf8text + textBytes);
59 }
halcanary13cba492016-08-03 10:43:55 -070060 paint.setTextEncoding(SkPaint::kUTF8_TextEncoding);
61 (void)paint.textToGlyphs(utf8text, textBytes, runBuffer.glyphs);
62 (void)paint.getTextWidths(utf8text, textBytes, runBuffer.pos);
63 SkScalar x = point.x();
64 for (int i = 0; i < glyphCount; ++i) {
65 SkScalar w = runBuffer.pos[i];
66 runBuffer.pos[i] = x;
67 x += w;
68 }
69 return (SkScalar)x;
70}