summaryrefslogtreecommitdiff
path: root/libs/minikin/MeasuredText.cpp
blob: 8a37dc76267989658e42162ca8b73680ce709db1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define LOG_TAG "Minikin"
#include "minikin/MeasuredText.h"

#include "BidiUtils.h"
#include "LayoutSplitter.h"
#include "LayoutUtils.h"
#include "LineBreakerUtil.h"
#include "minikin/Characters.h"
#include "minikin/Layout.h"

namespace minikin {

// Helper class for composing character advances.
class AdvancesCompositor {
public:
    AdvancesCompositor(std::vector<float>* outAdvances, std::vector<uint8_t>* flags,
                       LayoutPieces* outPieces)
            : mOutAdvances(outAdvances), mFlags(flags), mOutPieces(outPieces) {}

    void setNextRange(const Range& range, bool dir) {
        mRange = range;
        mDir = dir;
    }

    void operator()(const LayoutPiece& layoutPiece, const MinikinPaint& paint,
                    const MinikinRect& bounds) {
        const std::vector<float>& advances = layoutPiece.advances();
        std::copy(advances.begin(), advances.end(), mOutAdvances->begin() + mRange.getStart());

        if (bounds.mLeft < 0 || bounds.mRight > layoutPiece.advance()) {
            for (uint32_t i : mRange) {
                (*mFlags)[i] |= MeasuredText::MAY_OVERHANG_BIT;
            }
        }

        if (mOutPieces != nullptr) {
            mOutPieces->insert(mRange, 0 /* no edit */, layoutPiece, mDir, paint, bounds);
        }
    }

private:
    Range mRange;
    bool mDir;
    std::vector<float>* mOutAdvances;
    std::vector<uint8_t>* mFlags;
    LayoutPieces* mOutPieces;
};

void StyleRun::getMetrics(const U16StringPiece& textBuf, std::vector<float>* advances,
                          std::vector<uint8_t>* flags, LayoutPieces* precomputed,
                          bool boundsCalculation, LayoutPieces* outPieces) const {
    AdvancesCompositor compositor(advances, flags, outPieces);
    const Bidi bidiFlag = mIsRtl ? Bidi::FORCE_RTL : Bidi::FORCE_LTR;
    const uint32_t paintId =
            (precomputed == nullptr) ? LayoutPieces::kNoPaintId : precomputed->findPaintId(mPaint);
    for (const BidiText::RunInfo info : BidiText(textBuf, mRange, bidiFlag)) {
        for (const auto[context, piece] : LayoutSplitter(textBuf, info.range, info.isRtl)) {
            compositor.setNextRange(piece, info.isRtl);
            if (paintId == LayoutPieces::kNoPaintId) {
                LayoutCache::getInstance().getOrCreate(
                        textBuf.substr(context), piece - context.getStart(), mPaint, info.isRtl,
                        StartHyphenEdit::NO_EDIT, EndHyphenEdit::NO_EDIT, boundsCalculation,
                        compositor);
            } else {
                precomputed->getOrCreate(textBuf, piece, context, mPaint, info.isRtl,
                                         StartHyphenEdit::NO_EDIT, EndHyphenEdit::NO_EDIT, paintId,
                                         boundsCalculation, compositor);
            }
        }
    }
}

// Helper class for composing total advances.
class TotalAdvancesCompositor {
public:
    TotalAdvancesCompositor() : mOut(0) {}

    void operator()(const LayoutPiece& layoutPiece, const MinikinPaint&, const MinikinRect&) {
        for (float w : layoutPiece.advances()) {
            mOut += w;
        }
    }

    float getTotalAdvance() { return mOut; }

private:
    float mOut;
};

float StyleRun::measureText(const U16StringPiece& textBuf) const {
    TotalAdvancesCompositor compositor;
    const Bidi bidiFlag = mIsRtl ? Bidi::FORCE_RTL : Bidi::FORCE_LTR;
    LayoutCache& layoutCache = LayoutCache::getInstance();
    for (const BidiText::RunInfo info : BidiText(textBuf, Range(0, textBuf.length()), bidiFlag)) {
        for (const auto [context, piece] : LayoutSplitter(textBuf, info.range, info.isRtl)) {
            layoutCache.getOrCreate(textBuf.substr(context), piece - context.getStart(), mPaint,
                                    info.isRtl, StartHyphenEdit::NO_EDIT, EndHyphenEdit::NO_EDIT,
                                    false /* bounds calculation */, compositor);
        }
    }
    return compositor.getTotalAdvance();
}

// Helper class for composing total amount of advance
class TotalAdvanceCompositor {
public:
    TotalAdvanceCompositor(LayoutPieces* outPieces) : mTotalAdvance(0), mOutPieces(outPieces) {}

