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 = fBuilder.allocRunTextPos(info.fFont, glyphCount, utf8RangeSize);
117     fCurrentGlyphs = runBuffer.glyphs;
118     fCurrentPoints = runBuffer.points();
119 
120     if (runBuffer.utf8text && fUtf8Text) {
121         memcpy(runBuffer.utf8text, fUtf8Text + info.utf8Range.begin(), utf8RangeSize);
122     }
123     fClusters = runBuffer.clusters;
124     fGlyphCount = glyphCount;
125     fClusterOffset = info.utf8Range.begin();
126 
127     return {runBuffer.glyphs,
128             runBuffer.points(),
129             nullptr,
130             runBuffer.clusters,
131             fCurrentPosition};
132 }
133 
commitRunBuffer(const RunInfo & info)134 void RunHandler::commitRunBuffer(const RunInfo& info) {
135     // for (size_t i = 0; i < info.glyphCount; ++i) {
136     //     SkASSERT(fClusters[i] >= info.utf8Range.begin());
137     //     // this fails for khmer example.
138     //     SkASSERT(fClusters[i] <  info.utf8Range.end());
139     // }
140     if (fCallbackFunction) {
141         fCallbackFunction(fCallbackContext,
142                           fUtf8Text,
143                           info.utf8Range.end(),
144                           info.glyphCount,
145                           fCurrentGlyphs,
146                           fCurrentPoints,
147                           fClusters,
148                           info.fFont);
149     }
150     SkASSERT(0 <= fClusterOffset);
151     for (int i = 0; i < fGlyphCount; ++i) {
152         SkASSERT(fClusters[i] >= (unsigned)fClusterOffset);
153         fClusters[i] -= fClusterOffset;
154     }
155     fCurrentPosition += info.fAdvance;
156     fTextOffset = std::max(fTextOffset, info.utf8Range.end());
157 }
158 
commitLine()159 void RunHandler::commitLine() {
160     if (fLineEndOffsets.empty() || fTextOffset > fLineEndOffsets.back()) {
161         // Ensure that fLineEndOffsets is monotonic.
162         fLineEndOffsets.push_back(fTextOffset);
163     }
164     fOffset += { 0, fMaxRunDescent + fMaxRunLeading - fMaxRunAscent };
165 }
166 
makeBlob()167 sk_sp<SkTextBlob> RunHandler::makeBlob() {
168     return fBuilder.make();
169 }
170 
selection_box(const SkFontMetrics & metrics,float advance,SkPoint pos)171 static SkRect selection_box(const SkFontMetrics& metrics,
172                             float advance,
173                             SkPoint pos) {
174     if (fabsf(advance) < 1.0f) {
175         advance = copysignf(1.0f, advance);
176     }
177     return SkRect{pos.x(),
178                   pos.y() + metrics.fAscent,
179                   pos.x() + advance,
180                   pos.y() + metrics.fDescent}.makeSorted();
181 }
182 
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)183 static void set_character_bounds(void* context,
184                                  const char* utf8Text,
185                                  size_t utf8TextBytes,
186                                  size_t glyphCount,
187                                  const SkGlyphID* glyphs,
188                                  const SkPoint* positions,
189                                  const uint32_t* clusters,
190                                  const SkFont& font)
191 {
192     SkASSERT(context);
193     SkASSERT(glyphCount > 0);
194     SkRect* cursors = (SkRect*)context;
195 
196     SkFontMetrics metrics;
197     font.getMetrics(&metrics);
198     std::unique_ptr<float[]> advances(new float[glyphCount]);
199     font.getWidths(glyphs, glyphCount, advances.get());
200 
201     // Loop over each cluster in this run.
202     size_t clusterStart = 0;
203     for (size_t glyphIndex = 0; glyphIndex < glyphCount; ++glyphIndex) {
204         if (glyphIndex + 1 < glyphCount  // more glyphs
205             && clusters[glyphIndex] == clusters[glyphIndex + 1]) {
206             continue; // multi-glyph cluster
207         }
208         unsigned textBegin = clusters[glyphIndex];
209         unsigned textEnd = utf8TextBytes;
210         for (size_t i = 0; i < glyphCount; ++i) {
211             if (clusters[i] >= textEnd) {
212                 textEnd = clusters[i] + 1;
213             }
214         }
215         for (size_t i = 0; i < glyphCount; ++i) {
216             if (clusters[i] > textBegin && clusters[i] < textEnd) {
217                 textEnd = clusters[i];
218                 if (textEnd == textBegin + 1) { break; }
219             }
220         }
221         SkASSERT(glyphIndex + 1 > clusterStart);
222         unsigned clusterGlyphCount = glyphIndex + 1 - clusterStart;
223         const SkPoint* clusterGlyphPositions = &positions[clusterStart];
224         const float* clusterAdvances = &advances[clusterStart];
225         clusterStart = glyphIndex + 1;  // for next loop
226 
227         SkRect clusterBox = selection_box(metrics, clusterAdvances[0], clusterGlyphPositions[0]);
228         for (unsigned i = 1; i < clusterGlyphCount; ++i) { // multiple glyphs
229             clusterBox.join(selection_box(metrics, clusterAdvances[i], clusterGlyphPositions[i]));
230         }
231         if (textBegin + 1 == textEnd) {  // single byte, fast path.
232             cursors[textBegin] = clusterBox;
233             continue;
234         }
235         int textCount = textEnd - textBegin;
236         int codePointCount = SkUTF::CountUTF8(utf8Text + textBegin, textCount);
237         if (codePointCount == 1) {  // single codepoint, fast path.
238             cursors[textBegin] = clusterBox;
239             continue;
240         }
241 
242         float width = clusterBox.width() / codePointCount;
243         SkASSERT(width > 0);
244         const char* ptr = utf8Text + textBegin;
245         const char* end = utf8Text + textEnd;
246         float x = clusterBox.left();
247         while (ptr < end) {  // for each codepoint in cluster
248             const char* nextPtr = ptr;
249             SkUTF::NextUTF8(&nextPtr, end);
250             int firstIndex = ptr - utf8Text;
251             float nextX = x + width;
252             cursors[firstIndex] = SkRect{x, clusterBox.top(), nextX, clusterBox.bottom()};
253             x = nextX;
254             ptr = nextPtr;
255         }
256     }
257 }
258 
Shape(const char * utf8Text,size_t textByteLen,const SkFont & font,const char * locale,float width)259 ShapeResult SkPlainTextEditor::Shape(const char* utf8Text,
260                           size_t textByteLen,
261                           const SkFont& font,
262                           const char* locale,
263                           float width)
264 {
265     ShapeResult result;
266     if (SkUTF::CountUTF8(utf8Text, textByteLen) < 0) {
267         utf8Text = nullptr;
268         textByteLen = 0;
269     }
270     std::unique_ptr<SkShaper> shaper = SkShaper::Make();
271     float height = font.getSpacing();
272     RunHandler runHandler(utf8Text, textByteLen);
273     if (textByteLen) {
274         result.glyphBounds.resize(textByteLen);
275         for (SkRect& c : result.glyphBounds) {
276             c = SkRect{-FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX};
277         }
278         runHandler.setRunCallback(set_character_bounds, result.glyphBounds.data());
279         // TODO: make use of locale in shaping.
280         shaper->shape(utf8Text, textByteLen, font, true, width, &runHandler);
281         if (runHandler.lineEndOffsets().size() > 1) {
282             result.lineBreakOffsets = runHandler.lineEndOffsets();
283             SkASSERT(result.lineBreakOffsets.size() > 0);
284             result.lineBreakOffsets.pop_back();
285         }
286         height = std::max(height, runHandler.endPoint().y());
287         result.blob = runHandler.makeBlob();
288     }
289     result.glyphBounds.push_back(runHandler.finalRect(font));
290     result.verticalAdvance = (int)ceilf(height);
291     result.wordBreaks = GetUtf8WordBoundaries(utf8Text, textByteLen, locale);
292     return result;
293 }
294