• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "OptimalLineBreaker.h"
18 
19 #include <algorithm>
20 #include <limits>
21 
22 #include "FeatureFlags.h"
23 #include "HyphenatorMap.h"
24 #include "LayoutUtils.h"
25 #include "LineBreakerUtil.h"
26 #include "Locale.h"
27 #include "LocaleListCache.h"
28 #include "MinikinInternal.h"
29 #include "WordBreaker.h"
30 #include "minikin/Characters.h"
31 #include "minikin/Layout.h"
32 #include "minikin/Range.h"
33 #include "minikin/U16StringPiece.h"
34 
35 namespace minikin {
36 
37 namespace {
38 
39 // Large scores in a hierarchy; we prefer desperate breaks to an overfull line. All these
40 // constants are larger than any reasonable actual width score.
41 constexpr float SCORE_INFTY = std::numeric_limits<float>::max();
42 constexpr float SCORE_OVERFULL = 1e12f;
43 constexpr float SCORE_DESPERATE = 1e10f;
44 constexpr float SCORE_FALLBACK = 1e6f;
45 
46 // Multiplier for hyphen penalty on last line.
47 constexpr float LAST_LINE_PENALTY_MULTIPLIER = 4.0f;
48 // Penalty assigned to each line break (to try to minimize number of lines)
49 // TODO: when we implement full justification (so spaces can shrink and stretch), this is
50 // probably not the most appropriate method.
51 constexpr float LINE_PENALTY_MULTIPLIER = 2.0f;
52 
53 // Penalty assigned to shrinking the whitepsace.
54 constexpr float SHRINK_PENALTY_MULTIPLIER = 4.0f;
55 
56 // Maximum amount that spaces can shrink, in justified text.
57 constexpr float SHRINKABILITY = 1.0 / 3.0;
58 
59 // A single candidate break
60 struct Candidate {
61     uint32_t offset;  // offset to text buffer, in code units
62 
63     ParaWidth preBreak;       // width of text until this point, if we decide to not break here:
64                               // preBreak is used as an optimized way to calculate the width
65                               // between two candidates. The line width between two line break
66                               // candidates i and j is calculated as postBreak(j) - preBreak(i).
67     ParaWidth postBreak;      // width of text until this point, if we decide to break here
68     float penalty;            // penalty of this break (for example, hyphen penalty)
69     uint32_t preSpaceCount;   // preceding space count before breaking
70     uint32_t postSpaceCount;  // preceding space count after breaking
71     HyphenationType hyphenType;
72     bool isRtl;  // The direction of the bidi run containing or ending in this candidate
73 
Candidateminikin::__anonfe8f38e50111::Candidate74     Candidate(uint32_t offset, ParaWidth preBreak, ParaWidth postBreak, float penalty,
75               uint32_t preSpaceCount, uint32_t postSpaceCount, HyphenationType hyphenType,
76               bool isRtl)
77             : offset(offset),
78               preBreak(preBreak),
79               postBreak(postBreak),
80               penalty(penalty),
81               preSpaceCount(preSpaceCount),
82               postSpaceCount(postSpaceCount),
83               hyphenType(hyphenType),
84               isRtl(isRtl) {}
85 };
86 
87 // A context of line break optimization.
88 struct OptimizeContext {
89     // The break candidates.
90     std::vector<Candidate> candidates;
91 
92     // The penalty for the number of lines.
93     float linePenalty = 0.0f;
94 
95     // The width of a space. May be 0 if there are no spaces.
96     // Note: if there are multiple different widths for spaces (for example, because of mixing of
97     // fonts), it's only guaranteed to pick one.
98     float spaceWidth = 0.0f;
99 
100     bool retryWithPhraseWordBreak = false;
101 
102     float maxCharWidth = 0.0f;
103 
104     // Append desperate break point to the candidates.
pushDesperateminikin::__anonfe8f38e50111::OptimizeContext105     inline void pushDesperate(uint32_t offset, ParaWidth sumOfCharWidths, float score,
106                               uint32_t spaceCount, bool isRtl, float letterSpacing) {
107         pushBreakCandidate(offset, sumOfCharWidths, sumOfCharWidths, score, spaceCount, spaceCount,
108                            HyphenationType::BREAK_AND_DONT_INSERT_HYPHEN, isRtl, letterSpacing);
109     }
110 
111     // Append hyphenation break point to the candidates.
pushHyphenationminikin::__anonfe8f38e50111::OptimizeContext112     inline void pushHyphenation(uint32_t offset, ParaWidth preBreak, ParaWidth postBreak,
113                                 float penalty, uint32_t spaceCount, HyphenationType type,
114                                 bool isRtl, float letterSpacing) {
115         pushBreakCandidate(offset, preBreak, postBreak, penalty, spaceCount, spaceCount, type,
116                            isRtl, letterSpacing);
117     }
118 
119     // Append word break point to the candidates.
pushWordBreakminikin::__anonfe8f38e50111::OptimizeContext120     inline void pushWordBreak(uint32_t offset, ParaWidth preBreak, ParaWidth postBreak,
121                               float penalty, uint32_t preSpaceCount, uint32_t postSpaceCount,
122                               bool isRtl, float letterSpacing) {
123         pushBreakCandidate(offset, preBreak, postBreak, penalty, preSpaceCount, postSpaceCount,
124                            HyphenationType::DONT_BREAK, isRtl, letterSpacing);
125     }
126 
OptimizeContextminikin::__anonfe8f38e50111::OptimizeContext127     OptimizeContext(float firstLetterSpacing) {
128         pushWordBreak(0, 0, 0, 0, 0, 0, false, firstLetterSpacing);
129     }
130 
131 private:
pushBreakCandidateminikin::__anonfe8f38e50111::OptimizeContext132     void pushBreakCandidate(uint32_t offset, ParaWidth preBreak, ParaWidth postBreak, float penalty,
133                             uint32_t preSpaceCount, uint32_t postSpaceCount, HyphenationType type,
134                             bool isRtl, float letterSpacing) {
135         // Adjust the letter spacing amount. To remove the letter spacing of left and right edge,
136         // adjust the preBreak and postBreak values. Adding half to preBreak and removing half from
137         // postBreak, the letter space amount is subtracted from the line.
138         //
139         // This calculation assumes the letter spacing of starting edge is the same to the line
140         // start offset and letter spacing of ending edge is the same to the line end offset.
141         // Ideally, we should do the BiDi reordering for identifying the run of the left edge and
142         // right edge but it makes the candidate population to O(n^2). To avoid performance
143         // regression, use the letter spacing of the line start offset and letter spacing of the
144         // line end offset.
145         const float letterSpacingHalf = letterSpacing * 0.5;
146         candidates.emplace_back(offset, preBreak + letterSpacingHalf, postBreak - letterSpacingHalf,
147                                 penalty, preSpaceCount, postSpaceCount, type, isRtl);
148     }
149 };
150 
151 // Compute the penalty for the run and returns penalty for hyphenation and number of lines.
computePenalties(const Run & run,const LineWidth & lineWidth,HyphenationFrequency frequency,bool justified)152 std::pair<float, float> computePenalties(const Run& run, const LineWidth& lineWidth,
153                                          HyphenationFrequency frequency, bool justified) {
154     float linePenalty = 0.0;
155     const MinikinPaint* paint = run.getPaint();
156     // a heuristic that seems to perform well
157     float hyphenPenalty = 0.5 * paint->size * paint->scaleX * lineWidth.getAt(0);
158     if (frequency == HyphenationFrequency::Normal) {
159         hyphenPenalty *= 4.0;  // TODO: Replace with a better value after some testing
160     }
161 
162     if (justified) {
163         // Make hyphenation more aggressive for fully justified text (so that "normal" in
164         // justified mode is the same as "full" in ragged-right).
165         hyphenPenalty *= 0.25;
166     } else {
167         // Line penalty is zero for justified text.
168         linePenalty = hyphenPenalty * LINE_PENALTY_MULTIPLIER;
169     }
170 
171     return std::make_pair(hyphenPenalty, linePenalty);
172 }
173 
174 // Represents a desperate break point.
175 struct DesperateBreak {
176     // The break offset.
177     uint32_t offset;
178 
179     // The sum of the character width from the beginning of the word.
180     ParaWidth sumOfChars;
181 
182     float score;
183 
DesperateBreakminikin::__anonfe8f38e50111::DesperateBreak184     DesperateBreak(uint32_t offset, ParaWidth sumOfChars, float score)
185             : offset(offset), sumOfChars(sumOfChars), score(score){};
186 };
187 
188 // Retrieves desperate break points from a word.
populateDesperatePoints(const U16StringPiece & textBuf,const MeasuredText & measured,const Range & range,const Run & run)189 std::vector<DesperateBreak> populateDesperatePoints(const U16StringPiece& textBuf,
190                                                     const MeasuredText& measured,
191                                                     const Range& range, const Run& run) {
192     std::vector<DesperateBreak> out;
193 
194     WordBreaker wb;
195     wb.setText(textBuf.data(), textBuf.length());
196     ssize_t next =
197             wb.followingWithLocale(getEffectiveLocale(run.getLocaleListId()), run.lineBreakStyle(),
198                                    LineBreakWordStyle::None, range.getStart());
199 
200     const bool calculateFallback = range.contains(next);
201     ParaWidth width = measured.widths[range.getStart()];
202     for (uint32_t i = range.getStart() + 1; i < range.getEnd(); ++i) {
203         const float w = measured.widths[i];
204         if (w == 0) {
205             continue;  // w == 0 means here is not a grapheme bounds. Don't break here.
206         }
207         if (calculateFallback && i == (uint32_t)next) {
208             out.emplace_back(i, width, SCORE_FALLBACK);
209             next = wb.next();
210         } else {
211             out.emplace_back(i, width, SCORE_DESPERATE);
212         }
213         width += w;
214     }
215 
216     return out;
217 }
218 
219 // Append hyphenation break points and desperate break points.
220 // If an offset is a both candidate for hyphenation and desperate break points, place desperate
221 // break candidate first and hyphenation break points second since the result width of the desperate
222 // break is shorter than hyphenation break.
223 // This is important since DP in computeBreaksOptimal assumes that the result line width is
224 // increased by break offset.
appendWithMerging(std::vector<HyphenBreak>::const_iterator hyIter,std::vector<HyphenBreak>::const_iterator endHyIter,const std::vector<DesperateBreak> & desperates,const CharProcessor & proc,float hyphenPenalty,bool isRtl,float letterSpacing,OptimizeContext * out)225 void appendWithMerging(std::vector<HyphenBreak>::const_iterator hyIter,
226                        std::vector<HyphenBreak>::const_iterator endHyIter,
227                        const std::vector<DesperateBreak>& desperates, const CharProcessor& proc,
228                        float hyphenPenalty, bool isRtl, float letterSpacing, OptimizeContext* out) {
229     auto d = desperates.begin();
230     while (hyIter != endHyIter || d != desperates.end()) {
231         // If both hyphen breaks and desperate breaks point to the same offset, push desperate
232         // breaks first.
233         if (d != desperates.end() && (hyIter == endHyIter || d->offset <= hyIter->offset)) {
234             out->pushDesperate(d->offset, proc.sumOfCharWidthsAtPrevWordBreak + d->sumOfChars,
235                                d->score, proc.effectiveSpaceCount, isRtl, letterSpacing);
236             d++;
237         } else {
238             out->pushHyphenation(hyIter->offset, proc.sumOfCharWidths - hyIter->second,
239                                  proc.sumOfCharWidthsAtPrevWordBreak + hyIter->first, hyphenPenalty,
240                                  proc.effectiveSpaceCount, hyIter->type, isRtl, letterSpacing);
241             hyIter++;
242         }
243     }
244 }
245 
246 // Enumerate all line break candidates.
populateCandidates(const U16StringPiece & textBuf,const MeasuredText & measured,const LineWidth & lineWidth,HyphenationFrequency frequency,bool isJustified,bool forceWordStyleAutoToPhrase)247 OptimizeContext populateCandidates(const U16StringPiece& textBuf, const MeasuredText& measured,
248                                    const LineWidth& lineWidth, HyphenationFrequency frequency,
249                                    bool isJustified, bool forceWordStyleAutoToPhrase) {
250     const ParaWidth minLineWidth = lineWidth.getMin();
251     CharProcessor proc(textBuf);
252 
253     float initialLetterSpacing;
254     if (measured.runs.empty()) {
255         initialLetterSpacing = 0;
256     } else {
257         initialLetterSpacing = measured.runs[0]->getLetterSpacingInPx();
258     }
259     OptimizeContext result(initialLetterSpacing);
260 
261     const bool doHyphenation = frequency != HyphenationFrequency::None;
262     auto hyIter = std::begin(measured.hyphenBreaks);
263 
264     for (const auto& run : measured.runs) {
265         const bool isRtl = run->isRtl();
266         const Range& range = run->getRange();
267         const float letterSpacing = run->getLetterSpacingInPx();
268 
269         // Compute penalty parameters.
270         float hyphenPenalty = 0.0f;
271         if (run->canBreak()) {
272             auto penalties = computePenalties(*run, lineWidth, frequency, isJustified);
273             hyphenPenalty = penalties.first;
274             result.linePenalty = std::max(penalties.second, result.linePenalty);
275         }
276 
277         proc.updateLocaleIfNecessary(*run, forceWordStyleAutoToPhrase);
278 
279         for (uint32_t i = range.getStart(); i < range.getEnd(); ++i) {
280             MINIKIN_ASSERT(textBuf[i] != CHAR_TAB, "TAB is not supported in optimal line breaker");
281             // Even if the run is not a candidate of line break, treat the end of run as the line
282             // break candidate.
283             const bool canBreak = run->canBreak() || (i + 1) == range.getEnd();
284             proc.feedChar(i, textBuf[i], measured.widths[i], canBreak);
285 
286             const uint32_t nextCharOffset = i + 1;
287             if (nextCharOffset != proc.nextWordBreak) {
288                 continue;  // Wait until word break point.
289             }
290 
291             // Add hyphenation and desperate break points.
292             std::vector<HyphenBreak> hyphenedBreaks;
293             std::vector<DesperateBreak> desperateBreaks;
294             const Range contextRange = proc.contextRange();
295 
296             auto beginHyIter = hyIter;
297             while (hyIter != std::end(measured.hyphenBreaks) &&
298                    hyIter->offset < contextRange.getEnd()) {
299                 hyIter++;
300             }
301             if (proc.widthFromLastWordBreak() > minLineWidth) {
302                 desperateBreaks = populateDesperatePoints(textBuf, measured, contextRange, *run);
303             }
304             const bool doHyphenationRun = doHyphenation && run->canHyphenate();
305 
306             appendWithMerging(beginHyIter, doHyphenationRun ? hyIter : beginHyIter, desperateBreaks,
307                               proc, hyphenPenalty, isRtl, letterSpacing, &result);
308 
309             // We skip breaks for zero-width characters inside replacement spans.
310             if (run->getPaint() != nullptr || nextCharOffset == range.getEnd() ||
311                 measured.widths[nextCharOffset] > 0) {
312                 const float penalty = hyphenPenalty * proc.wordBreakPenalty();
313                 result.pushWordBreak(nextCharOffset, proc.sumOfCharWidths, proc.effectiveWidth,
314                                      penalty, proc.rawSpaceCount, proc.effectiveSpaceCount, isRtl,
315                                      letterSpacing);
316             }
317         }
318     }
319     result.spaceWidth = proc.spaceWidth;
320     result.retryWithPhraseWordBreak = proc.retryWithPhraseWordBreak;
321     result.maxCharWidth = proc.maxCharWidth;
322     return result;
323 }
324 
325 class LineBreakOptimizer {
326 public:
LineBreakOptimizer()327     LineBreakOptimizer() {}
328 
329     LineBreakResult computeBreaks(const OptimizeContext& context, const U16StringPiece& textBuf,
330                                   const MeasuredText& measuredText, const LineWidth& lineWidth,
331                                   BreakStrategy strategy, bool justified, bool useBoundsForWidth);
332 
333 private:
334     // Data used to compute optimal line breaks
335     struct OptimalBreaksData {
336         float score;          // best score found for this break
337         uint32_t prev;        // index to previous break
338         uint32_t lineNumber;  // the computed line number of the candidate
339     };
340     LineBreakResult finishBreaksOptimal(const U16StringPiece& textBuf, const MeasuredText& measured,
341                                         const std::vector<OptimalBreaksData>& breaksData,
342                                         const std::vector<Candidate>& candidates,
343                                         bool useBoundsForWidth);
344 };
345 
346 // Follow "prev" links in candidates array, and copy to result arrays.
finishBreaksOptimal(const U16StringPiece & textBuf,const MeasuredText & measured,const std::vector<OptimalBreaksData> & breaksData,const std::vector<Candidate> & candidates,bool useBoundsForWidth)347 LineBreakResult LineBreakOptimizer::finishBreaksOptimal(
348         const U16StringPiece& textBuf, const MeasuredText& measured,
349         const std::vector<OptimalBreaksData>& breaksData, const std::vector<Candidate>& candidates,
350         bool useBoundsForWidth) {
351     LineBreakResult result;
352     const uint32_t nCand = candidates.size();
353     uint32_t prevIndex;
354     for (uint32_t i = nCand - 1; i > 0; i = prevIndex) {
355         prevIndex = breaksData[i].prev;
356         const Candidate& cand = candidates[i];
357         const Candidate& prev = candidates[prevIndex];
358 
359         result.breakPoints.push_back(cand.offset);
360         result.widths.push_back(cand.postBreak - prev.preBreak);
361         if (useBoundsForWidth) {
362             Range range = Range(prev.offset, cand.offset);
363             Range actualRange = trimTrailingLineEndSpaces(textBuf, range);
364             if (actualRange.isEmpty()) {
365                 MinikinExtent extent = measured.getExtent(textBuf, range);
366                 result.ascents.push_back(extent.ascent);
367                 result.descents.push_back(extent.descent);
368                 result.bounds.emplace_back(0, extent.ascent, cand.postBreak - prev.preBreak,
369                                            extent.descent);
370             } else {
371                 LineMetrics metrics = measured.getLineMetrics(textBuf, actualRange);
372                 result.ascents.push_back(metrics.extent.ascent);
373                 result.descents.push_back(metrics.extent.descent);
374                 result.bounds.emplace_back(metrics.bounds);
375             }
376         } else {
377             MinikinExtent extent = measured.getExtent(textBuf, Range(prev.offset, cand.offset));
378             result.ascents.push_back(extent.ascent);
379             result.descents.push_back(extent.descent);
380             result.bounds.emplace_back(0, extent.ascent, cand.postBreak - prev.preBreak,
381                                        extent.descent);
382         }
383 
384         const HyphenEdit edit =
385                 packHyphenEdit(editForNextLine(prev.hyphenType), editForThisLine(cand.hyphenType));
386         result.flags.push_back(static_cast<int>(edit));
387     }
388     result.reverse();
389     return result;
390 }
391 
computeBreaks(const OptimizeContext & context,const U16StringPiece & textBuf,const MeasuredText & measured,const LineWidth & lineWidth,BreakStrategy strategy,bool justified,bool useBoundsForWidth)392 LineBreakResult LineBreakOptimizer::computeBreaks(const OptimizeContext& context,
393                                                   const U16StringPiece& textBuf,
394                                                   const MeasuredText& measured,
395                                                   const LineWidth& lineWidth,
396                                                   BreakStrategy strategy, bool justified,
397                                                   bool useBoundsForWidth) {
398     const std::vector<Candidate>& candidates = context.candidates;
399     uint32_t active = 0;
400     const uint32_t nCand = candidates.size();
401     const float maxShrink = justified ? SHRINKABILITY * context.spaceWidth : 0.0f;
402 
403     std::vector<OptimalBreaksData> breaksData;
404     breaksData.reserve(nCand);
405     breaksData.push_back({0.0, 0, 0});  // The first candidate is always at the first line.
406 
407     const float deltaMax = context.maxCharWidth * 2;
408     // "i" iterates through candidates for the end of the line.
409     for (uint32_t i = 1; i < nCand; i++) {
410         const bool atEnd = i == nCand - 1;
411         float best = SCORE_INFTY;
412         uint32_t bestPrev = 0;
413 
414         uint32_t lineNumberLast = breaksData[active].lineNumber;
415         float width = lineWidth.getAt(lineNumberLast);
416 
417         ParaWidth leftEdge = candidates[i].postBreak - width;
418         float bestHope = 0;
419 
420         // "j" iterates through candidates for the beginning of the line.
421         for (uint32_t j = active; j < i; j++) {
422             const uint32_t lineNumber = breaksData[j].lineNumber;
423             if (lineNumber != lineNumberLast) {
424                 const float widthNew = lineWidth.getAt(lineNumber);
425                 if (widthNew != width) {
426                     leftEdge = candidates[i].postBreak - width;
427                     bestHope = 0;
428                     width = widthNew;
429                 }
430                 lineNumberLast = lineNumber;
431             }
432             const float jScore = breaksData[j].score;
433             if (jScore + bestHope >= best) continue;
434             float delta = candidates[j].preBreak - leftEdge;
435 
436             // The bounds calculation is for preventing horizontal clipping.
437             // So, if the delta is negative, i.e. overshoot is happening with advance width, we can
438             // skip the bounds calculation. Also we skip the bounds calculation if the delta is
439             // larger than twice of max character widdth. This is a heuristic that the twice of max
440             // character width should be good enough space for keeping overshoot.
441             if (useBoundsForWidth && 0 <= delta && delta < deltaMax) {
442                 // FIXME: Support bounds based line break for hyphenated break point.
443                 if (candidates[i].hyphenType == HyphenationType::DONT_BREAK &&
444                     candidates[j].hyphenType == HyphenationType::DONT_BREAK) {
445                     Range range = Range(candidates[j].offset, candidates[i].offset);
446                     Range actualRange = trimTrailingLineEndSpaces(textBuf, range);
447                     if (!actualRange.isEmpty() && measured.hasOverhang(range)) {
448                         float boundsDelta =
449                                 width - measured.getBounds(textBuf, actualRange).width();
450                         if (boundsDelta < 0) {
451                             delta = boundsDelta;
452                         }
453                     }
454                 }
455             }
456 
457             // compute width score for line
458 
459             // Note: the "bestHope" optimization makes the assumption that, when delta is
460             // non-negative, widthScore will increase monotonically as successive candidate
461             // breaks are considered.
462             float widthScore = 0.0f;
463             float additionalPenalty = 0.0f;
464             if ((atEnd || !justified) && delta < 0) {
465                 widthScore = SCORE_OVERFULL;
466             } else if (atEnd && strategy != BreakStrategy::Balanced) {
467                 // increase penalty for hyphen on last line
468                 additionalPenalty = LAST_LINE_PENALTY_MULTIPLIER * candidates[j].penalty;
469             } else {
470                 widthScore = delta * delta;
471                 if (delta < 0) {
472                     if (-delta <
473                         maxShrink * (candidates[i].postSpaceCount - candidates[j].preSpaceCount)) {
474                         widthScore *= SHRINK_PENALTY_MULTIPLIER;
475                     } else {
476                         widthScore = SCORE_OVERFULL;
477                     }
478                 }
479             }
480 
481             if (delta < 0) {
482                 active = j + 1;
483             } else {
484                 bestHope = widthScore;
485             }
486 
487             const float score = jScore + widthScore + additionalPenalty;
488             if (score <= best) {
489                 best = score;
490                 bestPrev = j;
491             }
492         }
493         breaksData.push_back({best + candidates[i].penalty + context.linePenalty,  // score
494                               bestPrev,                                            // prev
495                               breaksData[bestPrev].lineNumber + 1});               // lineNumber
496     }
497     return finishBreaksOptimal(textBuf, measured, breaksData, candidates, useBoundsForWidth);
498 }
499 
500 }  // namespace
501 
breakLineOptimal(const U16StringPiece & textBuf,const MeasuredText & measured,const LineWidth & lineWidth,BreakStrategy strategy,HyphenationFrequency frequency,bool justified,bool useBoundsForWidth)502 LineBreakResult breakLineOptimal(const U16StringPiece& textBuf, const MeasuredText& measured,
503                                  const LineWidth& lineWidth, BreakStrategy strategy,
504                                  HyphenationFrequency frequency, bool justified,
505                                  bool useBoundsForWidth) {
506     if (textBuf.size() == 0) {
507         return LineBreakResult();
508     }
509 
510     const OptimizeContext context =
511             populateCandidates(textBuf, measured, lineWidth, frequency, justified,
512                                false /* forceWordStyleAutoToPhrase */);
513     LineBreakOptimizer optimizer;
514     LineBreakResult res = optimizer.computeBreaks(context, textBuf, measured, lineWidth, strategy,
515                                                   justified, useBoundsForWidth);
516 
517     // The line breaker says that retry with phrase based word break because of the auto option and
518     // given locales.
519     if (!context.retryWithPhraseWordBreak) {
520         return res;
521     }
522 
523     // If the line break result is more than heuristics threshold, don't try pharse based word
524     // break.
525     if (res.breakPoints.size() >= LBW_AUTO_HEURISTICS_LINE_COUNT) {
526         return res;
527     }
528 
529     const OptimizeContext phContext =
530             populateCandidates(textBuf, measured, lineWidth, frequency, justified,
531                                true /* forceWordStyleAutoToPhrase */);
532     LineBreakResult res2 = optimizer.computeBreaks(phContext, textBuf, measured, lineWidth,
533                                                    strategy, justified, useBoundsForWidth);
534     if (res2.breakPoints.size() < LBW_AUTO_HEURISTICS_LINE_COUNT) {
535         return res2;
536     } else {
537         return res;
538     }
539 }
540 
541 }  // namespace minikin
542