    void setNextContext(const Range& range, HyphenEdit edit, bool dir) {
        mRange = range;
        mEdit = edit;
        mDir = dir;
    }

    void operator()(const LayoutPiece& layoutPiece, const MinikinPaint& paint,
                    const MinikinRect& bounds) {
        mTotalAdvance += layoutPiece.advance();
        if (mOutPieces != nullptr) {
            mOutPieces->insert(mRange, mEdit, layoutPiece, mDir, paint, bounds);
        }
    }

    float advance() const { return mTotalAdvance; }

private:
    float mTotalAdvance;
    Range mRange;
    HyphenEdit mEdit;
    bool mDir;
    LayoutPieces* mOutPieces;
};

float StyleRun::measureHyphenPiece(const U16StringPiece& textBuf, const Range& range,
                                   StartHyphenEdit startHyphen, EndHyphenEdit endHyphen,
                                   LayoutPieces* pieces) const {
    TotalAdvanceCompositor compositor(pieces);
    const Bidi bidiFlag = mIsRtl ? Bidi::FORCE_RTL : Bidi::FORCE_LTR;
    for (const BidiText::RunInfo info : BidiText(textBuf, range, bidiFlag)) {
        for (const auto[context, piece] : LayoutSplitter(textBuf, info.range, info.isRtl)) {
            const StartHyphenEdit startEdit =
                    piece.getStart() == range.getStart() ? startHyphen : StartHyphenEdit::NO_EDIT;
            const EndHyphenEdit endEdit =
                    piece.getEnd() == range.getEnd() ? endHyphen : EndHyphenEdit::NO_EDIT;

            compositor.setNextContext(piece, packHyphenEdit(startEdit, endEdit), info.isRtl);
            LayoutCache::getInstance().getOrCreate(
                    textBuf.substr(context), piece - context.getStart(), mPaint, info.isRtl,
                    startEdit, endEdit, false /* bounds calculation */, compositor);
        }
    }
    return compositor.advance();
}

void MeasuredText::measure(const U16StringPiece& textBuf, bool computeHyphenation,
                           bool computeLayout, bool computeBounds, bool ignoreHyphenKerning,
                           MeasuredText* hint) {
    if (textBuf.size() == 0) {
        return;
    }

    LayoutPieces* piecesOut = computeLayout ? &layoutPieces : nullptr;
    CharProcessor proc(textBuf);
    for (const auto& run : runs) {
        const Range& range = run->getRange();
        run->getMetrics(textBuf, &widths, &flags, hint ? &hint->layoutPieces : nullptr,
                        computeBounds, piecesOut);

        if (!computeHyphenation || !run->canBreak()) {
            continue;
        }

        proc.updateLocaleIfNecessary(*run, false /* forceWordStyleAutoToPhrase */);
        for (uint32_t i = range.getStart(); i < range.getEnd(); ++i) {
            // Even if the run is not a candidate of line break, treat the end of run as the line
            // break candidate.
            const bool canBreak = run->canBreak() || (i + 1) == range.getEnd();
            proc.feedChar(i, textBuf[i], widths[i], canBreak);

            const uint32_t nextCharOffset = i + 1;
            if (nextCharOffset != proc.nextWordBreak) {
                continue;  // Wait until word break point.
            }

            populateHyphenationPoints(textBuf, *run, *proc.hyphenator, proc.contextRange(),
                                      proc.wordRange(), widths, ignoreHyphenKerning, &hyphenBreaks,
                                      piecesOut);
        }
    }
}

// Helper class for composing Layout object.
class LayoutCompositor {
public:
    LayoutCompositor(Layout* outLayout, float extraAdvance)
            : mOutLayout(outLayout), mExtraAdvance(extraAdvance) {}

    void setOutOffset(uint32_t outOffset) { mOutOffset = outOffset; }

