diff --git a/engine/src/flutter/app/HyphTool.cpp b/engine/src/flutter/app/HyphTool.cpp index 88245fea33..cdb1466f40 100644 --- a/engine/src/flutter/app/HyphTool.cpp +++ b/engine/src/flutter/app/HyphTool.cpp @@ -2,11 +2,13 @@ #include #include +#include "unicode/locid.h" #include "utils/Log.h" #include #include +using minikin::HyphenationType; using minikin::Hyphenator; Hyphenator* loadHybFile(const char* fn) { @@ -35,7 +37,7 @@ Hyphenator* loadHybFile(const char* fn) { int main(int argc, char** argv) { Hyphenator* hyph = loadHybFile("/tmp/en.hyb"); // should also be configurable - std::vector result; + std::vector result; std::vector word; if (argc < 2) { fprintf(stderr, "usage: hyphtool word\n"); @@ -51,9 +53,9 @@ int main(int argc, char** argv) { // ASCII (or possibly ISO Latin 1), but kinda painful to do utf conversion :( word.push_back(c); } - hyph->hyphenate(&result, word.data(), word.size()); + hyph->hyphenate(&result, word.data(), word.size(), icu::Locale::getUS()); for (size_t i = 0; i < len; i++) { - if (result[i] != 0) { + if (result[i] != HyphenationType::DONT_BREAK) { printf("-"); } printf("%c", word[i]); diff --git a/engine/src/flutter/include/minikin/Hyphenator.h b/engine/src/flutter/include/minikin/Hyphenator.h index f922dcbfb7..ea81813745 100644 --- a/engine/src/flutter/include/minikin/Hyphenator.h +++ b/engine/src/flutter/include/minikin/Hyphenator.h @@ -18,6 +18,7 @@ * An implementation of Liang's hyphenation algorithm. */ +#include "unicode/locid.h" #include #include @@ -26,38 +27,131 @@ namespace minikin { +enum class HyphenationType : uint8_t { + // Note: There are implicit assumptions scattered in the code that DONT_BREAK is 0. + + // Do not break. + DONT_BREAK = 0, + // Break the line and insert a normal hyphen. + BREAK_AND_INSERT_HYPHEN = 1, + // Break the line and insert an Armenian hyphen (U+058A). + BREAK_AND_INSERT_ARMENIAN_HYPHEN = 2, + // Break the line and insert a maqaf (Hebrew hyphen, U+05BE). + BREAK_AND_INSERT_MAQAF = 3, + // Break the line and insert a Canadian Syllabics hyphen (U+1400). + BREAK_AND_INSERT_UCAS_HYPHEN = 4, + // Break the line, but don't insert a hyphen. Used for cases when there is already a hyphen + // present or the script does not use a hyphen (e.g. in Malayalam). + BREAK_AND_DONT_INSERT_HYPHEN = 5, + // Break and replace the last code unit with hyphen. Used for Catalan "l·l" which hyphenates + // as "l-/l". + BREAK_AND_REPLACE_WITH_HYPHEN = 6, + // Break the line, and repeat the hyphen (which is the last character) at the beginning of the + // next line. Used in Polish, where "czerwono-niebieska" should hyphenate as + // "czerwono-/-niebieska". + BREAK_AND_INSERT_HYPHEN_AT_NEXT_LINE = 7, + // Break the line, insert a ZWJ and hyphen at the first line, and a ZWJ at the second line. + // This is used in Arabic script, mostly for writing systems of Central Asia. It's our default + // behavior when a soft hyphen is used in Arabic script. + BREAK_AND_INSERT_HYPHEN_AND_ZWJ = 8 +}; + +// The hyphen edit represents an edit to the string when a word is +// hyphenated. The most common hyphen edit is adding a "-" at the end +// of a syllable, but nonstandard hyphenation allows for more choices. +// Note that a HyphenEdit can hold two types of edits at the same time, +// One at the beginning of the string/line and one at the end. +class HyphenEdit { +public: + static const uint32_t NO_EDIT = 0x00; + + static const uint32_t INSERT_HYPHEN_AT_END = 0x01; + static const uint32_t INSERT_ARMENIAN_HYPHEN_AT_END = 0x02; + static const uint32_t INSERT_MAQAF_AT_END = 0x03; + static const uint32_t INSERT_UCAS_HYPHEN_AT_END = 0x04; + static const uint32_t INSERT_ZWJ_AND_HYPHEN_AT_END = 0x05; + static const uint32_t REPLACE_WITH_HYPHEN_AT_END = 0x06; + static const uint32_t BREAK_AT_END = 0x07; + + static const uint32_t INSERT_HYPHEN_AT_START = 0x01 << 3; + static const uint32_t INSERT_ZWJ_AT_START = 0x02 << 3; + static const uint32_t BREAK_AT_START = 0x03 << 3; + + // Keep in sync with the definitions in the Java code at: + // frameworks/base/graphics/java/android/graphics/Paint.java + static const uint32_t MASK_END_OF_LINE = 0x07; + static const uint32_t MASK_START_OF_LINE = 0x03 << 3; + + inline static bool isReplacement(uint32_t hyph) { + return hyph == REPLACE_WITH_HYPHEN_AT_END; + } + + inline static bool isInsertion(uint32_t hyph) { + return (hyph == INSERT_HYPHEN_AT_END + || hyph == INSERT_ARMENIAN_HYPHEN_AT_END + || hyph == INSERT_MAQAF_AT_END + || hyph == INSERT_UCAS_HYPHEN_AT_END + || hyph == INSERT_ZWJ_AND_HYPHEN_AT_END + || hyph == INSERT_HYPHEN_AT_START + || hyph == INSERT_ZWJ_AT_START); + } + + const static uint32_t* getHyphenString(uint32_t hyph); + static uint32_t editForThisLine(HyphenationType type); + static uint32_t editForNextLine(HyphenationType type); + + HyphenEdit() : hyphen(NO_EDIT) { } + HyphenEdit(uint32_t hyphenInt) : hyphen(hyphenInt) { } // NOLINT(implicit) + uint32_t getHyphen() const { return hyphen; } + bool operator==(const HyphenEdit &other) const { return hyphen == other.hyphen; } + + uint32_t getEnd() const { return hyphen & MASK_END_OF_LINE; } + uint32_t getStart() const { return hyphen & MASK_START_OF_LINE; } + +private: + uint32_t hyphen; +}; + // hyb file header; implementation details are in the .cpp file struct Header; class Hyphenator { public: - // Note: this will also require a locale, for proper case folding behavior - static Hyphenator* load(const uint16_t* patternData, size_t size); + // Compute the hyphenation of a word, storing the hyphenation in result vector. Each entry in + // the vector is a "hyphenation type" for a potential hyphenation that can be applied at the + // corresponding code unit offset in the word. + // + // Example: word is "hyphen", result is the following, corresponding to "hy-phen": + // [DONT_BREAK, DONT_BREAK, BREAK_AND_INSERT_HYPHEN, DONT_BREAK, DONT_BREAK, DONT_BREAK] + void hyphenate(std::vector* result, const uint16_t* word, size_t len, + const icu::Locale& locale); - // Compute the hyphenation of a word, storing the hyphenation in result vector. Each - // entry in the vector is a "hyphen edit" to be applied at the corresponding code unit - // offset in the word. Currently 0 means no hyphen and 1 means insert hyphen and break, - // but this will be expanded to other edits for nonstandard hyphenation. - // Example: word is "hyphen", result is [0 0 1 0 0 0], corresponding to "hy-phen". - void hyphenate(std::vector* result, const uint16_t* word, size_t len); + // Returns true if the codepoint is like U+2010 HYPHEN in line breaking and usage: a character + // immediately after which line breaks are allowed, but words containing it should not be + // automatically hyphenated. + static bool isLineBreakingHyphen(uint32_t cp); // pattern data is in binary format, as described in doc/hyb_file_format.md. Note: // the caller is responsible for ensuring that the lifetime of the pattern data is // at least as long as the Hyphenator object. - // Note: nullptr is valid input, in which case the hyphenator only processes soft hyphens + // Note: nullptr is valid input, in which case the hyphenator only processes soft hyphens. static Hyphenator* loadBinary(const uint8_t* patternData); private: - // apply soft hyphens only, ignoring patterns - void hyphenateSoft(uint8_t* result, const uint16_t* word, size_t len); + // apply various hyphenation rules including hard and soft hyphens, ignoring patterns + void hyphenateWithNoPatterns(HyphenationType* result, const uint16_t* word, size_t len, + const icu::Locale& locale); - // try looking up word in alphabet table, return false if any code units fail to map - // Note that this methor writes len+2 entries into alpha_codes (including start and stop) - bool alphabetLookup(uint16_t* alpha_codes, const uint16_t* word, size_t len); + // Try looking up word in alphabet table, return DONT_BREAK if any code units fail to map. + // Otherwise, returns BREAK_AND_INSERT_HYPHEN, BREAK_AND_INSERT_ARMENIAN_HYPHEN, or + // BREAK_AND_DONT_INSERT_HYPHEN based on the the script of the characters seen. + // Note that this method writes len+2 entries into alpha_codes (including start and stop) + HyphenationType alphabetLookup(uint16_t* alpha_codes, const uint16_t* word, size_t len); // calculate hyphenation from patterns, assuming alphabet lookup has already been done - void hyphenateFromCodes(uint8_t* result, const uint16_t* codes, size_t len); + void hyphenateFromCodes(HyphenationType* result, const uint16_t* codes, size_t len, + HyphenationType hyphenValue); // TODO: these should become parameters, as they might vary by locale, screen size, and // possibly explicit user control. diff --git a/engine/src/flutter/include/minikin/LineBreaker.h b/engine/src/flutter/include/minikin/LineBreaker.h index e93953666b..ce8eb7d571 100644 --- a/engine/src/flutter/include/minikin/LineBreaker.h +++ b/engine/src/flutter/include/minikin/LineBreaker.h @@ -198,18 +198,18 @@ class LineBreaker { size_t lineNumber; // only updated for non-constant line widths size_t preSpaceCount; // preceding space count before breaking size_t postSpaceCount; // preceding space count after breaking - uint8_t hyphenEdit; + HyphenationType hyphenType; }; float currentLineWidth() const; void addWordBreak(size_t offset, ParaWidth preBreak, ParaWidth postBreak, - size_t preSpaceCount, size_t postSpaceCount, float penalty, uint8_t hyph); + size_t preSpaceCount, size_t postSpaceCount, float penalty, HyphenationType hyph); void addCandidate(Candidate cand); // push an actual break to the output. Takes care of setting flags for tab - void pushBreak(int offset, float width, uint8_t hyph); + void pushBreak(int offset, float width, uint8_t hyphenEdit); float getSpaceWidth() const; @@ -220,11 +220,12 @@ class LineBreaker { void finishBreaksOptimal(); WordBreaker mWordBreaker; + icu::Locale mLocale; std::vectormTextBuf; std::vectormCharWidths; Hyphenator* mHyphenator; - std::vector mHyphBuf; + std::vector mHyphBuf; // layout parameters BreakStrategy mStrategy = kBreakStrategy_Greedy; diff --git a/engine/src/flutter/include/minikin/MinikinFont.h b/engine/src/flutter/include/minikin/MinikinFont.h index 1d5ebb774a..52263f529a 100644 --- a/engine/src/flutter/include/minikin/MinikinFont.h +++ b/engine/src/flutter/include/minikin/MinikinFont.h @@ -21,25 +21,13 @@ #include #include +#include // An abstraction for platform fonts, allowing Minikin to be used with // multiple actual implementations of fonts. namespace minikin { -// The hyphen edit represents an edit to the string when a word is -// hyphenated. The most common hyphen edit is adding a "-" at the end -// of a syllable, but nonstandard hyphenation allows for more choices. -class HyphenEdit { -public: - HyphenEdit() : hyphen(0) { } - HyphenEdit(uint32_t hyphenInt) : hyphen(hyphenInt) { } // NOLINT(implicit) - bool hasHyphen() const { return hyphen != 0; } - bool operator==(const HyphenEdit &other) const { return hyphen == other.hyphen; } -private: - uint32_t hyphen; -}; - class MinikinFont; // Possibly move into own .h file? diff --git a/engine/src/flutter/libs/minikin/FontCollection.cpp b/engine/src/flutter/libs/minikin/FontCollection.cpp index c351c3a58d..8ec302b5ea 100644 --- a/engine/src/flutter/libs/minikin/FontCollection.cpp +++ b/engine/src/flutter/libs/minikin/FontCollection.cpp @@ -328,7 +328,8 @@ const std::shared_ptr& FontCollection::getFamilyForChar(uint32_t ch, return familyVec[bestFamilyIndex]; } -const uint32_t NBSP = 0xA0; +const uint32_t NBSP = 0x00A0; +const uint32_t SOFT_HYPHEN = 0x00AD; const uint32_t ZWJ = 0x200C; const uint32_t ZWNJ = 0x200D; const uint32_t HYPHEN = 0x2010; @@ -421,8 +422,8 @@ void FontCollection::itemize(const uint16_t *string, size_t string_size, FontSty if (isStickyWhitelisted(ch)) { // Continue using existing font as long as it has coverage and is whitelisted shouldContinueRun = lastFamily->getCoverage().get(ch); - } else if (isVariationSelector(ch)) { - // Always continue if the character is a variation selector. + } else if (ch == SOFT_HYPHEN || isVariationSelector(ch)) { + // Always continue if the character is the soft hyphen or a variation selector. shouldContinueRun = true; } } diff --git a/engine/src/flutter/libs/minikin/Hyphenator.cpp b/engine/src/flutter/libs/minikin/Hyphenator.cpp index c170c6bd48..5ec82feb50 100644 --- a/engine/src/flutter/libs/minikin/Hyphenator.cpp +++ b/engine/src/flutter/libs/minikin/Hyphenator.cpp @@ -19,6 +19,7 @@ #include #include #include +#include // HACK: for reading pattern file #include @@ -32,7 +33,10 @@ using std::vector; namespace minikin { +static const uint16_t CHAR_HYPHEN_MINUS = 0x002D; static const uint16_t CHAR_SOFT_HYPHEN = 0x00AD; +static const uint16_t CHAR_MIDDLE_DOT = 0x00B7; +static const uint16_t CHAR_HYPHEN = 0x2010; // The following are structs that correspond to tables inside the hyb file format @@ -110,34 +114,216 @@ Hyphenator* Hyphenator::loadBinary(const uint8_t* patternData) { return result; } -void Hyphenator::hyphenate(vector* result, const uint16_t* word, size_t len) { +void Hyphenator::hyphenate(vector* result, const uint16_t* word, size_t len, + const icu::Locale& locale) { result->clear(); result->resize(len); const size_t paddedLen = len + 2; // start and stop code each count for 1 if (patternData != nullptr && (int)len >= MIN_PREFIX + MIN_SUFFIX && paddedLen <= MAX_HYPHENATED_SIZE) { uint16_t alpha_codes[MAX_HYPHENATED_SIZE]; - if (alphabetLookup(alpha_codes, word, len)) { - hyphenateFromCodes(result->data(), alpha_codes, paddedLen); + const HyphenationType hyphenValue = alphabetLookup(alpha_codes, word, len); + if (hyphenValue != HyphenationType::DONT_BREAK) { + hyphenateFromCodes(result->data(), alpha_codes, paddedLen, hyphenValue); return; } // TODO: try NFC normalization // TODO: handle non-BMP Unicode (requires remapping of offsets) } - hyphenateSoft(result->data(), word, len); + // Note that we will always get here if the word contains a hyphen or a soft hyphen, because the + // alphabet is not expected to contain a hyphen or a soft hyphen character, so alphabetLookup + // would return DONT_BREAK. + hyphenateWithNoPatterns(result->data(), word, len, locale); } -// If any soft hyphen is present in the word, use soft hyphens to decide hyphenation, -// as recommended in UAX #14 (Use of Soft Hyphen) -void Hyphenator::hyphenateSoft(uint8_t* result, const uint16_t* word, size_t len) { - result[0] = 0; +// This function determines whether a character is like U+2010 HYPHEN in +// line breaking and usage: a character immediately after which line breaks +// are allowed, but words containing it should not be automatically +// hyphenated using patterns. This is a curated set, created by manually +// inspecting all the characters that have the Unicode line breaking +// property of BA or HY and seeing which ones are hyphens. +bool Hyphenator::isLineBreakingHyphen(uint32_t c) { + return (c == 0x002D || // HYPHEN-MINUS + c == 0x058A || // ARMENIAN HYPHEN + c == 0x05BE || // HEBREW PUNCTUATION MAQAF + c == 0x1400 || // CANADIAN SYLLABICS HYPHEN + c == 0x2010 || // HYPHEN + c == 0x2013 || // EN DASH + c == 0x2027 || // HYPHENATION POINT + c == 0x2E17 || // DOUBLE OBLIQUE HYPHEN + c == 0x2E40); // DOUBLE HYPHEN +} + +const static uint32_t HYPHEN_STR[] = {0x2010, 0}; +const static uint32_t ARMENIAN_HYPHEN_STR[] = {0x058A, 0}; +const static uint32_t MAQAF_STR[] = {0x05BE, 0}; +const static uint32_t UCAS_HYPHEN_STR[] = {0x1400, 0}; +const static uint32_t ZWJ_STR[] = {0x200D, 0}; +const static uint32_t ZWJ_AND_HYPHEN_STR[] = {0x200D, 0x2010, 0}; + +const uint32_t* HyphenEdit::getHyphenString(uint32_t hyph) { + switch (hyph) { + case INSERT_HYPHEN_AT_END: + case REPLACE_WITH_HYPHEN_AT_END: + case INSERT_HYPHEN_AT_START: + return HYPHEN_STR; + case INSERT_ARMENIAN_HYPHEN_AT_END: + return ARMENIAN_HYPHEN_STR; + case INSERT_MAQAF_AT_END: + return MAQAF_STR; + case INSERT_UCAS_HYPHEN_AT_END: + return UCAS_HYPHEN_STR; + case INSERT_ZWJ_AND_HYPHEN_AT_END: + return ZWJ_AND_HYPHEN_STR; + case INSERT_ZWJ_AT_START: + return ZWJ_STR; + default: + return nullptr; + } +} + +uint32_t HyphenEdit::editForThisLine(HyphenationType type) { + switch (type) { + case HyphenationType::DONT_BREAK: + return NO_EDIT; + case HyphenationType::BREAK_AND_INSERT_HYPHEN: + return INSERT_HYPHEN_AT_END; + case HyphenationType::BREAK_AND_INSERT_ARMENIAN_HYPHEN: + return INSERT_ARMENIAN_HYPHEN_AT_END; + case HyphenationType::BREAK_AND_INSERT_MAQAF: + return INSERT_MAQAF_AT_END; + case HyphenationType::BREAK_AND_INSERT_UCAS_HYPHEN: + return INSERT_UCAS_HYPHEN_AT_END; + case HyphenationType::BREAK_AND_REPLACE_WITH_HYPHEN: + return REPLACE_WITH_HYPHEN_AT_END; + case HyphenationType::BREAK_AND_INSERT_HYPHEN_AND_ZWJ: + return INSERT_ZWJ_AND_HYPHEN_AT_END; + default: + return BREAK_AT_END; + } +} + +uint32_t HyphenEdit::editForNextLine(HyphenationType type) { + switch (type) { + case HyphenationType::DONT_BREAK: + return NO_EDIT; + case HyphenationType::BREAK_AND_INSERT_HYPHEN_AT_NEXT_LINE: + return INSERT_HYPHEN_AT_START; + case HyphenationType::BREAK_AND_INSERT_HYPHEN_AND_ZWJ: + return INSERT_ZWJ_AT_START; + default: + return BREAK_AT_START; + } +} + +static UScriptCode getScript(uint32_t codePoint) { + UErrorCode errorCode = U_ZERO_ERROR; + const UScriptCode script = uscript_getScript(static_cast(codePoint), &errorCode); + if (U_SUCCESS(errorCode)) { + return script; + } else { + return USCRIPT_INVALID_CODE; + } +} + +static HyphenationType hyphenationTypeBasedOnScript(uint32_t codePoint) { + // Note: It's not clear what the best hyphen for Hebrew is. While maqaf is the "correct" hyphen + // for Hebrew, modern practice may have shifted towards Western hyphens. We use normal hyphens + // for now to be safe. BREAK_AND_INSERT_MAQAF is already implemented, so if we want to switch + // to maqaf for Hebrew, we can simply add a condition here. + const UScriptCode script = getScript(codePoint); + if (script == USCRIPT_KANNADA + || script == USCRIPT_MALAYALAM + || script == USCRIPT_TAMIL + || script == USCRIPT_TELUGU) { + // Grantha is not included, since we don't support non-BMP hyphenation yet. + return HyphenationType::BREAK_AND_DONT_INSERT_HYPHEN; + } else if (script == USCRIPT_ARMENIAN) { + return HyphenationType::BREAK_AND_INSERT_ARMENIAN_HYPHEN; + } else if (script == USCRIPT_CANADIAN_ABORIGINAL) { + return HyphenationType::BREAK_AND_INSERT_UCAS_HYPHEN; + } else { + return HyphenationType::BREAK_AND_INSERT_HYPHEN; + } +} + +static inline int32_t getJoiningType(UChar32 codepoint) { + return u_getIntPropertyValue(codepoint, UCHAR_JOINING_TYPE); +} + +// Assumption for caller: location must be >= 2 and word[location] == CHAR_SOFT_HYPHEN. +// This function decides if the letters before and after the hyphen should appear as joining. +static inline HyphenationType getHyphTypeForArabic(const uint16_t* word, size_t len, + size_t location) { + ssize_t i = location; + int32_t type = U_JT_NON_JOINING; + while (static_cast(i) < len && (type = getJoiningType(word[i])) == U_JT_TRANSPARENT) { + i++; + } + if (type == U_JT_DUAL_JOINING || type == U_JT_RIGHT_JOINING || type == U_JT_JOIN_CAUSING) { + // The next character is of the type that may join the last character. See if the last + // character is also of the right type. + i = location - 2; // Skip the soft hyphen + type = U_JT_NON_JOINING; + while (i >= 0 && (type = getJoiningType(word[i])) == U_JT_TRANSPARENT) { + i--; + } + if (type == U_JT_DUAL_JOINING || type == U_JT_LEFT_JOINING || type == U_JT_JOIN_CAUSING) { + return HyphenationType::BREAK_AND_INSERT_HYPHEN_AND_ZWJ; + } + } + return HyphenationType::BREAK_AND_INSERT_HYPHEN; +} + +// Use various recommendations of UAX #14 Unicode Line Breaking Algorithm for hyphenating words +// that didn't match patterns, especially words that contain hyphens or soft hyphens (See sections +// 5.3, Use of Hyphen, and 5.4, Use of Soft Hyphen). +void Hyphenator::hyphenateWithNoPatterns(HyphenationType* result, const uint16_t* word, size_t len, + const icu::Locale& locale) { + result[0] = HyphenationType::DONT_BREAK; for (size_t i = 1; i < len; i++) { - result[i] = word[i - 1] == CHAR_SOFT_HYPHEN; + const uint16_t prevChar = word[i - 1]; + if (i > 1 && isLineBreakingHyphen(prevChar)) { + // Break after hyphens, but only if they don't start the word. + + if ((prevChar == CHAR_HYPHEN_MINUS || prevChar == CHAR_HYPHEN) + && strcmp(locale.getLanguage(), "pl") == 0 + && getScript(word[i]) == USCRIPT_LATIN ) { + // In Polish, hyphens get repeated at the next line. To be safe, + // we will do this only if the next character is Latin. + result[i] = HyphenationType::BREAK_AND_INSERT_HYPHEN_AT_NEXT_LINE; + } else { + result[i] = HyphenationType::BREAK_AND_DONT_INSERT_HYPHEN; + } + } else if (i > 1 && prevChar == CHAR_SOFT_HYPHEN) { + // Break after soft hyphens, but only if they don't start the word (a soft hyphen + // starting the word doesn't give any useful break opportunities). The type of the break + // is based on the script of the character we break on. + if (getScript(word[i]) == USCRIPT_ARABIC) { + // For Arabic, we need to look and see if the characters around the soft hyphen + // actually join. If they don't, we'll just insert a normal hyphen. + result[i] = getHyphTypeForArabic(word, len, i); + } else { + result[i] = hyphenationTypeBasedOnScript(word[i]); + } + } else if (prevChar == CHAR_MIDDLE_DOT + && MIN_PREFIX < i && i <= len - MIN_SUFFIX + && ((word[i - 2] == 'l' && word[i] == 'l') + || (word[i - 2] == 'L' && word[i] == 'L')) + && strcmp(locale.getLanguage(), "ca") == 0) { + // In Catalan, "l·l" should break as "l-" on the first line + // and "l" on the next line. + result[i] = HyphenationType::BREAK_AND_REPLACE_WITH_HYPHEN; + } else { + result[i] = HyphenationType::DONT_BREAK; + } } } -bool Hyphenator::alphabetLookup(uint16_t* alpha_codes, const uint16_t* word, size_t len) { +HyphenationType Hyphenator::alphabetLookup(uint16_t* alpha_codes, const uint16_t* word, + size_t len) { const Header* header = getHeader(); + HyphenationType result = HyphenationType::BREAK_AND_INSERT_HYPHEN; // TODO: check header magic uint32_t alphabetVersion = header->alphabetVersion(); if (alphabetVersion == 0) { @@ -148,16 +334,19 @@ bool Hyphenator::alphabetLookup(uint16_t* alpha_codes, const uint16_t* word, siz for (size_t i = 0; i < len; i++) { uint16_t c = word[i]; if (c < min_codepoint || c >= max_codepoint) { - return false; + return HyphenationType::DONT_BREAK; } uint8_t code = alphabet->data[c - min_codepoint]; if (code == 0) { - return false; + return HyphenationType::DONT_BREAK; + } + if (result == HyphenationType::BREAK_AND_INSERT_HYPHEN) { + result = hyphenationTypeBasedOnScript(c); } alpha_codes[i + 1] = code; } alpha_codes[len + 1] = 0; // word termination - return true; + return result; } else if (alphabetVersion == 1) { const AlphabetTable1* alphabet = header->alphabetTable1(); size_t n_entries = alphabet->n_entries; @@ -168,18 +357,21 @@ bool Hyphenator::alphabetLookup(uint16_t* alpha_codes, const uint16_t* word, siz uint16_t c = word[i]; auto p = std::lower_bound(begin, end, c << 11); if (p == end) { - return false; + return HyphenationType::DONT_BREAK; } uint32_t entry = *p; if (AlphabetTable1::codepoint(entry) != c) { - return false; + return HyphenationType::DONT_BREAK; + } + if (result == HyphenationType::BREAK_AND_INSERT_HYPHEN) { + result = hyphenationTypeBasedOnScript(c); } alpha_codes[i + 1] = AlphabetTable1::value(entry); } alpha_codes[len + 1] = 0; - return true; + return result; } - return false; + return HyphenationType::DONT_BREAK; } /** @@ -187,7 +379,12 @@ bool Hyphenator::alphabetLookup(uint16_t* alpha_codes, const uint16_t* word, siz * has been done by now, and all characters have been found in the alphabet. * Note: len here is the padded length including 0 codes at start and end. **/ -void Hyphenator::hyphenateFromCodes(uint8_t* result, const uint16_t* codes, size_t len) { +void Hyphenator::hyphenateFromCodes(HyphenationType* result, const uint16_t* codes, size_t len, + HyphenationType hyphenValue) { + static_assert(sizeof(HyphenationType) == sizeof(uint8_t), "HyphnationType must be uint8_t."); + // Reuse the result array as a buffer for calculating intermediate hyphenation numbers. + uint8_t* buffer = reinterpret_cast(result); + const Header* header = getHeader(); const Trie* trie = header->trieTable(); const Pattern* pattern = header->patternTable(); @@ -209,26 +406,27 @@ void Hyphenator::hyphenateFromCodes(uint8_t* result, const uint16_t* codes, size uint32_t pat_ix = trie->data[node] >> pattern_shift; // pat_ix contains a 3-tuple of length, shift (number of trailing zeros), and an offset // into the buf pool. This is the pattern for the substring (i..j) we just matched, - // which we combine (via point-wise max) into the result vector. + // which we combine (via point-wise max) into the buffer vector. if (pat_ix != 0) { uint32_t pat_entry = pattern->data[pat_ix]; int pat_len = Pattern::len(pat_entry); int pat_shift = Pattern::shift(pat_entry); const uint8_t* pat_buf = pattern->buf(pat_entry); int offset = j + 1 - (pat_len + pat_shift); - // offset is the index within result that lines up with the start of pat_buf + // offset is the index within buffer that lines up with the start of pat_buf int start = std::max(MIN_PREFIX - offset, 0); int end = std::min(pat_len, (int)maxOffset - offset); for (int k = start; k < end; k++) { - result[offset + k] = std::max(result[offset + k], pat_buf[k]); + buffer[offset + k] = std::max(buffer[offset + k], pat_buf[k]); } } } } // Since the above calculation does not modify values outside - // [MIN_PREFIX, len - MIN_SUFFIX], they are left as 0. + // [MIN_PREFIX, len - MIN_SUFFIX], they are left as 0 = DONT_BREAK. for (size_t i = MIN_PREFIX; i < maxOffset; i++) { - result[i] &= 1; + // Hyphenation opportunities happen when the hyphenation numbers are odd. + result[i] = (buffer[i] & 1u) ? hyphenValue : HyphenationType::DONT_BREAK; } } diff --git a/engine/src/flutter/libs/minikin/Layout.cpp b/engine/src/flutter/libs/minikin/Layout.cpp index 6b28f57a33..743cb763ae 100644 --- a/engine/src/flutter/libs/minikin/Layout.cpp +++ b/engine/src/flutter/libs/minikin/Layout.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include @@ -242,7 +243,7 @@ android::hash_t LayoutCacheKey::computeHash() const { hash = android::JenkinsHashMix(hash, hash_type(mSkewX)); hash = android::JenkinsHashMix(hash, hash_type(mLetterSpacing)); hash = android::JenkinsHashMix(hash, hash_type(mPaintFlags)); - hash = android::JenkinsHashMix(hash, hash_type(mHyphenEdit.hasHyphen())); + hash = android::JenkinsHashMix(hash, hash_type(mHyphenEdit.getHyphen())); hash = android::JenkinsHashMix(hash, hash_type(mIsRtl)); hash = android::JenkinsHashMixShorts(hash, mChars, mNchars); return android::JenkinsHashWhiten(hash); @@ -623,7 +624,7 @@ float Layout::measureText(const uint16_t* buf, size_t start, size_t count, size_ float Layout::doLayoutRunCached(const uint16_t* buf, size_t start, size_t count, size_t bufSize, bool isRtl, LayoutContext* ctx, size_t dstStart, const std::shared_ptr& collection, Layout* layout, float* advances) { - HyphenEdit hyphen = ctx->paint.hyphenEdit; + const uint32_t originalHyphen = ctx->paint.hyphenEdit.getHyphen(); float advance = 0; if (!isRtl) { // left to right @@ -632,8 +633,15 @@ float Layout::doLayoutRunCached(const uint16_t* buf, size_t start, size_t count, size_t wordend; for (size_t iter = start; iter < start + count; iter = wordend) { wordend = getNextWordBreakForCache(buf, iter, bufSize); - // Only apply hyphen to the last word in the string. - ctx->paint.hyphenEdit = wordend >= start + count ? hyphen : HyphenEdit(); + // Only apply hyphen to the first or last word in the string. + uint32_t hyphen = originalHyphen; + if (iter != start) { // Not the first word + hyphen &= ~HyphenEdit::MASK_START_OF_LINE; + } + if (wordend < start + count) { // Not the last word + hyphen &= ~HyphenEdit::MASK_END_OF_LINE; + } + ctx->paint.hyphenEdit = hyphen; size_t wordcount = std::min(start + count, wordend) - iter; advance += doLayoutWord(buf + wordstart, iter - wordstart, wordcount, wordend - wordstart, isRtl, ctx, iter - dstStart, collection, layout, @@ -647,8 +655,15 @@ float Layout::doLayoutRunCached(const uint16_t* buf, size_t start, size_t count, size_t wordend = end == 0 ? 0 : getNextWordBreakForCache(buf, end - 1, bufSize); for (size_t iter = end; iter > start; iter = wordstart) { wordstart = getPrevWordBreakForCache(buf, iter, bufSize); - // Only apply hyphen to the last (leftmost) word in the string. - ctx->paint.hyphenEdit = iter == end ? hyphen : HyphenEdit(); + // Only apply hyphen to the first (rightmost) or last (leftmost) word in the string. + uint32_t hyphen = originalHyphen; + if (wordstart > start) { // Not the first word + hyphen &= ~HyphenEdit::MASK_START_OF_LINE; + } + if (iter != end) { // Not the last word + hyphen &= ~HyphenEdit::MASK_END_OF_LINE; + } + ctx->paint.hyphenEdit = hyphen; size_t bufStart = std::max(start, wordstart); advance += doLayoutWord(buf + wordstart, bufStart - wordstart, iter - bufStart, wordend - wordstart, isRtl, ctx, bufStart - dstStart, collection, layout, @@ -719,6 +734,134 @@ static void addFeatures(const string &str, vector* features) { } } +static inline hb_codepoint_t determineHyphenChar(hb_codepoint_t preferredHyphen, hb_font_t* font) { + if (preferredHyphen == 0x2010 /* HYPHEN */ + || preferredHyphen == 0x058A /* ARMENIAN_HYPHEN */ + || preferredHyphen == 0x05BE /* HEBREW PUNCTUATION MAQAF */ + || preferredHyphen == 0x1400 /* CANADIAN SYLLABIC HYPHEN */) { + hb_codepoint_t glyph; + // Fallback to ASCII HYPHEN-MINUS if the font didn't have a glyph for the preferred hyphen. + // Note that we intentionally don't do anything special if the font doesn't have a + // HYPHEN-MINUS either, so a tofu could be shown, hinting towards something missing. + if (!hb_font_get_nominal_glyph(font, preferredHyphen, &glyph)) { + return 0x002D; // HYPHEN-MINUS + } + } + return preferredHyphen; +} + +static inline void addHyphenToHbBuffer(hb_buffer_t* buffer, hb_font_t* font, uint32_t hyphen, + uint32_t cluster) { + const uint32_t* hyphenStr = HyphenEdit::getHyphenString(hyphen); + while (*hyphenStr != 0) { + hb_codepoint_t hyphenChar = determineHyphenChar(*hyphenStr, font); + hb_buffer_add(buffer, hyphenChar, cluster); + hyphenStr++; + } +} + +// Returns the cluster value assigned to the first codepoint added to the buffer, which can be used +// to translate cluster values returned by HarfBuzz to input indices. +static inline uint32_t addToHbBuffer(hb_buffer_t* buffer, + const uint16_t* buf, size_t start, size_t count, size_t bufSize, + ssize_t scriptRunStart, ssize_t scriptRunEnd, + HyphenEdit hyphenEdit, hb_font_t* hbFont) { + + // Only hyphenate the very first script run for starting hyphens. + const uint32_t startHyphen = (scriptRunStart == 0) + ? hyphenEdit.getStart() + : HyphenEdit::NO_EDIT; + // Only hyphenate the very last script run for ending hyphens. + const uint32_t endHyphen = (static_cast(scriptRunEnd) == count) + ? hyphenEdit.getEnd() + : HyphenEdit::NO_EDIT; + + // In the following code, we drop the pre-context and/or post-context if there is a + // hyphen edit at that end. This is not absolutely necessary, since HarfBuzz uses + // contexts only for joining scripts at the moment, e.g. to determine if the first or + // last letter of a text range to shape should take a joining form based on an + // adjacent letter or joiner (that comes from the context). + // + // TODO: Revisit this for: + // 1. Desperate breaks for joining scripts like Arabic (where it may be better to keep + // the context); + // 2. Special features like start-of-word font features (not implemented in HarfBuzz + // yet). + + // We don't have any start-of-line replacement edit yet, so we don't need to check for + // those. + if (HyphenEdit::isInsertion(startHyphen)) { + // A cluster value of zero guarantees that the inserted hyphen will be in the same + // cluster with the next codepoint, since there is no pre-context. + addHyphenToHbBuffer(buffer, hbFont, startHyphen, 0 /* cluster value */); + } + + const uint16_t* hbText; + int hbTextLength; + unsigned int hbItemOffset; + unsigned int hbItemLength = scriptRunEnd - scriptRunStart; // This is >= 1. + + const bool hasEndInsertion = HyphenEdit::isInsertion(endHyphen); + const bool hasEndReplacement = HyphenEdit::isReplacement(endHyphen); + if (hasEndReplacement) { + // Skip the last code unit while copying the buffer for HarfBuzz if it's a replacement. We + // don't need to worry about non-BMP characters yet since replacements are only done for + // code units at the moment. + hbItemLength -= 1; + } + + if (startHyphen == HyphenEdit::NO_EDIT) { + // No edit at the beginning. Use the whole pre-context. + hbText = buf; + hbItemOffset = start + scriptRunStart; + } else { + // There's an edit at the beginning. Drop the pre-context and start the buffer at where we + // want to start shaping. + hbText = buf + start + scriptRunStart; + hbItemOffset = 0; + } + + if (endHyphen == HyphenEdit::NO_EDIT) { + // No edit at the end, use the whole post-context. + hbTextLength = (buf + bufSize) - hbText; + } else { + // There is an edit at the end. Drop the post-context. + hbTextLength = hbItemOffset + hbItemLength; + } + + hb_buffer_add_utf16(buffer, hbText, hbTextLength, hbItemOffset, hbItemLength); + + unsigned int numCodepoints; + hb_glyph_info_t* cpInfo = hb_buffer_get_glyph_infos(buffer, &numCodepoints); + + // Add the hyphen at the end, if there's any. + if (hasEndInsertion || hasEndReplacement) { + // When a hyphen is inserted, by assigning the added hyphen and the last + // codepoint added to the HarfBuzz buffer to the same cluster, we can make sure + // that they always remain in the same cluster, even if the last codepoint gets + // merged into another cluster (for example when it's a combining mark). + // + // When a replacement happens instead, we want it to get the cluster value of + // the character it's replacing, which is one "codepoint length" larger than + // the last cluster. But since the character replaced is always just one + // code unit, we can just add 1. + uint32_t hyphenCluster; + if (numCodepoints == 0) { + // Nothing was added to the HarfBuzz buffer. This can only happen if + // we have a replacement that is replacing a one-code unit script run. + hyphenCluster = 0; + } else { + hyphenCluster = cpInfo[numCodepoints - 1].cluster + (uint32_t) hasEndReplacement; + } + addHyphenToHbBuffer(buffer, hbFont, endHyphen, hyphenCluster); + // Since we have just added to the buffer, cpInfo no longer necessarily points to + // the right place. Refresh it. + cpInfo = hb_buffer_get_glyph_infos(buffer, nullptr /* we don't need the size */); + } + return cpInfo[0].cluster; +} + + void Layout::doLayoutRun(const uint16_t* buf, size_t start, size_t count, size_t bufSize, bool isRtl, LayoutContext* ctx) { hb_buffer_t* buffer = LayoutEngine::getInstance().hbBuffer; @@ -769,10 +912,21 @@ void Layout::doLayoutRun(const uint16_t* buf, size_t start, size_t count, size_t // TODO: if there are multiple scripts within a font in an RTL run, // we need to reorder those runs. This is unlikely with our current // font stack, but should be done for correctness. - ssize_t srunend; - for (ssize_t srunstart = run.start; srunstart < run.end; srunstart = srunend) { - srunend = srunstart; - hb_script_t script = getScriptRun(buf + start, run.end, &srunend); + + // Note: scriptRunStart and scriptRunEnd, as well as run.start and run.end, run between 0 + // and count. + ssize_t scriptRunEnd; + for (ssize_t scriptRunStart = run.start; + scriptRunStart < run.end; + scriptRunStart = scriptRunEnd) { + scriptRunEnd = scriptRunStart; + hb_script_t script = getScriptRun(buf + start, run.end, &scriptRunEnd /* iterator */); + // After the last line, scriptRunEnd is guaranteed to have increased, since the only + // time getScriptRun does not increase its iterator is when it has already reached the + // end of the buffer. But that can't happen, since if we have already reached the end + // of the buffer, we should have had (scriptRunEnd == run.end), which means + // (scriptRunStart == run.end) which is impossible due to the exit condition of the for + // loop. So we can be sure that scriptRunEnd > scriptRunStart. double letterSpace = 0.0; double letterSpaceHalfLeft = 0.0; @@ -804,30 +958,29 @@ void Layout::doLayoutRun(const uint16_t* buf, size_t start, size_t count, size_t } hb_buffer_set_language(buffer, hbLanguage->getHbLanguage()); } - hb_buffer_add_utf16(buffer, buf, bufSize, srunstart + start, srunend - srunstart); - if (ctx->paint.hyphenEdit.hasHyphen() && srunend > srunstart) { - // TODO: check whether this is really the desired semantics. It could have the - // effect of assigning the hyphen width to a nonspacing mark - unsigned int lastCluster = start + srunend - 1; - hb_codepoint_t hyphenChar = 0x2010; // HYPHEN - hb_codepoint_t glyph; - // Fallback to ASCII HYPHEN-MINUS if the font didn't have a glyph for HYPHEN. Note - // that we intentionally don't do anything special if the font doesn't have a - // HYPHEN-MINUS either, so a tofu could be shown, hinting towards something - // missing. - if (!hb_font_get_glyph(hbFont, hyphenChar, 0, &glyph)) { - hyphenChar = 0x002D; // HYPHEN-MINUS - } - hb_buffer_add(buffer, hyphenChar, lastCluster); - } + const uint32_t clusterStart = addToHbBuffer( + buffer, + buf, start, count, bufSize, + scriptRunStart, scriptRunEnd, + ctx->paint.hyphenEdit, hbFont); + hb_shape(hbFont, buffer, features.empty() ? NULL : &features[0], features.size()); unsigned int numGlyphs; hb_glyph_info_t* info = hb_buffer_get_glyph_infos(buffer, &numGlyphs); hb_glyph_position_t* positions = hb_buffer_get_glyph_positions(buffer, NULL); + + // At this point in the code, the cluster values in the info buffer correspond to the + // input characters with some shift. The cluster value clusterStart corresponds to the + // first character passed to HarfBuzz, which is at buf[start + scriptRunStart] whose + // advance needs to be saved into mAdvances[scriptRunStart]. So cluster values need to + // be reduced by (clusterStart - scriptRunStart) to get converted to indices of + // mAdvances. + const ssize_t clusterOffset = clusterStart - scriptRunStart; + if (numGlyphs) { - mAdvances[info[0].cluster - start] += letterSpaceHalfLeft; + mAdvances[info[0].cluster - clusterOffset] += letterSpaceHalfLeft; x += letterSpaceHalfLeft; } for (unsigned int i = 0; i < numGlyphs; i++) { @@ -840,8 +993,8 @@ void Layout::doLayoutRun(const uint16_t* buf, size_t start, size_t count, size_t positions[i].x_offset, positions[i].y_offset); #endif if (i > 0 && info[i - 1].cluster != info[i].cluster) { - mAdvances[info[i - 1].cluster - start] += letterSpaceHalfRight; - mAdvances[info[i].cluster - start] += letterSpaceHalfLeft; + mAdvances[info[i - 1].cluster - clusterOffset] += letterSpaceHalfRight; + mAdvances[info[i].cluster - clusterOffset] += letterSpaceHalfLeft; x += letterSpace; } @@ -871,17 +1024,17 @@ void Layout::doLayoutRun(const uint16_t* buf, size_t start, size_t count, size_t } glyphBounds.offset(x + xoff, y + yoff); mBounds.join(glyphBounds); - if (info[i].cluster - start < count) { - mAdvances[info[i].cluster - start] += xAdvance; + if (static_cast(info[i].cluster - clusterOffset) < count) { + mAdvances[info[i].cluster - clusterOffset] += xAdvance; } else { ALOGE("cluster %zu (start %zu) out of bounds of count %zu", - info[i].cluster - start, start, count); + info[i].cluster - clusterOffset, start, count); } x += xAdvance; } if (numGlyphs) { - mAdvances[info[numGlyphs - 1].cluster - start] += letterSpaceHalfRight; + mAdvances[info[numGlyphs - 1].cluster - clusterOffset] += letterSpaceHalfRight; x += letterSpaceHalfRight; } } diff --git a/engine/src/flutter/libs/minikin/LineBreaker.cpp b/engine/src/flutter/libs/minikin/LineBreaker.cpp index 3965cbd4c8..b8814b63d4 100644 --- a/engine/src/flutter/libs/minikin/LineBreaker.cpp +++ b/engine/src/flutter/libs/minikin/LineBreaker.cpp @@ -63,7 +63,7 @@ const float SHRINKABILITY = 1.0 / 3.0; void LineBreaker::setLocale(const icu::Locale& locale, Hyphenator* hyphenator) { mWordBreaker.setLocale(locale); - + mLocale = locale; mHyphenator = hyphenator; } @@ -73,7 +73,7 @@ void LineBreaker::setText() { // handle initial break here because addStyleRun may never be called mWordBreaker.next(); mCandidates.clear(); - Candidate cand = {0, 0, 0.0, 0.0, 0.0, 0.0, 0, 0, 0, 0}; + Candidate cand = {0, 0, 0.0, 0.0, 0.0, 0.0, 0, 0, 0, HyphenationType::DONT_BREAK}; mCandidates.push_back(cand); // reset greedy breaker state @@ -106,24 +106,6 @@ static bool isLineEndSpace(uint16_t c) { c == 0x205F || c == 0x3000; } -// This function determines whether a character is like U+2010 HYPHEN in -// line breaking and usage: a character immediately after which line breaks -// are allowed, but words containing it should not be automatically -// hyphenated. This is a curated set, created by manually inspecting all -// the characters that have the Unicode line breaking property of BA or HY -// and seeing which ones are hyphens. -static bool isLineBreakingHyphen(uint16_t c) { - return (c == 0x002D || // HYPHEN-MINUS - c == 0x058A || // ARMENIAN HYPHEN - c == 0x05BE || // HEBREW PUNCTUATION MAQAF - c == 0x1400 || // CANADIAN SYLLABICS HYPHEN - c == 0x2010 || // HYPHEN - c == 0x2013 || // EN DASH - c == 0x2027 || // HYPHENATION POINT - c == 0x2E17 || // DOUBLE OBLIQUE HYPHEN - c == 0x2E40); // DOUBLE HYPHEN -} - // Ordinarily, this method measures the text in the range given. However, when paint // is nullptr, it assumes the widths have already been calculated and stored in the // width buffer. @@ -161,7 +143,6 @@ float LineBreaker::addStyleRun(MinikinPaint* paint, const std::shared_ptr= start && wordEnd > wordStart && wordEnd - wordStart <= LONGEST_HYPHENATED_WORD) { - mHyphenator->hyphenate(&mHyphBuf, &mTextBuf[wordStart], wordEnd - wordStart); + mHyphenator->hyphenate(&mHyphBuf, + &mTextBuf[wordStart], + wordEnd - wordStart, + mLocale); #if VERBOSE_DEBUG std::string hyphenatedString; for (size_t j = wordStart; j < wordEnd; j++) { - if (mHyphBuf[j - wordStart]) hyphenatedString.push_back('-'); + if (mHyphBuf[j - wordStart] == HyphenationType::BREAK_AND_INSERT_HYPHEN) { + hyphenatedString.push_back('-'); + } // Note: only works with ASCII, should do UTF-8 conversion here hyphenatedString.push_back(buffer()[j]); } @@ -204,32 +186,33 @@ float LineBreaker::addStyleRun(MinikinPaint* paint, const std::shared_ptrhyphenEdit = hyph; - + HyphenationType hyph = mHyphBuf[j - wordStart]; + if (hyph != HyphenationType::DONT_BREAK) { + paint->hyphenEdit = HyphenEdit::editForThisLine(hyph); const float firstPartWidth = Layout::measureText(mTextBuf.data(), lastBreak, j - lastBreak, mTextBuf.size(), bidiFlags, style, *paint, typeface, nullptr); ParaWidth hyphPostBreak = lastBreakWidth + firstPartWidth; - paint->hyphenEdit = 0; + paint->hyphenEdit = HyphenEdit::editForNextLine(hyph); const float secondPartWidth = Layout::measureText(mTextBuf.data(), j, afterWord - j, mTextBuf.size(), bidiFlags, style, *paint, typeface, nullptr); ParaWidth hyphPreBreak = postBreak - secondPartWidth; + addWordBreak(j, hyphPreBreak, hyphPostBreak, postSpaceCount, postSpaceCount, hyphenPenalty, hyph); + + paint->hyphenEdit = HyphenEdit::NO_EDIT; } } } - // Skip hyphenating the next word if and only if the present word ends in a hyphen - temporarilySkipHyphenation = wordEndsInHyphen; // Skip break for zero-width characters inside replacement span if (paint != nullptr || current == end || mCharWidths[current] > 0) { float penalty = hyphenPenalty * mWordBreaker.breakBadness(); - addWordBreak(current, mWidth, postBreak, mSpaceCount, postSpaceCount, penalty, 0); + addWordBreak(current, mWidth, postBreak, mSpaceCount, postSpaceCount, penalty, + HyphenationType::DONT_BREAK); } lastBreak = current; lastBreakWidth = mWidth; @@ -243,7 +226,7 @@ float LineBreaker::addStyleRun(MinikinPaint* paint, const std::shared_ptr currentLineWidth()) { @@ -262,7 +245,7 @@ void LineBreaker::addWordBreak(size_t offset, ParaWidth preBreak, ParaWidth post cand.preSpaceCount = postSpaceCount; cand.postSpaceCount = postSpaceCount; cand.penalty = SCORE_DESPERATE; - cand.hyphenEdit = 0; + cand.hyphenType = HyphenationType::BREAK_AND_DONT_INSERT_HYPHEN; #if VERBOSE_DEBUG ALOGD("desperate cand: %zd %g:%g", mCandidates.size(), cand.postBreak, cand.preBreak); @@ -279,7 +262,7 @@ void LineBreaker::addWordBreak(size_t offset, ParaWidth preBreak, ParaWidth post cand.penalty = penalty; cand.preSpaceCount = preSpaceCount; cand.postSpaceCount = postSpaceCount; - cand.hyphenEdit = hyph; + cand.hyphenType = hyph; #if VERBOSE_DEBUG ALOGD("cand: %zd %g:%g", mCandidates.size(), cand.postBreak, cand.preBreak); #endif @@ -296,7 +279,7 @@ void LineBreaker::addCandidate(Candidate cand) { mBestBreak = candIndex; } pushBreak(mCandidates[mBestBreak].offset, mCandidates[mBestBreak].postBreak - mPreBreak, - mCandidates[mBestBreak].hyphenEdit); + HyphenEdit::editForThisLine(mCandidates[mBestBreak].hyphenType)); mBestScore = SCORE_INFTY; #if VERBOSE_DEBUG ALOGD("break: %d %g", mBreaks.back(), mWidths.back()); @@ -310,11 +293,11 @@ void LineBreaker::addCandidate(Candidate cand) { } } -void LineBreaker::pushBreak(int offset, float width, uint8_t hyph) { +void LineBreaker::pushBreak(int offset, float width, uint8_t hyphenEdit) { mBreaks.push_back(offset); mWidths.push_back(width); int flags = (mFirstTabIndex < mBreaks.back()) << kTab_Shift; - flags |= hyph; + flags |= hyphenEdit; mFlags.push_back(flags); mFirstTabIndex = INT_MAX; } @@ -345,7 +328,8 @@ void LineBreaker::computeBreaksGreedy() { // All breaks but the last have been added in addCandidate already. size_t nCand = mCandidates.size(); if (nCand == 1 || mLastBreak != nCand - 1) { - pushBreak(mCandidates[nCand - 1].offset, mCandidates[nCand - 1].postBreak - mPreBreak, 0); + pushBreak(mCandidates[nCand - 1].offset, mCandidates[nCand - 1].postBreak - mPreBreak, + HyphenEdit::NO_EDIT); // don't need to update mBestScore, because we're done #if VERBOSE_DEBUG ALOGD("final break: %d %g", mBreaks.back(), mWidths.back()); @@ -365,7 +349,11 @@ void LineBreaker::finishBreaksOptimal() { prev = mCandidates[i].prev; mBreaks.push_back(mCandidates[i].offset); mWidths.push_back(mCandidates[i].postBreak - mCandidates[prev].preBreak); - mFlags.push_back(mCandidates[i].hyphenEdit); + int flags = HyphenEdit::editForThisLine(mCandidates[i].hyphenType); + if (prev > 0) { + flags |= HyphenEdit::editForNextLine(mCandidates[prev].hyphenType); + } + mFlags.push_back(flags); } std::reverse(mBreaks.begin(), mBreaks.end()); std::reverse(mWidths.begin(), mWidths.end()); diff --git a/engine/src/flutter/libs/minikin/WordBreaker.cpp b/engine/src/flutter/libs/minikin/WordBreaker.cpp index 82596f8a04..7ad7242dff 100644 --- a/engine/src/flutter/libs/minikin/WordBreaker.cpp +++ b/engine/src/flutter/libs/minikin/WordBreaker.cpp @@ -19,6 +19,7 @@ #include #include +#include #include "MinikinInternal.h" #include @@ -74,7 +75,8 @@ static bool isBreakValid(const uint16_t* buf, size_t bufEnd, size_t i) { uint32_t codePoint; size_t prev_offset = i; U16_PREV(buf, 0, prev_offset, codePoint); - if (codePoint == CHAR_SOFT_HYPHEN) { + // Do not break on hard or soft hyphens. These are handled by automatic hyphenation. + if (Hyphenator::isLineBreakingHyphen(codePoint) || codePoint == CHAR_SOFT_HYPHEN) { return false; } // For Myanmar kinzi sequences, created by . This is to go diff --git a/engine/src/flutter/tests/perftests/Hyphenator.cpp b/engine/src/flutter/tests/perftests/Hyphenator.cpp index 692e06d2bf..1e6411f76d 100644 --- a/engine/src/flutter/tests/perftests/Hyphenator.cpp +++ b/engine/src/flutter/tests/perftests/Hyphenator.cpp @@ -22,13 +22,14 @@ namespace minikin { const char* enUsHyph = "/system/usr/hyphen-data/hyph-en-us.hyb"; +const icu::Locale& usLocale = icu::Locale::getUS(); static void BM_Hyphenator_short_word(benchmark::State& state) { Hyphenator* hyphenator = Hyphenator::loadBinary(readWholeFile(enUsHyph).data()); std::vector word = utf8ToUtf16("hyphen"); - std::vector result; + std::vector result; while (state.KeepRunning()) { - hyphenator->hyphenate(&result, word.data(), word.size()); + hyphenator->hyphenate(&result, word.data(), word.size(), usLocale); } Hyphenator::loadBinary(nullptr); } @@ -40,9 +41,9 @@ static void BM_Hyphenator_long_word(benchmark::State& state) { Hyphenator* hyphenator = Hyphenator::loadBinary(readWholeFile(enUsHyph).data()); std::vector word = utf8ToUtf16( "Pneumonoultramicroscopicsilicovolcanoconiosis"); - std::vector result; + std::vector result; while (state.KeepRunning()) { - hyphenator->hyphenate(&result, word.data(), word.size()); + hyphenator->hyphenate(&result, word.data(), word.size(), usLocale); } Hyphenator::loadBinary(nullptr); } diff --git a/engine/src/flutter/tests/unittest/Android.mk b/engine/src/flutter/tests/unittest/Android.mk index 7b3f60f8f9..da7851a3e7 100644 --- a/engine/src/flutter/tests/unittest/Android.mk +++ b/engine/src/flutter/tests/unittest/Android.mk @@ -62,6 +62,7 @@ LOCAL_STATIC_LIBRARIES += \ libxml2 LOCAL_SRC_FILES += \ + ../util/FileUtils.cpp \ ../util/FontTestUtils.cpp \ ../util/MinikinFontForTest.cpp \ ../util/UnicodeUtils.cpp \ @@ -70,6 +71,7 @@ LOCAL_SRC_FILES += \ FontFamilyTest.cpp \ FontLanguageListCacheTest.cpp \ HbFontCacheTest.cpp \ + HyphenatorTest.cpp \ MinikinInternalTest.cpp \ GraphemeBreakTests.cpp \ LayoutTest.cpp \ diff --git a/engine/src/flutter/tests/unittest/HyphenatorTest.cpp b/engine/src/flutter/tests/unittest/HyphenatorTest.cpp new file mode 100644 index 0000000000..6265c2c6c1 --- /dev/null +++ b/engine/src/flutter/tests/unittest/HyphenatorTest.cpp @@ -0,0 +1,335 @@ +/* + * 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. + */ + +#include + +#include "ICUTestBase.h" +#include +#include + +#ifndef NELEM +#define NELEM(x) ((sizeof(x) / sizeof((x)[0]))) +#endif + +namespace minikin { + +const char* usHyph = "/system/usr/hyphen-data/hyph-en-us.hyb"; +const char* malayalamHyph = "/system/usr/hyphen-data/hyph-ml.hyb"; + +typedef ICUTestBase HyphenatorTest; + +const icu::Locale catalanLocale("ca", "ES", nullptr, nullptr); +const icu::Locale polishLocale("pl", "PL", nullptr, nullptr); +const icu::Locale& usLocale = icu::Locale::getUS(); + +const uint16_t HYPHEN_MINUS = 0x002D; +const uint16_t SOFT_HYPHEN = 0x00AD; +const uint16_t MIDDLE_DOT = 0x00B7; +const uint16_t GREEK_LOWER_ALPHA = 0x03B1; +const uint16_t ARMENIAN_AYB = 0x0531; +const uint16_t HEBREW_ALEF = 0x05D0; +const uint16_t ARABIC_ALEF = 0x0627; +const uint16_t ARABIC_BEH = 0x0628; +const uint16_t ARABIC_ZWARAKAY = 0x0659; +const uint16_t MALAYALAM_KA = 0x0D15; +const uint16_t UCAS_E = 0x1401; +const uint16_t HYPHEN = 0x2010; +const uint16_t EN_DASH = 0x2013; + +// Simple test for US English. This tests "table", which happens to be the in the exceptions list. +TEST_F(HyphenatorTest, usEnglishAutomaticHyphenation) { + Hyphenator* hyphenator = Hyphenator::loadBinary(readWholeFile(usHyph).data()); + const uint16_t word[] = {'t', 'a', 'b', 'l', 'e'}; + std::vector result; + hyphenator->hyphenate(&result, word, NELEM(word), usLocale); + EXPECT_EQ((size_t) 5, result.size()); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[0]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[1]); + EXPECT_EQ(HyphenationType::BREAK_AND_INSERT_HYPHEN, result[2]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[3]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[4]); +} + +// Catalan l·l should break as l-/l +TEST_F(HyphenatorTest, catalanMiddleDot) { + Hyphenator* hyphenator = Hyphenator::loadBinary(nullptr); + const uint16_t word[] = {'l', 'l', MIDDLE_DOT, 'l', 'l', 'l'}; + std::vector result; + hyphenator->hyphenate(&result, word, NELEM(word), catalanLocale); + EXPECT_EQ((size_t) 6, result.size()); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[0]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[1]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[2]); + EXPECT_EQ(HyphenationType::BREAK_AND_REPLACE_WITH_HYPHEN, result[3]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[4]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[5]); +} + +// Catalan l·l should not break if the word is too short. +TEST_F(HyphenatorTest, catalanMiddleDotShortWord) { + Hyphenator* hyphenator = Hyphenator::loadBinary(nullptr); + const uint16_t word[] = {'l', MIDDLE_DOT, 'l'}; + std::vector result; + hyphenator->hyphenate(&result, word, NELEM(word), catalanLocale); + EXPECT_EQ((size_t) 3, result.size()); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[0]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[1]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[2]); +} + +// If we break on a hyphen in Polish, the hyphen should be repeated on the next line. +TEST_F(HyphenatorTest, polishHyphen) { + Hyphenator* hyphenator = Hyphenator::loadBinary(nullptr); + const uint16_t word[] = {'x', HYPHEN, 'y'}; + std::vector result; + hyphenator->hyphenate(&result, word, NELEM(word), polishLocale); + EXPECT_EQ((size_t) 3, result.size()); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[0]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[1]); + EXPECT_EQ(HyphenationType::BREAK_AND_INSERT_HYPHEN_AT_NEXT_LINE, result[2]); +} + +// If the language is Polish but the script is not Latin, don't use Polish rules for hyphenation. +TEST_F(HyphenatorTest, polishHyphenButNonLatinWord) { + Hyphenator* hyphenator = Hyphenator::loadBinary(nullptr); + const uint16_t word[] = {GREEK_LOWER_ALPHA, HYPHEN, GREEK_LOWER_ALPHA}; + std::vector result; + hyphenator->hyphenate(&result, word, NELEM(word), polishLocale); + EXPECT_EQ((size_t) 3, result.size()); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[0]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[1]); + EXPECT_EQ(HyphenationType::BREAK_AND_DONT_INSERT_HYPHEN, result[2]); +} + +// Polish en dash doesn't repeat on next line (as far as we know), but just provides a break +// opportunity. +TEST_F(HyphenatorTest, polishEnDash) { + Hyphenator* hyphenator = Hyphenator::loadBinary(nullptr); + const uint16_t word[] = {'x', EN_DASH, 'y'}; + std::vector result; + hyphenator->hyphenate(&result, word, NELEM(word), polishLocale); + EXPECT_EQ((size_t) 3, result.size()); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[0]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[1]); + EXPECT_EQ(HyphenationType::BREAK_AND_DONT_INSERT_HYPHEN, result[2]); +} + +// In Latin script text, soft hyphens should insert a visible hyphen if broken at. +TEST_F(HyphenatorTest, latinSoftHyphen) { + Hyphenator* hyphenator = Hyphenator::loadBinary(nullptr); + const uint16_t word[] = {'x', SOFT_HYPHEN, 'y'}; + std::vector result; + hyphenator->hyphenate(&result, word, NELEM(word), usLocale); + EXPECT_EQ((size_t) 3, result.size()); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[0]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[1]); + EXPECT_EQ(HyphenationType::BREAK_AND_INSERT_HYPHEN, result[2]); +} + +// Soft hyphens at the beginning of a word are not useful in linebreaking. +TEST_F(HyphenatorTest, latinSoftHyphenStartingTheWord) { + Hyphenator* hyphenator = Hyphenator::loadBinary(nullptr); + const uint16_t word[] = {SOFT_HYPHEN, 'y'}; + std::vector result; + hyphenator->hyphenate(&result, word, NELEM(word), usLocale); + EXPECT_EQ((size_t) 2, result.size()); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[0]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[1]); +} + +// In Malayalam script text, soft hyphens should not insert a visible hyphen if broken at. +TEST_F(HyphenatorTest, malayalamSoftHyphen) { + Hyphenator* hyphenator = Hyphenator::loadBinary(nullptr); + const uint16_t word[] = {MALAYALAM_KA, SOFT_HYPHEN, MALAYALAM_KA}; + std::vector result; + hyphenator->hyphenate(&result, word, NELEM(word), usLocale); + EXPECT_EQ((size_t) 3, result.size()); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[0]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[1]); + EXPECT_EQ(HyphenationType::BREAK_AND_DONT_INSERT_HYPHEN, result[2]); +} + +// In automatically hyphenated Malayalam script text, we should not insert a visible hyphen. +TEST_F(HyphenatorTest, malayalamAutomaticHyphenation) { + Hyphenator* hyphenator = Hyphenator::loadBinary(readWholeFile(malayalamHyph).data()); + const uint16_t word[] = { + MALAYALAM_KA, MALAYALAM_KA, MALAYALAM_KA, MALAYALAM_KA, MALAYALAM_KA}; + std::vector result; + hyphenator->hyphenate(&result, word, NELEM(word), usLocale); + EXPECT_EQ((size_t) 5, result.size()); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[0]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[1]); + EXPECT_EQ(HyphenationType::BREAK_AND_DONT_INSERT_HYPHEN, result[2]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[3]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[4]); +} + +// In Armenian script text, soft hyphens should insert an Armenian hyphen if broken at. +TEST_F(HyphenatorTest, aremenianSoftHyphen) { + Hyphenator* hyphenator = Hyphenator::loadBinary(nullptr); + const uint16_t word[] = {ARMENIAN_AYB, SOFT_HYPHEN, ARMENIAN_AYB}; + std::vector result; + hyphenator->hyphenate(&result, word, NELEM(word), usLocale); + EXPECT_EQ((size_t) 3, result.size()); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[0]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[1]); + EXPECT_EQ(HyphenationType::BREAK_AND_INSERT_ARMENIAN_HYPHEN, result[2]); +} + +// In Hebrew script text, soft hyphens should insert a normal hyphen if broken at, for now. +// We may need to change this to maqaf later. +TEST_F(HyphenatorTest, hebrewSoftHyphen) { + Hyphenator* hyphenator = Hyphenator::loadBinary(nullptr); + const uint16_t word[] = {HEBREW_ALEF, SOFT_HYPHEN, HEBREW_ALEF}; + std::vector result; + hyphenator->hyphenate(&result, word, NELEM(word), usLocale); + EXPECT_EQ((size_t) 3, result.size()); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[0]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[1]); + EXPECT_EQ(HyphenationType::BREAK_AND_INSERT_HYPHEN, result[2]); +} + +// Soft hyphen between two Arabic letters that join should keep the joining +// behavior when broken across lines. +TEST_F(HyphenatorTest, arabicSoftHyphenConnecting) { + Hyphenator* hyphenator = Hyphenator::loadBinary(nullptr); + const uint16_t word[] = {ARABIC_BEH, SOFT_HYPHEN, ARABIC_BEH}; + std::vector result; + hyphenator->hyphenate(&result, word, NELEM(word), usLocale); + EXPECT_EQ((size_t) 3, result.size()); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[0]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[1]); + EXPECT_EQ(HyphenationType::BREAK_AND_INSERT_HYPHEN_AND_ZWJ, result[2]); +} + +// Arabic letters may be joining on one side, but if it's the wrong side, we +// should use the normal hyphen. +TEST_F(HyphenatorTest, arabicSoftHyphenNonConnecting) { + Hyphenator* hyphenator = Hyphenator::loadBinary(nullptr); + const uint16_t word[] = {ARABIC_ALEF, SOFT_HYPHEN, ARABIC_BEH}; + std::vector result; + hyphenator->hyphenate(&result, word, NELEM(word), usLocale); + EXPECT_EQ((size_t) 3, result.size()); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[0]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[1]); + EXPECT_EQ(HyphenationType::BREAK_AND_INSERT_HYPHEN, result[2]); +} + +// Skip transparent characters until you find a non-transparent one. +TEST_F(HyphenatorTest, arabicSoftHyphenSkipTransparents) { + Hyphenator* hyphenator = Hyphenator::loadBinary(nullptr); + const uint16_t word[] = {ARABIC_BEH, ARABIC_ZWARAKAY, SOFT_HYPHEN, ARABIC_ZWARAKAY, ARABIC_BEH}; + std::vector result; + hyphenator->hyphenate(&result, word, NELEM(word), usLocale); + EXPECT_EQ((size_t) 5, result.size()); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[0]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[1]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[2]); + EXPECT_EQ(HyphenationType::BREAK_AND_INSERT_HYPHEN_AND_ZWJ, result[3]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[4]); +} + +// Skip transparent characters until you find a non-transparent one. If we get to one end without +// finding anything, we are still non-joining. +TEST_F(HyphenatorTest, arabicSoftHyphenTransparentsAtEnd) { + Hyphenator* hyphenator = Hyphenator::loadBinary(nullptr); + const uint16_t word[] = {ARABIC_BEH, ARABIC_ZWARAKAY, SOFT_HYPHEN, ARABIC_ZWARAKAY}; + std::vector result; + hyphenator->hyphenate(&result, word, NELEM(word), usLocale); + EXPECT_EQ((size_t) 4, result.size()); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[0]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[1]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[2]); + EXPECT_EQ(HyphenationType::BREAK_AND_INSERT_HYPHEN, result[3]); +} + +// Skip transparent characters until you find a non-transparent one. If we get to one end without +// finding anything, we are still non-joining. +TEST_F(HyphenatorTest, arabicSoftHyphenTransparentsAtStart) { + Hyphenator* hyphenator = Hyphenator::loadBinary(nullptr); + const uint16_t word[] = {ARABIC_ZWARAKAY, SOFT_HYPHEN, ARABIC_ZWARAKAY, ARABIC_BEH}; + std::vector result; + hyphenator->hyphenate(&result, word, NELEM(word), usLocale); + EXPECT_EQ((size_t) 4, result.size()); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[0]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[1]); + EXPECT_EQ(HyphenationType::BREAK_AND_INSERT_HYPHEN, result[2]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[3]); +} + +// In Unified Canadian Aboriginal script (UCAS) text, soft hyphens should insert a UCAS hyphen. +TEST_F(HyphenatorTest, ucasSoftHyphen) { + Hyphenator* hyphenator = Hyphenator::loadBinary(nullptr); + const uint16_t word[] = {UCAS_E, SOFT_HYPHEN, UCAS_E}; + std::vector result; + hyphenator->hyphenate(&result, word, NELEM(word), usLocale); + EXPECT_EQ((size_t) 3, result.size()); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[0]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[1]); + EXPECT_EQ(HyphenationType::BREAK_AND_INSERT_UCAS_HYPHEN, result[2]); +} + +// Presently, soft hyphen looks at the character after it to determine hyphenation type. This is a +// little arbitrary, but let's test it anyway. +TEST_F(HyphenatorTest, mixedScriptSoftHyphen) { + Hyphenator* hyphenator = Hyphenator::loadBinary(nullptr); + const uint16_t word[] = {'a', SOFT_HYPHEN, UCAS_E}; + std::vector result; + hyphenator->hyphenate(&result, word, NELEM(word), usLocale); + EXPECT_EQ((size_t) 3, result.size()); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[0]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[1]); + EXPECT_EQ(HyphenationType::BREAK_AND_INSERT_UCAS_HYPHEN, result[2]); +} + +// Hard hyphens provide a breaking opportunity with nothing extra inserted. +TEST_F(HyphenatorTest, hardHyphen) { + Hyphenator* hyphenator = Hyphenator::loadBinary(nullptr); + const uint16_t word[] = {'x', HYPHEN, 'y'}; + std::vector result; + hyphenator->hyphenate(&result, word, NELEM(word), usLocale); + EXPECT_EQ((size_t) 3, result.size()); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[0]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[1]); + EXPECT_EQ(HyphenationType::BREAK_AND_DONT_INSERT_HYPHEN, result[2]); +} + +// Hyphen-minuses also provide a breaking opportunity with nothing extra inserted. +TEST_F(HyphenatorTest, hyphenMinus) { + Hyphenator* hyphenator = Hyphenator::loadBinary(nullptr); + const uint16_t word[] = {'x', HYPHEN_MINUS, 'y'}; + std::vector result; + hyphenator->hyphenate(&result, word, NELEM(word), usLocale); + EXPECT_EQ((size_t) 3, result.size()); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[0]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[1]); + EXPECT_EQ(HyphenationType::BREAK_AND_DONT_INSERT_HYPHEN, result[2]); +} + +// If the word starts with a hard hyphen or hyphen-minus, it doesn't make sense to break +// it at that point. +TEST_F(HyphenatorTest, startingHyphenMinus) { + Hyphenator* hyphenator = Hyphenator::loadBinary(nullptr); + const uint16_t word[] = {HYPHEN_MINUS, 'y'}; + std::vector result; + hyphenator->hyphenate(&result, word, NELEM(word), usLocale); + EXPECT_EQ((size_t) 2, result.size()); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[0]); + EXPECT_EQ(HyphenationType::DONT_BREAK, result[1]); +} + +} // namespace minikin + diff --git a/engine/src/flutter/tests/unittest/LayoutTest.cpp b/engine/src/flutter/tests/unittest/LayoutTest.cpp index 4a849aa3eb..ed41ca4574 100644 --- a/engine/src/flutter/tests/unittest/LayoutTest.cpp +++ b/engine/src/flutter/tests/unittest/LayoutTest.cpp @@ -356,6 +356,53 @@ TEST_F(LayoutTest, doLayoutTest_rtlTest) { } } +TEST_F(LayoutTest, hyphenationTest) { + Layout layout(mCollection); + std::vector text; + + // The mock implementation returns 10.0f advance for all glyphs. + { + SCOPED_TRACE("one word with no hyphen edit"); + text = utf8ToUtf16("oneword"); + MinikinPaint paint; + paint.hyphenEdit = HyphenEdit::NO_EDIT; + layout.doLayout(text.data(), 0, text.size(), text.size(), kBidi_LTR, FontStyle(), paint); + EXPECT_EQ(70.0f, layout.getAdvance()); + } + { + SCOPED_TRACE("one word with hyphen insertion at the end"); + text = utf8ToUtf16("oneword"); + MinikinPaint paint; + paint.hyphenEdit = HyphenEdit::INSERT_HYPHEN_AT_END; + layout.doLayout(text.data(), 0, text.size(), text.size(), kBidi_LTR, FontStyle(), paint); + EXPECT_EQ(80.0f, layout.getAdvance()); + } + { + SCOPED_TRACE("one word with hyphen replacement at the end"); + text = utf8ToUtf16("oneword"); + MinikinPaint paint; + paint.hyphenEdit = HyphenEdit::REPLACE_WITH_HYPHEN_AT_END; + layout.doLayout(text.data(), 0, text.size(), text.size(), kBidi_LTR, FontStyle(), paint); + EXPECT_EQ(70.0f, layout.getAdvance()); + } + { + SCOPED_TRACE("one word with hyphen insertion at the start"); + text = utf8ToUtf16("oneword"); + MinikinPaint paint; + paint.hyphenEdit = HyphenEdit::INSERT_HYPHEN_AT_START; + layout.doLayout(text.data(), 0, text.size(), text.size(), kBidi_LTR, FontStyle(), paint); + EXPECT_EQ(80.0f, layout.getAdvance()); + } + { + SCOPED_TRACE("one word with hyphen insertion at the both ends"); + text = utf8ToUtf16("oneword"); + MinikinPaint paint; + paint.hyphenEdit = HyphenEdit::INSERT_HYPHEN_AT_START | HyphenEdit::INSERT_HYPHEN_AT_END; + layout.doLayout(text.data(), 0, text.size(), text.size(), kBidi_LTR, FontStyle(), paint); + EXPECT_EQ(90.0f, layout.getAdvance()); + } +} + // TODO: Add more test cases, e.g. measure text, letter spacing. } // namespace minikin diff --git a/engine/src/flutter/tests/unittest/WordBreakerTests.cpp b/engine/src/flutter/tests/unittest/WordBreakerTests.cpp index dc46c19d24..7971b49070 100644 --- a/engine/src/flutter/tests/unittest/WordBreakerTests.cpp +++ b/engine/src/flutter/tests/unittest/WordBreakerTests.cpp @@ -39,7 +39,7 @@ typedef ICUTestBase WordBreakerTest; TEST_F(WordBreakerTest, basic) { uint16_t buf[] = {'h', 'e', 'l', 'l' ,'o', ' ', 'w', 'o', 'r', 'l', 'd'}; WordBreaker breaker; - breaker.setLocale(icu::Locale::getEnglish()); + breaker.setLocale(icu::Locale::getUS()); breaker.setText(buf, NELEM(buf)); EXPECT_EQ(0, breaker.current()); EXPECT_EQ(6, breaker.next()); // after "hello " @@ -57,7 +57,7 @@ TEST_F(WordBreakerTest, basic) { TEST_F(WordBreakerTest, softHyphen) { uint16_t buf[] = {'h', 'e', 'l', 0x00AD, 'l' ,'o', ' ', 'w', 'o', 'r', 'l', 'd'}; WordBreaker breaker; - breaker.setLocale(icu::Locale::getEnglish()); + breaker.setLocale(icu::Locale::getUS()); breaker.setText(buf, NELEM(buf)); EXPECT_EQ(0, breaker.current()); EXPECT_EQ(7, breaker.next()); // after "hel{SOFT HYPHEN}lo " @@ -70,10 +70,23 @@ TEST_F(WordBreakerTest, softHyphen) { EXPECT_EQ(0, breaker.breakBadness()); } +TEST_F(WordBreakerTest, hardHyphen) { + // Hyphens should not allow breaks anymore. + uint16_t buf[] = {'s', 'u', 'g', 'a', 'r', '-', 'f', 'r', 'e', 'e'}; + WordBreaker breaker; + breaker.setLocale(icu::Locale::getUS()); + breaker.setText(buf, NELEM(buf)); + EXPECT_EQ(0, breaker.current()); + EXPECT_EQ((ssize_t)NELEM(buf), breaker.next()); + EXPECT_EQ(0, breaker.wordStart()); + EXPECT_EQ((ssize_t)NELEM(buf), breaker.wordEnd()); + EXPECT_EQ(0, breaker.breakBadness()); +} + TEST_F(WordBreakerTest, postfixAndPrefix) { uint16_t buf[] = {'U', 'S', 0x00A2, ' ', 'J', 'P', 0x00A5}; // US¢ JP¥ WordBreaker breaker; - breaker.setLocale(icu::Locale::getEnglish()); + breaker.setLocale(icu::Locale::getUS()); breaker.setText(buf, NELEM(buf)); EXPECT_EQ(0, breaker.current()); @@ -111,7 +124,7 @@ TEST_F(WordBreakerTest, zwjEmojiSequences) { UTF16(0x1F431), 0x200D, UTF16(0x1F464), }; WordBreaker breaker; - breaker.setLocale(icu::Locale::getEnglish()); + breaker.setLocale(icu::Locale::getUS()); breaker.setText(buf, NELEM(buf)); EXPECT_EQ(0, breaker.current()); EXPECT_EQ(7, breaker.next()); // after man + zwj + heart + zwj + man @@ -134,7 +147,7 @@ TEST_F(WordBreakerTest, emojiWithModifier) { 0x270C, 0xFE0F, UTF16(0x1F3FF) // victory hand + emoji style + type 6 fitzpatrick modifier }; WordBreaker breaker; - breaker.setLocale(icu::Locale::getEnglish()); + breaker.setLocale(icu::Locale::getUS()); breaker.setText(buf, NELEM(buf)); EXPECT_EQ(0, breaker.current()); EXPECT_EQ(4, breaker.next()); // after boy + type 1-2 fitzpatrick modifier @@ -157,7 +170,7 @@ TEST_F(WordBreakerTest, flagsSequenceSingleFlag) { ParseUnicode(buf, BUF_SIZE, flags.c_str(), &size, nullptr); WordBreaker breaker; - breaker.setLocale(icu::Locale::getEnglish()); + breaker.setLocale(icu::Locale::getUS()); breaker.setText(buf, size); EXPECT_EQ(0, breaker.current()); EXPECT_EQ(kFlagLength, breaker.next()); // end of the first flag @@ -182,7 +195,7 @@ TEST_F(WordBreakerTest, flagsSequence) { ParseUnicode(buf, BUF_SIZE, flagSequence.c_str(), &size, nullptr); WordBreaker breaker; - breaker.setLocale(icu::Locale::getEnglish()); + breaker.setLocale(icu::Locale::getUS()); breaker.setText(buf, size); EXPECT_EQ(0, breaker.current()); EXPECT_EQ(kFlagLength, breaker.next()); // end of the first flag sequence @@ -197,7 +210,7 @@ TEST_F(WordBreakerTest, punct) { uint16_t buf[] = {0x00A1, 0x00A1, 'h', 'e', 'l', 'l' ,'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!', '!'}; WordBreaker breaker; - breaker.setLocale(icu::Locale::getEnglish()); + breaker.setLocale(icu::Locale::getUS()); breaker.setText(buf, NELEM(buf)); EXPECT_EQ(0, breaker.current()); EXPECT_EQ(9, breaker.next()); // after "¡¡hello, " @@ -214,7 +227,7 @@ TEST_F(WordBreakerTest, email) { uint16_t buf[] = {'f', 'o', 'o', '@', 'e', 'x', 'a', 'm', 'p', 'l', 'e', '.', 'c', 'o', 'm', ' ', 'x'}; WordBreaker breaker; - breaker.setLocale(icu::Locale::getEnglish()); + breaker.setLocale(icu::Locale::getUS()); breaker.setText(buf, NELEM(buf)); EXPECT_EQ(0, breaker.current()); EXPECT_EQ(11, breaker.next()); // after "foo@example" @@ -233,7 +246,7 @@ TEST_F(WordBreakerTest, mailto) { uint16_t buf[] = {'m', 'a', 'i', 'l', 't', 'o', ':', 'f', 'o', 'o', '@', 'e', 'x', 'a', 'm', 'p', 'l', 'e', '.', 'c', 'o', 'm', ' ', 'x'}; WordBreaker breaker; - breaker.setLocale(icu::Locale::getEnglish()); + breaker.setLocale(icu::Locale::getUS()); breaker.setText(buf, NELEM(buf)); EXPECT_EQ(0, breaker.current()); EXPECT_EQ(7, breaker.next()); // after "mailto:" @@ -257,7 +270,7 @@ TEST_F(WordBreakerTest, emailNonAscii) { uint16_t buf[] = {'f', 'o', 'o', '@', 'e', 'x', 'a', 'm', 'p', 'l', 'e', '.', 'c', 'o', 'm', 0x4E00}; WordBreaker breaker; - breaker.setLocale(icu::Locale::getEnglish()); + breaker.setLocale(icu::Locale::getUS()); breaker.setText(buf, NELEM(buf)); EXPECT_EQ(0, breaker.current()); EXPECT_EQ(11, breaker.next()); // after "foo@example" @@ -276,7 +289,7 @@ TEST_F(WordBreakerTest, emailCombining) { uint16_t buf[] = {'f', 'o', 'o', '@', 'e', 'x', 'a', 'm', 'p', 'l', 'e', '.', 'c', 'o', 'm', 0x0303, ' ', 'x'}; WordBreaker breaker; - breaker.setLocale(icu::Locale::getEnglish()); + breaker.setLocale(icu::Locale::getUS()); breaker.setText(buf, NELEM(buf)); EXPECT_EQ(0, breaker.current()); EXPECT_EQ(11, breaker.next()); // after "foo@example" @@ -294,7 +307,7 @@ TEST_F(WordBreakerTest, emailCombining) { TEST_F(WordBreakerTest, lonelyAt) { uint16_t buf[] = {'a', ' ', '@', ' ', 'b'}; WordBreaker breaker; - breaker.setLocale(icu::Locale::getEnglish()); + breaker.setLocale(icu::Locale::getUS()); breaker.setText(buf, NELEM(buf)); EXPECT_EQ(0, breaker.current()); EXPECT_EQ(2, breaker.next()); // after "a " @@ -314,7 +327,7 @@ TEST_F(WordBreakerTest, url) { uint16_t buf[] = {'h', 't', 't', 'p', ':', '/', '/', 'e', 'x', 'a', 'm', 'p', 'l', 'e', '.', 'c', 'o', 'm', ' ', 'x'}; WordBreaker breaker; - breaker.setLocale(icu::Locale::getEnglish()); + breaker.setLocale(icu::Locale::getUS()); breaker.setText(buf, NELEM(buf)); EXPECT_EQ(0, breaker.current()); EXPECT_EQ(5, breaker.next()); // after "http:" @@ -340,7 +353,7 @@ TEST_F(WordBreakerTest, urlBreakChars) { uint16_t buf[] = {'h', 't', 't', 'p', ':', '/', '/', 'a', '.', 'b', '/', '~', 'c', ',', 'd', '-', 'e', '?', 'f', '=', 'g', '&', 'h', '#', 'i', '%', 'j', '_', 'k', '/', 'l'}; WordBreaker breaker; - breaker.setLocale(icu::Locale::getEnglish()); + breaker.setLocale(icu::Locale::getUS()); breaker.setText(buf, NELEM(buf)); EXPECT_EQ(0, breaker.current()); EXPECT_EQ(5, breaker.next()); // after "http:" @@ -399,7 +412,7 @@ TEST_F(WordBreakerTest, urlBreakChars) { TEST_F(WordBreakerTest, urlNoHyphenBreak) { uint16_t buf[] = {'h', 't', 't', 'p', ':', '/', '/', 'a', '-', '/', 'b'}; WordBreaker breaker; - breaker.setLocale(icu::Locale::getEnglish()); + breaker.setLocale(icu::Locale::getUS()); breaker.setText(buf, NELEM(buf)); EXPECT_EQ(0, breaker.current()); EXPECT_EQ(5, breaker.next()); // after "http:" @@ -415,7 +428,7 @@ TEST_F(WordBreakerTest, urlNoHyphenBreak) { TEST_F(WordBreakerTest, urlEndsWithSlash) { uint16_t buf[] = {'h', 't', 't', 'p', ':', '/', '/', 'a', '/'}; WordBreaker breaker; - breaker.setLocale(icu::Locale::getEnglish()); + breaker.setLocale(icu::Locale::getUS()); breaker.setText(buf, NELEM(buf)); EXPECT_EQ(0, breaker.current()); EXPECT_EQ(5, breaker.next()); // after "http:" @@ -431,7 +444,7 @@ TEST_F(WordBreakerTest, urlEndsWithSlash) { TEST_F(WordBreakerTest, emailStartsWithSlash) { uint16_t buf[] = {'/', 'a', '@', 'b'}; WordBreaker breaker; - breaker.setLocale(icu::Locale::getEnglish()); + breaker.setLocale(icu::Locale::getUS()); breaker.setText(buf, NELEM(buf)); EXPECT_EQ(0, breaker.current()); EXPECT_EQ((ssize_t)NELEM(buf), breaker.next()); // end