LayoutUtils.cpp revision 14e2d136aaef271ba131f917cf5f27baa31ae5ad
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#define LOG_TAG "Minikin"
18
19#include "LayoutUtils.h"
20
21namespace minikin {
22
23/**
24 * For the purpose of layout, a word break is a boundary with no
25 * kerning or complex script processing. This is necessarily a
26 * heuristic, but should be accurate most of the time.
27 */
28static bool isWordBreakAfter(int c) {
29    if (c == ' ' || (c >= 0x2000 && c <= 0x200a) || c == 0x3000) {
30        // spaces
31        return true;
32    }
33    // Note: kana is not included, as sophisticated fonts may kern kana
34    return false;
35}
36
37static bool isWordBreakBefore(int c) {
38    // CJK ideographs (and yijing hexagram symbols)
39    return isWordBreakAfter(c) || (c >= 0x3400 && c <= 0x9fff);
40}
41
42/**
43 * Return offset of previous word break. It is either < offset or == 0.
44 */
45size_t getPrevWordBreakForCache(
46        const uint16_t* chars, size_t offset, size_t len) {
47    if (offset == 0) return 0;
48    if (offset > len) offset = len;
49    if (isWordBreakBefore(chars[offset - 1])) {
50        return offset - 1;
51    }
52    for (size_t i = offset - 1; i > 0; i--) {
53        if (isWordBreakBefore(chars[i]) || isWordBreakAfter(chars[i - 1])) {
54            return i;
55        }
56    }
57    return 0;
58}
59
60/**
61 * Return offset of next word break. It is either > offset or == len.
62 */
63size_t getNextWordBreakForCache(
64        const uint16_t* chars, size_t offset, size_t len) {
65    if (offset >= len) return len;
66    if (isWordBreakAfter(chars[offset])) {
67        return offset + 1;
68    }
69    for (size_t i = offset + 1; i < len; i++) {
70        // No need to check isWordBreakAfter(chars[i - 1]) since it is checked
71        // in previous iteration.  Note that isWordBreakBefore returns true
72        // whenever isWordBreakAfter returns true.
73        if (isWordBreakBefore(chars[i])) {
74            return i;
75        }
76    }
77    return len;
78}
79
80}  // namespace minikin
81