    void operator()(const LayoutPiece& layoutPiece, const MinikinPaint& /* paint */,
                    const MinikinRect&) {
        mOutLayout->appendLayout(layoutPiece, mOutOffset, mExtraAdvance);
    }

    uint32_t mOutOffset;
    Layout* mOutLayout;
    float mExtraAdvance;
};

void StyleRun::appendLayout(const U16StringPiece& textBuf, const Range& range,
                            const Range& /* context */, const LayoutPieces& pieces,
                            const MinikinPaint& paint, uint32_t outOrigin,
                            StartHyphenEdit startHyphen, EndHyphenEdit endHyphen,
                            Layout* outLayout) const {
    bool boundsCalculation = false;
    float wordSpacing = range.getLength() == 1 && isWordSpace(textBuf[range.getStart()])
                                ? mPaint.wordSpacing
                                : 0;
    bool canUsePrecomputedResult = mPaint == paint;

    LayoutCompositor compositor(outLayout, wordSpacing);
    const Bidi bidiFlag = mIsRtl ? Bidi::FORCE_RTL : Bidi::FORCE_LTR;
    const uint32_t paintId = pieces.findPaintId(mPaint);
    for (const BidiText::RunInfo info : BidiText(textBuf, range, bidiFlag)) {
        for (const auto[context, piece] : LayoutSplitter(textBuf, info.range, info.isRtl)) {
            compositor.setOutOffset(piece.getStart() - outOrigin);
            const StartHyphenEdit startEdit =
                    range.getStart() == piece.getStart() ? startHyphen : StartHyphenEdit::NO_EDIT;
            const EndHyphenEdit endEdit =
                    range.getEnd() == piece.getEnd() ? endHyphen : EndHyphenEdit::NO_EDIT;

            if (canUsePrecomputedResult) {
                pieces.getOrCreate(textBuf, piece, context, mPaint, info.isRtl, startEdit, endEdit,
                                   paintId, boundsCalculation, compositor);
            } else {
                LayoutCache::getInstance().getOrCreate(
                        textBuf.substr(context), piece - context.getStart(), paint, info.isRtl,
                        startEdit, endEdit, boundsCalculation, compositor);
            }
        }
    }
}

// Helper class for composing bounding box.
class BoundsCompositor {
public:
    BoundsCompositor() : mAdvance(0) {}

    void operator()(const LayoutPiece& layoutPiece, const MinikinPaint& /* paint */,
                    const MinikinRect& bounds) {
        mBounds.join(bounds, mAdvance, 0);
        mAdvance += layoutPiece.advance();
    }

    const MinikinRect& bounds() const { return mBounds; }
    float advance() const { return mAdvance; }

private:
    float mAdvance;
    MinikinRect mBounds;
};

std::pair<float, MinikinRect> StyleRun::getBounds(const U16StringPiece& textBuf, const Range& range,
                                                  const LayoutPieces& pieces) const {
    BoundsCompositor compositor;
    const Bidi bidiFlag = mIsRtl ? Bidi::FORCE_RTL : Bidi::FORCE_LTR;
    const uint32_t paintId = pieces.findPaintId(mPaint);
    for (const BidiText::RunInfo info : BidiText(textBuf, range, bidiFlag)) {
        for (const auto[context, piece] : LayoutSplitter(textBuf, info.range, info.isRtl)) {
            pieces.getOrCreate(textBuf, piece, context, mPaint, info.isRtl,
                               StartHyphenEdit::NO_EDIT, EndHyphenEdit::NO_EDIT, paintId,
                               true /* bounds calculation */, compositor);
        }
    }
    return std::make_pair(compositor.advance(), compositor.bounds());
}

// Helper class for composing total extent.
class ExtentCompositor {
public:
    ExtentCompositor() {}

    void operator()(const LayoutPiece& layoutPiece, const MinikinPaint& /* paint */,
                    const MinikinRect&) {
        mExtent.extendBy(layoutPiece.extent());
    }

