1 // Copyright 2019 Google LLC.
2 // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
3 
4 #include "modules/skplaintexteditor/src/shape.h"
5 
6 #include "include/core/SkFont.h"
7 #include "include/core/SkFontMetrics.h"
8 #include "include/core/SkPoint.h"
9 #include "include/core/SkRefCnt.h"
10 #include "include/core/SkScalar.h"
11 #include "include/core/SkString.h"
12 #include "include/core/SkTextBlob.h"
13 #include "include/core/SkTypes.h"
14 #include "include/private/SkTFitsIn.h"
15 #include "modules/skplaintexteditor/src/word_boundaries.h"
16 #include "modules/skshaper/include/SkShaper.h"
17 #include "src/core/SkTextBlobPriv.h"
18 #include "src/utils/SkUTF.h"
19 
20 #include <limits.h>
21 #include <string.h>
22 
23 
24 using namespace SkPlainTextEditor;
25 
26 namespace {
27 class RunHandler final : public SkShaper::RunHandler {
28 public:
RunHandler(const char * utf8Text,size_t)29     RunHandler(const char* utf8Text, size_t) : fUtf8Text(utf8Text) {}
30     using RunCallback = void (*)(void* context,
31                                  const char* utf8Text,
32                                   size_t utf8TextBytes,
33                                   size_t glyphCount,
34                                   const SkGlyphID* glyphs,
35                                   const SkPoint* positions,
36                                   const uint32_t* clusters,
37                                   const SkFont& font);
setRunCallback(RunCallback f,void * context)38     void setRunCallback(RunCallback f, void* context) {
39         fCallbackContext = context;
40         fCallbackFunction = f;
41     }
42 
43     sk_sp<SkTextBlob> makeBlob();
endPoint() const44     SkPoint endPoint() const { return fOffset; }
finalPosition() const45     SkPoint finalPosition() const { return fCurrentPosition; }
46 
47     void beginLine() override;
48     void runInfo(const RunInfo&) override;
49     void commitRunInfo() override;
50     SkShaper::RunHandler::Buffer runBuffer(const RunInfo&) override;
51     void commitRunBuffer(const RunInfo&) override;
52     void commitLine() override;
53 
lineEndOffsets() const54     const std::vector<size_t>& lineEndOffsets() const { return fLineEndOffsets; }
55 
finalRect(const SkFont & font) const56     SkRect finalRect(const SkFont& font) const {
57         if (0 == fMaxRunAscent || 0 == fMaxRunDescent) {
58             SkFontMetrics metrics;
59             font.getMetrics(&metrics);
60             return {fCurrentPosition.x(),
61                     fCurrentPosition.y(),
62                     fCurrentPosition.x() + font.getSize(),
63                     fCurrentPosition.y() + metrics.fDescent - metrics.fAscent};
64         } else {
65             return {fCurrentPosition.x(),
66                     fCurrentPosition.y() + fMaxRunAscent,
67                     fCurrentPosition.x() + font.getSize(),
68                     fCurrentPosition.y() + fMaxRunDescent};
69         }
70     }
71 
72 
73 private:
74     SkTextBlobBuilder fBuilder;
75     std::vector<size_t> fLineEndOffsets;
76     const SkGlyphID* fCurrentGlyphs = nullptr;
77     const SkPoint* fCurrentPoints = nullptr;
78     void* fCallbackContext = nullptr;
79     RunCallback fCallbackFunction = nullptr;
80     char const * const fUtf8Text;
81     size_t fTextOffset = 0;
82     uint32_t* fClusters = nullptr;
83     int fClusterOffset = 0;
84     int fGlyphCount = 0;
85     SkScalar fMaxRunAscent = 0;
86     SkScalar fMaxRunDescent = 0;
87     SkScalar fMaxRunLeading = 0;
88     SkPoint fCurrentPosition = {0, 0};
89     SkPoint fOffset = {0, 0};
90 };
91 }  // namespace
92 
beginLine()93 void RunHandler::beginLine() {
94     fCurrentPosition = fOffset;
95     fMaxRunAscent = 0;
96     fMaxRunDescent = 0;
97     fMaxRunLeading = 0;
98 }
99 
runInfo(const SkShaper::RunHandler::RunInfo & info)100 void RunHandler::runInfo(const SkShaper::RunHandler::RunInfo& info) {
101     SkFontMetrics metrics;
102     info.fFont.getMetrics(&metrics);
103     fMaxRunAscent = std::min(fMaxRunAscent, metrics.fAscent);
104     fMaxRunDescent = std::max(fMaxRunDescent, metrics.fDescent);
105     fMaxRunLeading = std::max(fMaxRunLeading, metrics.fLeading);
106 }
107 
commitRunInfo()108 void RunHandler::commitRunInfo() {
109     fCurrentPosition.fY -= fMaxRunAscent;
110 }
111 
runBuffer(const RunInfo & info)112 SkShaper::RunHandler::Buffer RunHandler::runBuffer(const RunInfo& info) {
113     int glyphCount = SkTFitsIn<int>(info.glyphCount) ? info.glyphCount : INT_MAX;
114     int utf8RangeSize = SkTFitsIn<int>(info.utf8Range.size()) ? info.utf8Range.size() : INT_MAX;
115 
116     const auto& runBuffer = SkTextBlobBuilderPriv::AllocRunTextPos(&fBuilder, info.fFont, glyphCount,
117                                                                    utf8RangeSize, SkString());
118     fCurrentGlyphs = runBuffer.glyphs;
119     fCurrentPoints = runBuffer.points();
120 
121     if (runBuffer.utf8text && fUtf8Text) {
122         memcpy(runBuffer.utf8text, fUtf8Text + info.utf8Range.begin(), utf8RangeSize);
123     }
124     fClusters = runBuffer.clusters;
125     fGlyphCount = glyphCount;
126     fClusterOffset = info.utf8Range.begin();
127 
128     return {runBuffer.glyphs,
129             runBuffer.points(),
130             nullptr,
131             runBuffer.clusters,
132             fCurrentPosition};
133 }
134 
commitRunBuffer(const RunInfo & info)135 void RunHandler::commitRunBuffer(const RunInfo& info) {
136     // for (size_t i = 0; i < info.glyphCount; ++i) {
137     //     SkASSERT(fClusters[i] >= info.utf8Range.begin());
138     //     // this fails for khmer example.
139     //     SkASSERT(fClusters[i] <  info.utf8Range.end());
140     // }
141     if (fCallbackFunction) {
142         fCallbackFunction(fCallbackContext,
143                           fUtf8Text,
144                           info.utf8Range.end(),
145                           info.glyphCount,
146                           fCurrentGlyphs,
147                           fCurrentPoints,
148                           fClusters,
149                           info.fFont);
150     }
151     SkASSERT(0 <= fClusterOffset);
152     for (int i = 0; i < fGlyphCount; ++i) {
153         SkASSERT(fClusters[i] >= (unsigned)fClusterOffset);
154         fClusters[i] -= fClusterOffset;
155     }
156     fCurrentPosition += info.fAdvance;
157     fTextOffset = std::max(fTextOffset, info.utf8Range.end());
158 }
159 
commitLine()160 void RunHandler::commitLine() {
161     if (fLineEndOffsets.empty() || fTextOffset > fLineEndOffsets.back()) {
162         // Ensure that fLineEndOffsets is monotonic.
163         fLineEndOffsets.push_back(fTextOffset);
164     }
165     fOffset += { 0, fMaxRunDescent + fMaxRunLeading - fMaxRunAscent };
166 }
167 
makeBlob()168 sk_sp<SkTextBlob> RunHandler::makeBlob() {
169     return fBuilder.make();
170 }
171 
selection_box(const SkFontMetrics & metrics,float advance,SkPoint pos)172 static SkRect selection_box(const SkFontMetrics& metrics,
173                             float advance,
174                             SkPoint pos) {
175     if (fabsf(advance) < 1.0f) {
176         advance = copysignf(1.0f, advance);
177     }
178     return SkRect{pos.x(),
179                   pos.y() + metrics.fAscent,
180                   pos.x() + advance,
181                   pos.y() + metrics.fDescent}.makeSorted();
182 }
183 
set_character_bounds(void * context,const char * utf8Text,size_t utf8TextBytes,size_t glyphCount,const SkGlyphID * glyphs,const SkPoint * positions,const uint32_t * clusters,const SkFont & font)184 static void set_character_bounds(void* context,
185                                  const char* utf8Text,
186                                  size_t utf8TextBytes,
187                                  size_t glyphCount,
188                                  const SkGlyphID* glyphs,
189                                  const SkPoint* positions,
190                                  const uint32_t* clusters,
191                                  const SkFont& font)
192 {
193     SkASSERT(context);
194     SkASSERT(glyphCount > 0);
195     SkRect* cursors = (SkRect*)context;
196 
197     SkFontMetrics metrics;
198     font.getMetrics(&metrics);
199     std::unique_ptr<float[]> advances(new float[glyphCount]);
200     font.getWidths(glyphs, glyphCount, advances.get());
201 
202     // Loop over each cluster in this run.
203     size_t clusterStart = 0;
204     for (size_t glyphIndex = 0; glyphIndex < glyphCount; ++glyphIndex) {
205         if (glyphIndex + 1 < glyphCount  // more glyphs
206             && clusters[glyphIndex] == clusters[glyphIndex + 1]) {
207             continue; // multi-glyph cluster
208         }
209         unsigned textBegin = clusters[glyphIndex];
210         unsigned textEnd = utf8TextBytes;
211         for (size_t i = 0; i < glyphCount; ++i) {
212             if (clusters[i] >= textEnd) {
213                 textEnd = clusters[i] + 1;
214             }
215         }
216         for (size_t i = 0; i < glyphCount; ++i) {
217             if (clusters[i] > textBegin && clusters[i] < textEnd) {
218                 textEnd = clusters[i];
219                 if (textEnd == textBegin + 1) { break; }
220             }
221         }
222         SkASSERT(glyphIndex + 1 > clusterStart);
223         unsigned clusterGlyphCount = glyphIndex + 1 - clusterStart;
224         const SkPoint* clusterGlyphPositions = &positions[clusterStart];
225         const float* clusterAdvances = &advances[clusterStart];
226         clusterStart = glyphIndex + 1;  // for next loop
227 
228         SkRect clusterBox = selection_box(metrics, clusterAdvances[0], clusterGlyphPositions[0]);
229         for (unsigned i = 1; i < clusterGlyphCount; ++i) { // multiple glyphs
230             clusterBox.join(selection_box(metrics, clusterAdvances[i], clusterGlyphPositions[i]));
231         }
232         if (textBegin + 1 == textEnd) {  // single byte, fast path.
233             cursors[textBegin] = clusterBox;
234             continue;
235         }
236         int textCount = textEnd - textBegin;
237         int codePointCount = SkUTF::CountUTF8(utf8Text + textBegin, textCount);
238         if (codePointCount == 1) {  // single codepoint, fast path.
239             cursors[textBegin] = clusterBox;
240             continue;
241         }
242 
243         float width = clusterBox.width() / codePointCount;
244         SkASSERT(width > 0);
245         const char* ptr = utf8Text + textBegin;
246         const char* end = utf8Text + textEnd;
247         float x = clusterBox.left();
248         while (ptr < end) {  // for each codepoint in cluster
249             const char* nextPtr = ptr;
250             SkUTF::NextUTF8(&nextPtr, end);
251             int firstIndex = ptr - utf8Text;
252             float nextX = x + width;
253             cursors[firstIndex] = SkRect{x, clusterBox.top(), nextX, clusterBox.bottom()};
254             x = nextX;
255             ptr = nextPtr;
256         }
257     }
258 }
259 
Shape(const char * utf8Text,size_t textByteLen,const SkFont & font,const char * locale,float width)260 ShapeResult SkPlainTextEditor::Shape(const char* utf8Text,
261                           size_t textByteLen,
262                           const SkFont& font,
263                           const char* locale,
264                           float width)
265 {
266     ShapeResult result;
267     if (SkUTF::CountUTF8(utf8Text, textByteLen) < 0) {
268         utf8Text = nullptr;
269         textByteLen = 0;
270     }
271     std::unique_ptr<SkShaper> shaper = SkShaper::Make();
272     float height = font.getSpacing();
273     RunHandler runHandler(utf8Text, textByteLen);
274     if (textByteLen) {
275         result.glyphBounds.resize(textByteLen);
276         for (SkRect& c : result.glyphBounds) {
277             c = SkRect{-FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX};
278         }
279         runHandler.setRunCallback(set_character_bounds, result.glyphBounds.data());
280         // TODO: make use of locale in shaping.
281         shaper->shape(utf8Text, textByteLen, font, true, width, &runHandler);
282         if (runHandler.lineEndOffsets().size() > 1) {
283             result.lineBreakOffsets = runHandler.lineEndOffsets();
284             SkASSERT(result.lineBreakOffsets.size() > 0);
285             result.lineBreakOffsets.pop_back();
286         }
287         height = std::max(height, runHandler.endPoint().y());
288         result.blob = runHandler.makeBlob();
289     }
290     result.glyphBounds.push_back(runHandler.finalRect(font));
291     result.verticalAdvance = (int)ceilf(height);
292     result.wordBreaks = GetUtf8WordBoundaries(utf8Text, textByteLen, locale);
293     return result;
294 }
295