Chromium Code Reviews| Index: ui/gfx/render_text_harfbuzz.cc |
| diff --git a/ui/gfx/render_text_harfbuzz.cc b/ui/gfx/render_text_harfbuzz.cc |
| new file mode 100644 |
| index 0000000000000000000000000000000000000000..85dcc7ee59e9affb8052e8cc133d624a7ec1512e |
| --- /dev/null |
| +++ b/ui/gfx/render_text_harfbuzz.cc |
| @@ -0,0 +1,920 @@ |
| +// Copyright 2014 The Chromium Authors. All rights reserved. |
| +// Use of this source code is governed by a BSD-style license that can be |
| +// found in the LICENSE file. |
| + |
| +#include "ui/gfx/render_text_harfbuzz.h" |
| + |
| +#include <map> |
| + |
| +#include "base/i18n/break_iterator.h" |
| +#include "base/i18n/char_iterator.h" |
| +#include "third_party/harfbuzz-ng/src/hb-icu.h" |
| +#include "third_party/harfbuzz-ng/src/hb.h" |
| +#include "third_party/icu/source/common/unicode/ubidi.h" |
| +#include "third_party/skia/include/core/SkColor.h" |
| +#include "third_party/skia/include/core/SkTypeface.h" |
| +#include "ui/gfx/canvas.h" |
| +#include "ui/gfx/utf16_indexing.h" |
| + |
| +#if defined(OS_WIN) |
| +#include "ui/gfx/font_smoothing_win.h" |
| +#endif |
| + |
| +namespace gfx { |
| + |
| +namespace { |
| + |
| +// The maximum number of scripts a unicode character can belong to. |
| +const size_t kMaxScripts = 5; |
| + |
| +typedef std::map<uint32_t, uint16_t> GlyphCache; |
| + |
| +// Font data provider for HarfBuzz using Skia. Copied from Blink. |
| +// TODO(ckocagil): Eliminate the duplication. http://crbug.com/368375 |
| +struct FontData { |
| + FontData(GlyphCache* glyph_cache) : glyph_cache_(glyph_cache) {} |
| + |
| + SkPaint paint_; |
| + GlyphCache* glyph_cache_; |
| +}; |
| + |
| +hb_position_t SkiaScalarToHarfBuzzPosition(SkScalar value) { |
| + return SkScalarToFixed(value); |
| +} |
| + |
| +template<typename Type> |
| +void DeleteByType(void* data) { |
| + Type* typed_data = reinterpret_cast<Type*>(data); |
| + delete typed_data; |
| +} |
| + |
| +template<typename Type> |
| +void DeleteArrayByType(void* data) { |
| + Type* typed_data = reinterpret_cast<Type*>(data); |
| + delete[] typed_data; |
| +} |
| + |
| +void GetGlyphWidthAndExtents(SkPaint* paint, |
| + hb_codepoint_t codepoint, |
| + hb_position_t* width, |
| + hb_glyph_extents_t* extents) { |
| + CHECK_LE(codepoint, 0xFFFFU); |
|
Alexei Svitkine (slow)
2014/05/13 15:23:27
Does this need to be a CHECK rather than a DCHECK?
ckocagil
2014/05/16 13:47:25
This is actually supposed to be a DCHECK, I mistra
|
| + paint->setTextEncoding(SkPaint::kGlyphID_TextEncoding); |
| + |
| + SkScalar sk_width; |
| + SkRect sk_bounds; |
| + uint16_t glyph = codepoint; |
| + |
| + paint->getTextWidths(&glyph, sizeof(glyph), &sk_width, &sk_bounds); |
| + if (width) |
| + *width = SkiaScalarToHarfBuzzPosition(sk_width); |
| + if (extents) { |
| + // Invert y-axis because Skia is y-grows-down but we set up HarfBuzz to be |
| + // y-grows-up. |
| + extents->x_bearing = SkiaScalarToHarfBuzzPosition(sk_bounds.fLeft); |
| + extents->y_bearing = SkiaScalarToHarfBuzzPosition(-sk_bounds.fTop); |
| + extents->width = SkiaScalarToHarfBuzzPosition(sk_bounds.width()); |
| + extents->height = SkiaScalarToHarfBuzzPosition(-sk_bounds.height()); |
| + } |
| +} |
| + |
| +hb_bool_t GetGlyph(hb_font_t* font, |
| + void* data, |
| + hb_codepoint_t unicode, |
| + hb_codepoint_t variation_selector, |
| + hb_codepoint_t* glyph, |
| + void* user_data) { |
| + FontData* font_data = reinterpret_cast<FontData*>(data); |
| + GlyphCache* cache = font_data->glyph_cache_; |
| + |
| + bool exists = cache->count(unicode) != 0; |
| + if (!exists) { |
| + SkPaint* paint = &font_data->paint_; |
| + paint->setTextEncoding(SkPaint::kUTF32_TextEncoding); |
| + paint->textToGlyphs(&unicode, sizeof(hb_codepoint_t), &(*cache)[unicode]); |
| + } |
| + *glyph = (*cache)[unicode]; |
| + return !!*glyph; |
| +} |
| + |
| +hb_position_t GetGlyphHorizontalAdvance(hb_font_t* font, |
| + void* data, |
| + hb_codepoint_t glyph, |
| + void* user_data) { |
| + FontData* font_data = reinterpret_cast<FontData*>(data); |
| + hb_position_t advance = 0; |
| + |
| + GetGlyphWidthAndExtents(&font_data->paint_, glyph, &advance, 0); |
| + return advance; |
| +} |
| + |
| +hb_bool_t GetGlyphHorizontalOrigin(hb_font_t* font, |
| + void* data, |
| + hb_codepoint_t glyph, |
| + hb_position_t* x, |
| + hb_position_t* y, |
| + void* user_data) { |
| + // Just return true, like the HarfBuzz-FreeType implementation. |
| + return true; |
| +} |
| + |
| +hb_bool_t GetGlyphExtents(hb_font_t* font, |
| + void* data, |
| + hb_codepoint_t glyph, |
| + hb_glyph_extents_t* extents, |
| + void* user_data) { |
| + FontData* font_data = reinterpret_cast<FontData*>(data); |
| + |
| + GetGlyphWidthAndExtents(&font_data->paint_, glyph, 0, extents); |
| + return true; |
| +} |
| + |
| +hb_font_funcs_t* GetFontFuncs() { |
| + static hb_font_funcs_t* font_funcs = 0; |
| + |
| + // We don't set callback functions which we can't support. |
| + // HarfBuzz will use the fallback implementation if they aren't set. |
| + // TODO(ckocagil): Merge Blink's kerning funcs. |
| + if (!font_funcs) { |
| + font_funcs = hb_font_funcs_create(); |
|
Alexei Svitkine (slow)
2014/05/13 15:23:27
Is this intentionally leaked? If so, please add a
ckocagil
2014/05/16 13:47:25
Done.
|
| + hb_font_funcs_set_glyph_func(font_funcs, GetGlyph, 0, 0); |
| + hb_font_funcs_set_glyph_h_advance_func( |
| + font_funcs, GetGlyphHorizontalAdvance, 0, 0); |
| + hb_font_funcs_set_glyph_h_origin_func( |
| + font_funcs, GetGlyphHorizontalOrigin, 0, 0); |
| + hb_font_funcs_set_glyph_extents_func( |
| + font_funcs, GetGlyphExtents, 0, 0); |
| + hb_font_funcs_make_immutable(font_funcs); |
| + } |
| + return font_funcs; |
| +} |
| + |
| +hb_blob_t* GetFontTable(hb_face_t* face, hb_tag_t tag, void* user_data) { |
| + SkTypeface* typeface = reinterpret_cast<SkTypeface*>(user_data); |
| + |
| + const size_t table_size = typeface->getTableSize(tag); |
| + if (!table_size) |
| + return 0; |
| + |
| + char* buffer = new char[table_size]; |
|
Alexei Svitkine (slow)
2014/05/13 15:23:27
How about:
scoped_ptr<char[]> buffer(new char[tab
ckocagil
2014/05/16 13:47:25
Oh, good idea. Done! Sadly I had to assign the rel
|
| + if (!buffer) |
| + return 0; |
| + size_t actual_size = typeface->getTableData(tag, 0, table_size, buffer); |
| + if (table_size != actual_size) { |
| + delete[] buffer; |
| + return 0; |
| + } |
| + |
| + return hb_blob_create(buffer, table_size, HB_MEMORY_MODE_WRITABLE, buffer, |
| + DeleteArrayByType<char>); |
| +} |
| + |
| +void UnrefSkTypeface(void* data) { |
| + SkTypeface* skia_face = reinterpret_cast<SkTypeface*>(data); |
| + SkSafeUnref(skia_face); |
| +} |
| + |
| +hb_face_t* CreateHarfBuzzFace(SkTypeface* skia_face) { |
| + SkSafeRef(skia_face); |
| + hb_face_t* face = hb_face_create_for_tables(GetFontTable, skia_face, |
| + UnrefSkTypeface); |
| + CHECK(face); |
| + return face; |
| +} |
| + |
| +hb_font_t* CreateHarfBuzzFont(SkTypeface* skia_face, int text_size) { |
| + typedef std::pair<hb_face_t*, GlyphCache> FaceCache; |
| + |
| + // TODO(ckocagil): This shouldn't grow indefinitely. Maybe use base::MRUCache? |
| + static std::map<SkFontID, FaceCache> face_caches; |
| + |
| + FaceCache* face_cache = &face_caches[skia_face->uniqueID()]; |
| + if (face_cache->first == 0) { |
| + hb_face_t* harfbuzz_face = CreateHarfBuzzFace(skia_face); |
| + *face_cache = FaceCache(harfbuzz_face, GlyphCache()); |
| + } |
| + |
| + hb_font_t* harfbuzz_font = hb_font_create(face_cache->first); |
| + // TODO(ckocagil): Investigate whether disabling hinting here has any effect |
| + // on text quality. |
| + int upem = hb_face_get_upem(face_cache->first); |
| + hb_font_set_scale(harfbuzz_font, upem, upem); |
| + FontData* hb_font_data = new FontData(&face_cache->second); |
| + hb_font_data->paint_.setTypeface(skia_face); |
| + hb_font_data->paint_.setTextSize(text_size); |
| + hb_font_set_funcs(harfbuzz_font, GetFontFuncs(), hb_font_data, |
| + DeleteByType<FontData>); |
| + hb_font_make_immutable(harfbuzz_font); |
| + return harfbuzz_font; |
| +} |
| + |
| +size_t CharToGlyph(const internal::TextRunHarfBuzz& run, size_t pos) { |
|
Alexei Svitkine (slow)
2014/05/13 15:23:27
Can you add short 1-line comments for all these fu
ckocagil
2014/05/16 13:47:25
Done.
|
| + DCHECK(run.range.start() <= pos && pos < run.range.end()); |
| + |
| + if (run.direction == UBIDI_LTR) { |
| + for (size_t i = 0; i < run.glyph_count - 1; ++i) { |
| + if (pos < run.glyph_to_char[i + 1]) |
| + return i; |
| + } |
| + return run.glyph_count - 1; |
| + } |
| + |
| + for (size_t i = 0; i < run.glyph_count; ++i) { |
| + if (pos >= run.glyph_to_char[i]) |
| + return i; |
| + } |
| + NOTREACHED(); |
| + return 0; |
| +} |
| + |
| +// Returns the corresponding glyph range of the given character range. |
| +// |range| is in text-space (0 corresponds to |GetLayoutText()[0]|). |
| +// Returned value is in run-space (0 corresponds to the first glyph in the run). |
| +Range CharRangeToGlyphRange(const internal::TextRunHarfBuzz& run, |
| + const Range& range) { |
| + DCHECK(run.range.Contains(range)); |
| + DCHECK(!range.is_reversed()); |
| + DCHECK(!range.is_empty()); |
| + |
| + const size_t first = CharToGlyph(run, range.start()); |
| + const size_t last = CharToGlyph(run, range.end() - 1); |
| + return Range(std::min(first, last), std::max(first, last) + 1); |
| +} |
| + |
| +// Returns true if characters of |block_code| may trigger font fallback. |
| +bool IsUnusualBlockCode(const UBlockCode block_code) { |
| + return block_code == UBLOCK_GEOMETRIC_SHAPES || |
| + block_code == UBLOCK_MISCELLANEOUS_SYMBOLS; |
| +} |
| + |
| +bool HasMissingGlyphs(const internal::TextRunHarfBuzz& run) { |
|
Alexei Svitkine (slow)
2014/05/13 15:23:27
Can this be a method on TextRunHarfbuzz rather tha
ckocagil
2014/05/16 13:47:25
Good idea, but should we make it a proper class wi
Alexei Svitkine (slow)
2014/05/16 18:22:52
I think it's OK to have a struct with a few method
ckocagil
2014/05/20 18:35:10
Done, moved these to the struct.
|
| + static const int kMissingGlyphId = 0; |
| + for (size_t i = 0; i < run.glyph_count; ++i) { |
| + if (run.glyphs[i] == kMissingGlyphId) |
| + return true; |
| + } |
| + return false; |
| +} |
| + |
| +UScriptCode ScriptIntersect(UScriptCode first, UScriptCode second) { |
| + if (first == second || |
| + (second > USCRIPT_INVALID_CODE && second <= USCRIPT_INHERITED)) { |
| + return first; |
| + } |
| + if (first > USCRIPT_INVALID_CODE && first <= USCRIPT_INHERITED) |
| + return second; |
| + return USCRIPT_INVALID_CODE; |
| +} |
| + |
| +int GetScriptExtensions(UChar32 codepoint, UScriptCode* scripts) { |
| + UErrorCode icu_error = U_ZERO_ERROR; |
| + // ICU documentation incorrectly states that the result of |
| + // |uscript_getScriptExtensions| will contain the regular script property. |
| + // Call |uscript_getScript| to get the script property. |
| + scripts[0] = uscript_getScript(codepoint, &icu_error); |
| + if (U_FAILURE(icu_error)) |
| + return 0; |
| + int count = uscript_getScriptExtensions(codepoint, scripts + 1, |
| + kMaxScripts - 1, &icu_error); |
| + if (U_FAILURE(icu_error)) |
| + count = 0; |
| + return count + 1; |
| +} |
| + |
| +// Intersects the script extensions set of |codepoint| with |result| and writes |
| +// to |result|, reading and updating |result_size|. |
| +void ScriptSetIntersect(UChar32 codepoint, |
| + UScriptCode* result, |
| + size_t* result_size) { |
| + UScriptCode scripts[kMaxScripts] = { USCRIPT_INVALID_CODE }; |
| + int count = GetScriptExtensions(codepoint, scripts); |
| + |
| + UScriptCode* out = result; |
| + size_t out_size = 0; |
| + |
| + for (size_t i = 0; i < *result_size; ++i) { |
| + for (int j = 0; j < count; ++j) { |
| + UScriptCode intersection = ScriptIntersect(result[i], scripts[j]); |
| + if (intersection != USCRIPT_INVALID_CODE) { |
| + *out++ = intersection; |
| + ++out_size; |
| + break; |
| + } |
| + } |
| + } |
| + |
| + *result_size = out_size; |
| +} |
| + |
| +// Find the longest sequence of characters from 0 and up to |length| that |
| +// have at least one common UScriptCode value. Writes the common script value to |
| +// |script| and returns the length of the sequence. Takes the characters' script |
| +// extensions into account. http://www.unicode.org/reports/tr24/#ScriptX |
| +int ScriptInterval(const base::char16* text, |
|
Alexei Svitkine (slow)
2014/05/13 15:23:27
Can |text| be passed by const ref?
ckocagil
2014/05/16 13:47:25
Done.
|
| + size_t length, |
|
Alexei Svitkine (slow)
2014/05/13 15:23:27
Nit: Align params.
ckocagil
2014/05/16 13:47:25
Done.
|
| + UScriptCode* script) { |
| + DCHECK_GE(length, 0U); |
| + |
| + UScriptCode scripts[kMaxScripts] = { USCRIPT_INVALID_CODE }; |
| + |
| + base::i18n::UTF16CharIterator char_iterator(text, length); |
| + size_t scripts_size = GetScriptExtensions(char_iterator.get(), scripts); |
| + *script = scripts[0]; |
| + |
| + while (char_iterator.Advance()) { |
| + ScriptSetIntersect(char_iterator.get(), scripts, &scripts_size); |
| + if (scripts_size > 0U) |
| + *script = scripts[0]; |
| + else |
| + return char_iterator.array_pos(); |
| + } |
| + |
| + return length; |
| +} |
| + |
| +} // namespace |
| + |
| +namespace internal { |
| + |
| +TextRunHarfBuzz::TextRunHarfBuzz() |
| + : width(0), |
| + preceding_run_widths(0), |
| + direction(UBIDI_LTR), |
| + level(0), |
| + script(USCRIPT_INVALID_CODE), |
| + glyph_count(-1), |
| + font_size(0), |
| + font_style(0), |
| + strike(false), |
| + diagonal_strike(false), |
| + underline(false) {} |
| + |
| +TextRunHarfBuzz::~TextRunHarfBuzz() {} |
| + |
| +} // namespace internal |
| + |
| +RenderTextHarfBuzz::RenderTextHarfBuzz() |
| + : RenderText(), |
| + needs_layout_(false) {} |
| + |
| +RenderTextHarfBuzz::~RenderTextHarfBuzz() {} |
| + |
| +Size RenderTextHarfBuzz::GetStringSize() { |
| + EnsureLayout(); |
| + return Size(lines()[0].size.width(), font_list().GetHeight()); |
| +} |
| + |
| +SelectionModel RenderTextHarfBuzz::FindCursorPosition(const Point& point) { |
| + EnsureLayout(); |
| + |
| + int x = ToTextPoint(point).x(); |
| + int offset = 0; |
| + size_t run_index = GetRunContainingXCoord(x, &offset); |
| + if (run_index >= runs_.size()) |
| + return EdgeSelectionModel((x < 0) ? CURSOR_LEFT : CURSOR_RIGHT); |
| + const internal::TextRunHarfBuzz& run = *runs_[run_index]; |
| + |
| + for (size_t i = 0; i < run.glyph_count; ++i) { |
| + const SkScalar end = |
| + i + 1 == run.glyph_count ? run.width : run.positions[i + 1].x(); |
| + const SkScalar middle = (end + run.positions[i].x()) / 2; |
| + const bool is_rtl = run.direction == UBIDI_RTL; |
| + if (offset < middle) { |
| + return SelectionModel(LayoutIndexToTextIndex( |
| + run.glyph_to_char[i] + (is_rtl ? 1 : 0)), |
| + (is_rtl ? CURSOR_BACKWARD : CURSOR_FORWARD)); |
| + } |
| + if (offset < end) { |
| + return SelectionModel(LayoutIndexToTextIndex( |
| + run.glyph_to_char[i] + (is_rtl ? 0 : 1)), |
| + (is_rtl ? CURSOR_FORWARD : CURSOR_BACKWARD)); |
| + } |
| + } |
| + return EdgeSelectionModel(CURSOR_RIGHT); |
| +} |
| + |
| +std::vector<RenderText::FontSpan> RenderTextHarfBuzz::GetFontSpansForTesting() { |
| + NOTIMPLEMENTED(); |
| + return std::vector<RenderText::FontSpan>(); |
| +} |
| + |
| +int RenderTextHarfBuzz::GetLayoutTextBaseline() { |
| + EnsureLayout(); |
| + return lines()[0].baseline; |
| +} |
| + |
| +SelectionModel RenderTextHarfBuzz::AdjacentCharSelectionModel( |
| + const SelectionModel& selection, |
| + VisualCursorDirection direction) { |
| + DCHECK(!needs_layout_); |
| + internal::TextRunHarfBuzz* run; |
| + size_t run_index = GetRunContainingCaret(selection); |
| + if (run_index >= runs_.size()) { |
| + // The cursor is not in any run: we're at the visual and logical edge. |
| + SelectionModel edge = EdgeSelectionModel(direction); |
| + if (edge.caret_pos() == selection.caret_pos()) |
| + return edge; |
| + int visual_index = (direction == CURSOR_RIGHT) ? 0 : runs_.size() - 1; |
| + run = runs_[visual_to_logical_[visual_index]]; |
| + } else { |
| + // If the cursor is moving within the current run, just move it by one |
| + // grapheme in the appropriate direction. |
| + run = runs_[run_index]; |
| + size_t caret = selection.caret_pos(); |
| + bool forward_motion = |
| + (run->direction == UBIDI_RTL) == (direction == CURSOR_LEFT); |
| + if (forward_motion) { |
| + if (caret < LayoutIndexToTextIndex(run->range.end())) { |
| + caret = IndexOfAdjacentGrapheme(caret, CURSOR_FORWARD); |
| + return SelectionModel(caret, CURSOR_BACKWARD); |
| + } |
| + } else { |
| + if (caret > LayoutIndexToTextIndex(run->range.start())) { |
| + caret = IndexOfAdjacentGrapheme(caret, CURSOR_BACKWARD); |
| + return SelectionModel(caret, CURSOR_FORWARD); |
| + } |
| + } |
| + // The cursor is at the edge of a run; move to the visually adjacent run. |
| + int visual_index = logical_to_visual_[run_index]; |
| + visual_index += (direction == CURSOR_LEFT) ? -1 : 1; |
| + if (visual_index < 0 || visual_index >= static_cast<int>(runs_.size())) |
| + return EdgeSelectionModel(direction); |
| + run = runs_[visual_to_logical_[visual_index]]; |
| + } |
| + bool forward_motion = |
| + (run->direction == UBIDI_RTL) == (direction == CURSOR_LEFT); |
| + return forward_motion ? FirstSelectionModelInsideRun(run) : |
| + LastSelectionModelInsideRun(run); |
| +} |
| + |
| +SelectionModel RenderTextHarfBuzz::AdjacentWordSelectionModel( |
| + const SelectionModel& selection, |
| + VisualCursorDirection direction) { |
| + // TODO(ckocagil): This implementation currently matches RenderTextWin, but it |
| + // should match the native behavior on other platforms. |
| + if (obscured()) |
| + return EdgeSelectionModel(direction); |
| + |
| + base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD); |
| + bool success = iter.Init(); |
| + DCHECK(success); |
| + if (!success) |
| + return selection; |
| + |
| + size_t pos; |
| + if (direction == CURSOR_RIGHT) { |
| + pos = std::min(selection.caret_pos() + 1, text().length()); |
| + while (iter.Advance()) { |
| + pos = iter.pos(); |
| + if (iter.IsWord() && pos > selection.caret_pos()) |
| + break; |
| + } |
| + } else { // direction == CURSOR_LEFT |
| + // Notes: We always iterate words from the beginning. |
| + // This is probably fast enough for our usage, but we may |
| + // want to modify WordIterator so that it can start from the |
| + // middle of string and advance backwards. |
| + pos = std::max<int>(selection.caret_pos() - 1, 0); |
| + while (iter.Advance()) { |
| + if (iter.IsWord()) { |
| + size_t begin = iter.pos() - iter.GetString().length(); |
| + if (begin == selection.caret_pos()) { |
| + // The cursor is at the beginning of a word. |
| + // Move to previous word. |
| + break; |
| + } else if (iter.pos() >= selection.caret_pos()) { |
| + // The cursor is in the middle or at the end of a word. |
| + // Move to the top of current word. |
| + pos = begin; |
| + break; |
| + } |
| + pos = iter.pos() - iter.GetString().length(); |
| + } |
| + } |
| + } |
| + return SelectionModel(pos, CURSOR_FORWARD); |
| +} |
| + |
| +Range RenderTextHarfBuzz::GetGlyphBounds(size_t index) { |
| + const size_t run_index = |
| + GetRunContainingCaret(SelectionModel(index, CURSOR_FORWARD)); |
| + // Return edge bounds if the index is invalid or beyond the layout text size. |
| + if (run_index >= runs_.size()) |
| + return Range(GetStringSize().width()); |
| + const size_t layout_index = TextIndexToLayoutIndex(index); |
| + return Range(GetGlyphXBoundary(run_index, layout_index, false), |
| + GetGlyphXBoundary(run_index, layout_index, true)); |
| +} |
| + |
| +std::vector<Rect> RenderTextHarfBuzz::GetSubstringBounds(const Range& range) { |
| + DCHECK(!needs_layout_); |
| + DCHECK(Range(0, text().length()).Contains(range)); |
| + Range layout_range(TextIndexToLayoutIndex(range.start()), |
| + TextIndexToLayoutIndex(range.end())); |
| + DCHECK(Range(0, GetLayoutText().length()).Contains(layout_range)); |
| + |
| + std::vector<Rect> rects; |
| + if (layout_range.is_empty()) |
| + return rects; |
| + std::vector<Range> bounds; |
| + |
| + // Add a Range for each run/selection intersection. |
| + // TODO(msw): The bounds should probably not always be leading the range ends. |
| + for (size_t i = 0; i < runs_.size(); ++i) { |
| + const internal::TextRunHarfBuzz* run = runs_[visual_to_logical_[i]]; |
| + Range intersection = run->range.Intersect(layout_range); |
| + if (intersection.IsValid()) { |
| + DCHECK(!intersection.is_reversed()); |
| + Range range_x(GetGlyphXBoundary(i, intersection.start(), false), |
| + GetGlyphXBoundary(i, intersection.end(), false)); |
| + if (range_x.is_empty()) |
| + continue; |
| + range_x = Range(range_x.GetMin(), range_x.GetMax()); |
| + // Union this with the last range if they're adjacent. |
| + DCHECK(bounds.empty() || bounds.back().GetMax() <= range_x.GetMin()); |
| + if (!bounds.empty() && bounds.back().GetMax() == range_x.GetMin()) { |
| + range_x = Range(bounds.back().GetMin(), range_x.GetMax()); |
| + bounds.pop_back(); |
| + } |
| + bounds.push_back(range_x); |
| + } |
| + } |
| + for (size_t i = 0; i < bounds.size(); ++i) { |
| + std::vector<Rect> current_rects = TextBoundsToViewBounds(bounds[i]); |
| + rects.insert(rects.end(), current_rects.begin(), current_rects.end()); |
| + } |
| + return rects; |
| +} |
| + |
| +size_t RenderTextHarfBuzz::TextIndexToLayoutIndex(size_t index) const { |
| + DCHECK_LE(index, text().length()); |
| + ptrdiff_t i = obscured() ? UTF16IndexToOffset(text(), 0, index) : index; |
| + CHECK_GE(i, 0); |
| + // Clamp layout indices to the length of the text actually used for layout. |
| + return std::min<size_t>(GetLayoutText().length(), i); |
| +} |
| + |
| +size_t RenderTextHarfBuzz::LayoutIndexToTextIndex(size_t index) const { |
| + if (!obscured()) |
| + return index; |
| + |
| + DCHECK_LE(index, GetLayoutText().length()); |
| + const size_t text_index = UTF16OffsetToIndex(text(), 0, index); |
| + DCHECK_LE(text_index, text().length()); |
| + return text_index; |
| +} |
| + |
| +bool RenderTextHarfBuzz::IsValidCursorIndex(size_t index) { |
| + if (index == 0 || index == text().length()) |
| + return true; |
| + if (!IsValidLogicalIndex(index)) |
| + return false; |
| + EnsureLayout(); |
| + // Disallow indices amid multi-character graphemes by checking glyph bounds. |
| + // These characters are not surrogate-pairs, but may yield a single glyph: |
| + // \x0915\x093f - (ki) - one of many Devanagari biconsonantal conjuncts. |
| + // \x0e08\x0e33 - (cho chan + sara am) - a Thai consonant and vowel pair. |
| + return GetGlyphBounds(index) != GetGlyphBounds(index - 1); |
| +} |
| + |
| +void RenderTextHarfBuzz::ResetLayout() { |
| + needs_layout_ = true; |
| +} |
| + |
| +void RenderTextHarfBuzz::EnsureLayout() { |
| + if (needs_layout_) { |
| + runs_.clear(); |
| + |
| + if (!GetLayoutText().empty()) { |
| + ItemizeText(); |
| + |
| + for (size_t i = 0; i < runs_.size(); ++i) |
| + ShapeRun(runs_[i]); |
| + |
| + // Precalculate run width information. |
| + size_t preceding_run_widths = 0; |
| + for (size_t i = 0; i < runs_.size(); ++i) { |
| + internal::TextRunHarfBuzz* run = runs_[visual_to_logical_[i]]; |
| + run->preceding_run_widths = preceding_run_widths; |
| + preceding_run_widths += run->width; |
| + } |
| + } |
| + |
| + needs_layout_ = false; |
| + std::vector<internal::Line> empty_lines; |
| + set_lines(&empty_lines); |
| + } |
| + |
| + if (lines().empty()) { |
| + std::vector<internal::Line> lines; |
| + lines.push_back(internal::Line()); |
| + |
| + int current_x = 0; |
| + SkPaint paint; |
| + |
| + for (size_t i = 0; i < runs_.size(); ++i) { |
| + const internal::TextRunHarfBuzz& run = *runs_[visual_to_logical_[i]]; |
| + internal::LineSegment segment; |
| + segment.x_range = Range(current_x, current_x + run.width); |
| + segment.char_range = run.range; |
| + segment.run = i; |
| + lines[0].segments.push_back(segment); |
| + |
| + paint.setTypeface(run.skia_face.get()); |
| + paint.setTextSize(run.font_size); |
| + SkPaint::FontMetrics metrics; |
| + paint.getFontMetrics(&metrics); |
| + |
| + lines[0].size.set_width(lines[0].size.width() + run.width); |
| + lines[0].size.set_height(std::max(lines[0].size.height(), |
| + SkScalarRoundToInt(metrics.fDescent - metrics.fAscent))); |
| + lines[0].baseline = std::max(lines[0].baseline, |
| + SkScalarRoundToInt(-metrics.fAscent)); |
| + } |
| + |
| + set_lines(&lines); |
| + } |
| +} |
| + |
| +void RenderTextHarfBuzz::DrawVisualText(Canvas* canvas) { |
| + DCHECK(!needs_layout_); |
| + |
| + int current_x = 0; |
| + |
| + internal::SkiaTextRenderer renderer(canvas); |
| + ApplyFadeEffects(&renderer); |
| + ApplyTextShadows(&renderer); |
| + |
| +#if defined(OS_WIN) |
| + bool smoothing_enabled; |
| + bool cleartype_enabled; |
| + GetCachedFontSmoothingSettings(&smoothing_enabled, &cleartype_enabled); |
| + // Note that |cleartype_enabled| corresponds to Skia's |enable_lcd_text|. |
| + renderer.SetFontSmoothingSettings( |
| + smoothing_enabled, cleartype_enabled && !background_is_transparent(), |
| + smoothing_enabled /* subpixel_positioning */); |
| +#endif |
| + |
| + ApplyCompositionAndSelectionStyles(); |
| + |
| + const Vector2d line_offset = GetLineOffset(0); |
| + |
| + for (size_t i = 0; i < runs_.size(); ++i) { |
| + const internal::TextRunHarfBuzz& run = *runs_[visual_to_logical_[i]]; |
| + renderer.SetTypeface(run.skia_face.get()); |
| + renderer.SetTextSize(run.font_size); |
| + |
| + canvas->Save(); |
| + Vector2d origin = line_offset + Vector2d(current_x, lines()[0].baseline); |
| + canvas->Translate(origin); |
| + |
| + for (BreakList<SkColor>::const_iterator it = |
| + colors().GetBreak(run.range.start()); |
| + it != colors().breaks().end() && it->first < run.range.end(); |
| + ++it) { |
| + const Range intersection = colors().GetRange(it).Intersect(run.range); |
| + const Range colored_glyphs = CharRangeToGlyphRange(run, intersection); |
| + // The range may be empty if a portion of a multi-character grapheme is |
| + // selected, yielding two colors for a single glyph. For now, this just |
| + // paints the glyph with a single style, but it should paint it twice, |
| + // clipped according to selection bounds. See http://crbug.com/366786 |
| + if (colored_glyphs.is_empty()) |
| + continue; |
| + |
| + renderer.SetForegroundColor(it->second); |
| + renderer.DrawPosText(&run.positions[colored_glyphs.start()], |
| + &run.glyphs[colored_glyphs.start()], |
| + colored_glyphs.length()); |
| + int width = (colored_glyphs.end() == run.glyph_count ? run.width : |
| + run.positions[colored_glyphs.end()].x()) - |
| + run.positions[colored_glyphs.start()].x(); |
| + renderer.DrawDecorations(0, 0, width, run.underline, run.strike, |
| + run.diagonal_strike); |
| + } |
| + |
| + canvas->Restore(); |
| + current_x += run.width; |
| + } |
| + |
| + renderer.EndDiagonalStrike(); |
| + |
| + UndoCompositionAndSelectionStyles(); |
| +} |
| + |
| +size_t RenderTextHarfBuzz::GetRunContainingCaret( |
| + const SelectionModel& caret) const { |
| + DCHECK(!needs_layout_); |
| + size_t layout_position = TextIndexToLayoutIndex(caret.caret_pos()); |
| + LogicalCursorDirection affinity = caret.caret_affinity(); |
| + for (size_t run = 0; run < runs_.size(); ++run) { |
| + if (RangeContainsCaret(runs_[run]->range, layout_position, affinity)) |
| + return run; |
| + } |
| + return runs_.size(); |
| +} |
| + |
| +size_t RenderTextHarfBuzz::GetRunContainingXCoord(int x, int* offset) const { |
| + DCHECK(!needs_layout_); |
| + if (x < 0) |
| + return runs_.size(); |
| + // Find the text run containing the argument point (assumed already offset). |
| + int current_x = 0; |
| + for (size_t i = 0; i < runs_.size(); ++i) { |
| + size_t run = visual_to_logical_[i]; |
| + current_x += runs_[run]->width; |
| + if (x < current_x) { |
| + *offset = x - (current_x - runs_[run]->width); |
| + return run; |
| + } |
| + } |
| + return runs_.size(); |
| +} |
| + |
| +int RenderTextHarfBuzz::GetGlyphXBoundary(size_t run_index, |
| + size_t text_index, |
| + bool trailing) { |
| + const internal::TextRunHarfBuzz& run = *runs_[run_index]; |
| + int x = run.preceding_run_widths; |
| + |
| + Range glyph_range; |
| + if (text_index == run.range.end()) { |
| + trailing = true; |
| + glyph_range = run.direction == UBIDI_LTR ? |
| + Range(run.glyph_count - 1, run.glyph_count) : Range(0, 1); |
| + } else { |
| + glyph_range = CharRangeToGlyphRange(run, Range(text_index, text_index + 1)); |
| + } |
| + const int trailing_step = trailing ? 1 : 0; |
| + const size_t glyph_pos = glyph_range.start() + |
| + (run.direction == UBIDI_LTR ? trailing_step : (1 - trailing_step)); |
| + x += glyph_pos < run.glyph_count ? |
| + SkScalarRoundToInt(run.positions[glyph_pos].x()) : run.width; |
| + return x; |
| +} |
| + |
| +SelectionModel RenderTextHarfBuzz::FirstSelectionModelInsideRun( |
| + const internal::TextRunHarfBuzz* run) { |
| + size_t position = LayoutIndexToTextIndex(run->range.start()); |
| + position = IndexOfAdjacentGrapheme(position, CURSOR_FORWARD); |
| + return SelectionModel(position, CURSOR_BACKWARD); |
| +} |
| + |
| +SelectionModel RenderTextHarfBuzz::LastSelectionModelInsideRun( |
| + const internal::TextRunHarfBuzz* run) { |
| + size_t position = LayoutIndexToTextIndex(run->range.end()); |
| + position = IndexOfAdjacentGrapheme(position, CURSOR_BACKWARD); |
| + return SelectionModel(position, CURSOR_FORWARD); |
| +} |
| + |
| +void RenderTextHarfBuzz::ItemizeText() { |
| + const base::string16& text = GetLayoutText(); |
| + const bool is_rtl = GetTextDirection() == base::i18n::RIGHT_TO_LEFT; |
| + DCHECK_NE(0U, text.length()); |
| + |
| + bool fake_runs = false; |
| + UErrorCode result = U_ZERO_ERROR; |
| + |
| + UBiDi* line = ubidi_openSized(text.length(), 0, &result); |
| + if (U_FAILURE(result)) { |
| + NOTREACHED(); |
| + fake_runs = true; |
| + } else { |
| + ubidi_setPara(line, text.c_str(), text.length(), |
| + is_rtl ? UBIDI_DEFAULT_RTL : UBIDI_DEFAULT_LTR, NULL, |
| + &result); |
| + if (U_FAILURE(result)) { |
| + NOTREACHED(); |
| + fake_runs = true; |
| + } |
| + } |
| + |
| + // Temporarily apply composition underlines and selection colors. |
| + ApplyCompositionAndSelectionStyles(); |
| + |
| + // Build the list of runs from the script items and ranged styles. Use an |
| + // empty color BreakList to avoid breaking runs at color boundaries. |
| + BreakList<SkColor> empty_colors; |
| + empty_colors.SetMax(text.length()); |
| + internal::StyleIterator style(empty_colors, styles()); |
| + |
| + for (size_t run_break = 0; run_break < text.length();) { |
| + internal::TextRunHarfBuzz* run = new internal::TextRunHarfBuzz; |
| + run->range.set_start(run_break); |
| + run->font_style = (style.style(BOLD) ? Font::BOLD : 0) | |
| + (style.style(ITALIC) ? Font::ITALIC : 0); |
| + run->strike = style.style(STRIKE); |
| + run->diagonal_strike = style.style(DIAGONAL_STRIKE); |
| + run->underline = style.style(UNDERLINE); |
| + |
| + if (fake_runs) { |
| + run_break = text.length(); |
| + } else { |
| + int32 script_item_break = 0; |
| + ubidi_getLogicalRun(line, run_break, &script_item_break, &run->level); |
| + // Find the length and script of this script run. |
| + script_item_break = ScriptInterval(text.c_str() + run_break, |
| + script_item_break - run_break, &run->script) + run_break; |
| + |
| + // Find the next break and advance the iterators as needed. |
| + run_break = std::min(static_cast<size_t>(script_item_break), |
| + TextIndexToLayoutIndex(style.GetRange().end())); |
| + |
| + // Break runs adjacent to character substrings in certain code blocks. |
| + // This avoids using their fallback fonts for more characters than needed, |
| + // in cases like "\x25B6 Media Title", etc. http://crbug.com/278913 |
| + if (run_break > run->range.start()) { |
| + const size_t run_start = run->range.start(); |
| + const int32 run_length = static_cast<int32>(run_break - run_start); |
| + base::i18n::UTF16CharIterator iter(text.c_str() + run_start, |
| + run_length); |
| + const UBlockCode first_block_code = ublock_getCode(iter.get()); |
| + const bool first_block_unusual = IsUnusualBlockCode(first_block_code); |
| + while (iter.Advance() && iter.array_pos() < run_length) { |
| + const UBlockCode current_block_code = ublock_getCode(iter.get()); |
| + if (current_block_code != first_block_code && |
| + (first_block_unusual || IsUnusualBlockCode(current_block_code))) { |
| + run_break = run_start + iter.array_pos(); |
| + break; |
| + } |
| + } |
| + } |
| + } |
| + |
| + DCHECK(IsValidCodePointIndex(text, run_break)); |
| + style.UpdatePosition(LayoutIndexToTextIndex(run_break)); |
| + run->range.set_end(run_break); |
| + const UChar* uchar_start = ubidi_getText(line); |
| + // TODO(ckocagil): Add |ubidi_getBaseDirection| to i18n::BiDiLineIterator |
| + // and remove the bare ICU use here. |
| + run->direction = ubidi_getBaseDirection(uchar_start + run->range.start(), |
| + run->range.length()); |
| + if (run->direction == UBIDI_NEUTRAL) |
| + run->direction = is_rtl ? UBIDI_RTL : UBIDI_LTR; |
| + runs_.push_back(run); |
| + } |
| + |
| + ubidi_close(line); |
| + |
| + // Undo the temporarily applied composition underlines and selection colors. |
| + UndoCompositionAndSelectionStyles(); |
| + |
| + const size_t num_runs = runs_.size(); |
| + scoped_ptr<UBiDiLevel[]> levels(new UBiDiLevel[num_runs]); |
| + for (size_t i = 0; i < num_runs; ++i) |
| + levels[i] = runs_[i]->level; |
| + visual_to_logical_.resize(num_runs); |
| + ubidi_reorderVisual(levels.get(), num_runs, &visual_to_logical_[0]); |
| + logical_to_visual_.resize(num_runs); |
| + ubidi_reorderLogical(levels.get(), num_runs, &logical_to_visual_[0]); |
| +} |
| + |
| +void RenderTextHarfBuzz::ShapeRun(internal::TextRunHarfBuzz* run) { |
| + const base::string16& text = GetLayoutText(); |
| + // TODO(ckocagil|yukishiino): Implement font fallback. |
| + const Font& primary_font = font_list().GetPrimaryFont(); |
| + run->skia_face = internal::CreateSkiaTypeface(primary_font.GetFontName(), |
| + run->font_style); |
| + run->font_size = primary_font.GetFontSize(); |
| + |
| + hb_font_t* harfbuzz_font = CreateHarfBuzzFont(run->skia_face.get(), |
| + run->font_size); |
| + |
| + // Create a HarfBuzz buffer and add the string to be shaped. The HarfBuzz |
| + // buffer holds our text, run information to be used by the shaping engine, |
| + // and the resulting glyph data. |
| + hb_buffer_t* buffer = hb_buffer_create(); |
| + hb_buffer_add_utf16(buffer, reinterpret_cast<const uint16*>(text.c_str()), |
| + text.length(), run->range.start(), run->range.length()); |
| + hb_buffer_set_script(buffer, hb_icu_script_to_script(run->script)); |
| + hb_buffer_set_direction(buffer, |
| + run->direction == UBIDI_LTR ? HB_DIRECTION_LTR : HB_DIRECTION_RTL); |
| + // TODO(ckocagil): Should we determine the actual language? |
| + hb_buffer_set_language(buffer, hb_language_get_default()); |
| + |
| + // Shape the text. |
| + hb_shape(harfbuzz_font, buffer, NULL, 0); |
| + |
| + // Populate the run fields with the resulting glyph data in the buffer. |
| + hb_glyph_info_t* infos = hb_buffer_get_glyph_infos(buffer, &run->glyph_count); |
| + hb_glyph_position_t* hb_positions = hb_buffer_get_glyph_positions(buffer, |
| + NULL); |
| + run->glyphs.reset(new uint16[run->glyph_count]); |
| + run->glyph_to_char.reset(new uint32[run->glyph_count]); |
| + run->positions.reset(new SkPoint[run->glyph_count]); |
| + for (size_t i = 0; i < run->glyph_count; ++i) { |
| + run->glyphs[i] = infos[i].codepoint; |
| + run->glyph_to_char[i] = infos[i].cluster; |
| + const int x_offset = |
| + SkScalarRoundToInt(SkFixedToScalar(hb_positions[i].x_offset)); |
| + const int y_offset = |
| + SkScalarRoundToInt(SkFixedToScalar(hb_positions[i].y_offset)); |
| + run->positions[i].set(run->width + x_offset, y_offset); |
| + run->width += |
| + SkScalarRoundToInt(SkFixedToScalar(hb_positions[i].x_advance)); |
| + } |
| + |
| + hb_buffer_destroy(buffer); |
| + hb_font_destroy(harfbuzz_font); |
| +} |
| + |
| +} // namespace gfx |