    const MinikinExtent& extent() const { return mExtent; }

private:
    MinikinExtent mExtent;
};

MinikinExtent StyleRun::getExtent(const U16StringPiece& textBuf, const Range& range,
                                  const LayoutPieces& pieces) const {
    ExtentCompositor compositor;
    Bidi bidiFlag = mIsRtl ? Bidi::FORCE_RTL : Bidi::FORCE_LTR;
    const uint32_t paintId = pieces.findPaintId(mPaint);
    for (const BidiText::RunInfo info : BidiText(textBuf, range, bidiFlag)) {
        for (const auto[context, piece] : LayoutSplitter(textBuf, info.range, info.isRtl)) {
            pieces.getOrCreate(textBuf, piece, context, mPaint, info.isRtl,
                               StartHyphenEdit::NO_EDIT, EndHyphenEdit::NO_EDIT, paintId,
                               false /* bounds calculation */, compositor);
        }
    }
    return compositor.extent();
}

class LineMetricsCompositor {
public:
    LineMetricsCompositor() {}

    void operator()(const LayoutPiece& layoutPiece, const MinikinPaint& /* paint */,
                    const MinikinRect& bounds) {
        mMetrics.append(layoutPiece.extent(), bounds, layoutPiece.advance());
    }

    const LineMetrics& metrics() const { return mMetrics; }

private:
    LineMetrics mMetrics;
};

LineMetrics StyleRun::getLineMetrics(const U16StringPiece& textBuf, const Range& range,
                                     const LayoutPieces& pieces) const {
    LineMetricsCompositor compositor;
    Bidi bidiFlag = mIsRtl ? Bidi::FORCE_RTL : Bidi::FORCE_LTR;
    const uint32_t paintId = pieces.findPaintId(mPaint);
    for (const BidiText::RunInfo info : BidiText(textBuf, range, bidiFlag)) {
        for (const auto [context, piece] : LayoutSplitter(textBuf, info.range, info.isRtl)) {
            pieces.getOrCreate(textBuf, piece, context, mPaint, info.isRtl,
                               StartHyphenEdit::NO_EDIT, EndHyphenEdit::NO_EDIT, paintId,
                               true /* bounds calculation */, compositor);
        }
    }
    return compositor.metrics();
}

Layout MeasuredText::buildLayout(const U16StringPiece& textBuf, const Range& range,
                                 const Range& contextRange, const MinikinPaint& paint,
                                 StartHyphenEdit startHyphen, EndHyphenEdit endHyphen) {
    Layout outLayout(range.getLength());
    for (const auto& run : runs) {
        const Range& runRange = run->getRange();
        if (!Range::intersects(range, runRange)) {
            continue;
        }
        const Range targetRange = Range::intersection(runRange, range);
        StartHyphenEdit startEdit =
                targetRange.getStart() == range.getStart() ? startHyphen : StartHyphenEdit::NO_EDIT;
        EndHyphenEdit endEdit =
                targetRange.getEnd() == range.getEnd() ? endHyphen : EndHyphenEdit::NO_EDIT;
        run->appendLayout(textBuf, targetRange, contextRange, layoutPieces, paint, range.getStart(),
                          startEdit, endEdit, &outLayout);
    }
    return outLayout;
}

MinikinRect MeasuredText::getBounds(const U16StringPiece& textBuf, const Range& range) const {
    MinikinRect rect;
    float totalAdvance = 0.0f;

    for (const auto& run : runs) {
        const Range& runRange = run->getRange();
        if (!Range::intersects(range, runRange)) {
            continue;
        }
        auto[advance, bounds] =
                run->getBounds(textBuf, Range::intersection(runRange, range), layoutPieces);
        rect.join(bounds, totalAdvance, 0);
        totalAdvance += advance;
    }
    return rect;
}

MinikinExtent MeasuredText::getExtent(const U16StringPiece& textBuf, const Range& range) const {
    MinikinExtent extent;
    for (const auto& run : runs) {
        const Range& runRange = run->getRange();
        if (!Range::intersects(range, runRange)) {
            continue;
        }
        extent.extendBy(
                run->getExtent(textBuf, Range::intersection(runRange, range), layoutPieces));
    }
    return extent;
}

LineMetrics MeasuredText::getLineMetrics(const U16StringPiece& textBuf, const Range& range) const {
    LineMetrics metrics;
    for (const auto& run : runs) {
        const Range& runRange = run->getRange();
        if (!Range::intersects(range, runRange)) {
            continue;
        }
        metrics.append(
                run->getLineMetrics(textBuf, Range::intersection(runRange, range), layoutPieces));
    }
    return metrics;
}

}  // namespace minikin