1 /*
2  * Copyright 2018 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 
8 #include "SkClusterator.h"
9 
10 #include "SkGlyphRun.h"
11 #include "SkTo.h"
12 #include "SkUTF.h"
13 
14 static bool is_reversed(const uint32_t* clusters, uint32_t count) {
15     // "ReversedChars" is how PDF deals with RTL text.
16     // return true if more than one cluster and monotonicly decreasing to zero.
17     if (count < 2 || clusters[0] == 0 || clusters[count - 1] != 0) {
18         return false;
19     }
20     for (uint32_t i = 0; i + 1 < count; ++i) {
21         if (clusters[i + 1] > clusters[i]) {
22             return false;
23         }
24     }
25     return true;
26 }
27 
28 SkClusterator::SkClusterator(const SkGlyphRun& run)
29     : fClusters(run.clusters().data())
30     , fUtf8Text(run.text().data())
31     , fGlyphCount(SkToU32(run.glyphsIDs().size()))
32     , fTextByteLength(SkToU32(run.text().size()))
33 {
34     if (fClusters) {
35         SkASSERT(fUtf8Text && fTextByteLength > 0 && fGlyphCount > 0);
36         fReversedChars = is_reversed(fClusters, fGlyphCount);
37     } else {
38         SkASSERT(!fUtf8Text && fTextByteLength == 0);
39     }
40 }
41 
42 SkClusterator::Cluster SkClusterator::next() {
43     if (fCurrentGlyphIndex >= fGlyphCount) {
44         return Cluster{nullptr, 0, 0, 0};
45     }
46     if (!fClusters || !fUtf8Text) {
47         return Cluster{nullptr, 0, fCurrentGlyphIndex++, 1};
48     }
49     uint32_t clusterGlyphIndex = fCurrentGlyphIndex;
50     uint32_t cluster = fClusters[clusterGlyphIndex];
51     do {
52         ++fCurrentGlyphIndex;
53     } while (fCurrentGlyphIndex < fGlyphCount && cluster == fClusters[fCurrentGlyphIndex]);
54     uint32_t clusterGlyphCount = fCurrentGlyphIndex - clusterGlyphIndex;
55     uint32_t clusterEnd = fTextByteLength;
56     for (unsigned i = 0; i < fGlyphCount; ++i) {
57        uint32_t c = fClusters[i];
58        if (c > cluster && c < clusterEnd) {
59            clusterEnd = c;
60        }
61     }
62     uint32_t clusterLen = clusterEnd - cluster;
63     return Cluster{fUtf8Text + cluster, clusterLen, clusterGlyphIndex, clusterGlyphCount};
64 }
65