Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(344)

Side by Side Diff: ui/gfx/render_text_harfbuzz.cc

Issue 152473008: More or less implement RenderTextHarfBuzz (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: actual android fix Created 6 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « ui/gfx/render_text_harfbuzz.h ('k') | ui/gfx/render_text_mac.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "ui/gfx/render_text_harfbuzz.h"
6
7 #include <map>
8
9 #include "base/i18n/break_iterator.h"
10 #include "base/i18n/char_iterator.h"
11 #include "third_party/harfbuzz-ng/src/hb-icu.h"
12 #include "third_party/harfbuzz-ng/src/hb.h"
13 #include "third_party/icu/source/common/unicode/ubidi.h"
14 #include "third_party/skia/include/core/SkColor.h"
15 #include "third_party/skia/include/core/SkTypeface.h"
16 #include "ui/gfx/canvas.h"
17 #include "ui/gfx/utf16_indexing.h"
18
19 #if defined(OS_WIN)
20 #include "ui/gfx/font_smoothing_win.h"
21 #endif
22
23 namespace gfx {
24
25 namespace {
26
27 // The maximum number of scripts a Unicode character can belong to. This value
28 // is arbitrarily chosen to be a good limit because it is unlikely for a single
29 // character to belong to more scripts.
30 const size_t kMaxScripts = 5;
31
32 // Maps from code points to glyph indices in a font.
33 typedef std::map<uint32_t, uint16_t> GlyphCache;
34
35 // Font data provider for HarfBuzz using Skia. Copied from Blink.
36 // TODO(ckocagil): Eliminate the duplication. http://crbug.com/368375
37 struct FontData {
38 FontData(GlyphCache* glyph_cache) : glyph_cache_(glyph_cache) {}
39
40 SkPaint paint_;
41 GlyphCache* glyph_cache_;
42 };
43
44 hb_position_t SkiaScalarToHarfBuzzPosition(SkScalar value) {
45 return SkScalarToFixed(value);
46 }
47
48 // Deletes the object at the given pointer after casting it to the given type.
49 template<typename Type>
50 void DeleteByType(void* data) {
51 Type* typed_data = reinterpret_cast<Type*>(data);
52 delete typed_data;
53 }
54
55 template<typename Type>
56 void DeleteArrayByType(void* data) {
57 Type* typed_data = reinterpret_cast<Type*>(data);
58 delete[] typed_data;
59 }
60
61 // Outputs the |width| and |extents| of the glyph with index |codepoint| in
62 // |paint|'s font.
63 void GetGlyphWidthAndExtents(SkPaint* paint,
64 hb_codepoint_t codepoint,
65 hb_position_t* width,
66 hb_glyph_extents_t* extents) {
67 DCHECK_LE(codepoint, 0xFFFFU);
68 paint->setTextEncoding(SkPaint::kGlyphID_TextEncoding);
69
70 SkScalar sk_width;
71 SkRect sk_bounds;
72 uint16_t glyph = codepoint;
73
74 paint->getTextWidths(&glyph, sizeof(glyph), &sk_width, &sk_bounds);
75 if (width)
76 *width = SkiaScalarToHarfBuzzPosition(sk_width);
77 if (extents) {
78 // Invert y-axis because Skia is y-grows-down but we set up HarfBuzz to be
79 // y-grows-up.
80 extents->x_bearing = SkiaScalarToHarfBuzzPosition(sk_bounds.fLeft);
81 extents->y_bearing = SkiaScalarToHarfBuzzPosition(-sk_bounds.fTop);
82 extents->width = SkiaScalarToHarfBuzzPosition(sk_bounds.width());
83 extents->height = SkiaScalarToHarfBuzzPosition(-sk_bounds.height());
84 }
85 }
86
87 // Writes the |glyph| index for the given |unicode| code point. Returns whether
88 // the glyph exists, i.e. it is not a missing glyph.
89 hb_bool_t GetGlyph(hb_font_t* font,
90 void* data,
91 hb_codepoint_t unicode,
92 hb_codepoint_t variation_selector,
93 hb_codepoint_t* glyph,
94 void* user_data) {
95 FontData* font_data = reinterpret_cast<FontData*>(data);
96 GlyphCache* cache = font_data->glyph_cache_;
97
98 bool exists = cache->count(unicode) != 0;
99 if (!exists) {
100 SkPaint* paint = &font_data->paint_;
101 paint->setTextEncoding(SkPaint::kUTF32_TextEncoding);
102 paint->textToGlyphs(&unicode, sizeof(hb_codepoint_t), &(*cache)[unicode]);
103 }
104 *glyph = (*cache)[unicode];
105 return !!*glyph;
106 }
107
108 // Returns the horizontal advance value of the |glyph|.
109 hb_position_t GetGlyphHorizontalAdvance(hb_font_t* font,
110 void* data,
111 hb_codepoint_t glyph,
112 void* user_data) {
113 FontData* font_data = reinterpret_cast<FontData*>(data);
114 hb_position_t advance = 0;
115
116 GetGlyphWidthAndExtents(&font_data->paint_, glyph, &advance, 0);
117 return advance;
118 }
119
120 hb_bool_t GetGlyphHorizontalOrigin(hb_font_t* font,
121 void* data,
122 hb_codepoint_t glyph,
123 hb_position_t* x,
124 hb_position_t* y,
125 void* user_data) {
126 // Just return true, like the HarfBuzz-FreeType implementation.
127 return true;
128 }
129
130 // Writes the |extents| of |glyph|.
131 hb_bool_t GetGlyphExtents(hb_font_t* font,
132 void* data,
133 hb_codepoint_t glyph,
134 hb_glyph_extents_t* extents,
135 void* user_data) {
136 FontData* font_data = reinterpret_cast<FontData*>(data);
137
138 GetGlyphWidthAndExtents(&font_data->paint_, glyph, 0, extents);
139 return true;
140 }
141
142 // Returns a HarfBuzz font data provider that uses Skia.
143 hb_font_funcs_t* GetFontFuncs() {
144 static hb_font_funcs_t* font_funcs = 0;
145
146 // We don't set callback functions which we can't support.
147 // HarfBuzz will use the fallback implementation if they aren't set.
148 // TODO(ckocagil): Merge Blink's kerning funcs.
149 if (!font_funcs) {
150 // The object created by |hb_font_funcs_create()| below lives indefinitely
151 // and is intentionally leaked.
152 font_funcs = hb_font_funcs_create();
153 hb_font_funcs_set_glyph_func(font_funcs, GetGlyph, 0, 0);
154 hb_font_funcs_set_glyph_h_advance_func(
155 font_funcs, GetGlyphHorizontalAdvance, 0, 0);
156 hb_font_funcs_set_glyph_h_origin_func(
157 font_funcs, GetGlyphHorizontalOrigin, 0, 0);
158 hb_font_funcs_set_glyph_extents_func(
159 font_funcs, GetGlyphExtents, 0, 0);
160 hb_font_funcs_make_immutable(font_funcs);
161 }
162 return font_funcs;
163 }
164
165 // Returns the raw data of the font table |tag|.
166 hb_blob_t* GetFontTable(hb_face_t* face, hb_tag_t tag, void* user_data) {
167 SkTypeface* typeface = reinterpret_cast<SkTypeface*>(user_data);
168
169 const size_t table_size = typeface->getTableSize(tag);
170 if (!table_size)
171 return 0;
172
173 scoped_ptr<char[]> buffer(new char[table_size]);
174 if (!buffer)
175 return 0;
176 size_t actual_size = typeface->getTableData(tag, 0, table_size, buffer.get());
177 if (table_size != actual_size)
178 return 0;
179
180 char* buffer_raw = buffer.release();
181 return hb_blob_create(buffer_raw, table_size, HB_MEMORY_MODE_WRITABLE,
182 buffer_raw, DeleteArrayByType<char>);
183 }
184
185 void UnrefSkTypeface(void* data) {
186 SkTypeface* skia_face = reinterpret_cast<SkTypeface*>(data);
187 SkSafeUnref(skia_face);
188 }
189
190 // Creates a HarfBuzz face from the given Skia face.
191 hb_face_t* CreateHarfBuzzFace(SkTypeface* skia_face) {
192 SkSafeRef(skia_face);
193 hb_face_t* face = hb_face_create_for_tables(GetFontTable, skia_face,
194 UnrefSkTypeface);
195 DCHECK(face);
196 return face;
197 }
198
199 // Creates a HarfBuzz font from the given Skia face and text size.
200 hb_font_t* CreateHarfBuzzFont(SkTypeface* skia_face, int text_size) {
201 typedef std::pair<hb_face_t*, GlyphCache> FaceCache;
202
203 // TODO(ckocagil): This shouldn't grow indefinitely. Maybe use base::MRUCache?
204 static std::map<SkFontID, FaceCache> face_caches;
205
206 FaceCache* face_cache = &face_caches[skia_face->uniqueID()];
207 if (face_cache->first == 0) {
208 hb_face_t* harfbuzz_face = CreateHarfBuzzFace(skia_face);
209 *face_cache = FaceCache(harfbuzz_face, GlyphCache());
210 }
211
212 hb_font_t* harfbuzz_font = hb_font_create(face_cache->first);
213 // TODO(ckocagil): Investigate whether disabling hinting here has any effect
214 // on text quality.
215 int upem = hb_face_get_upem(face_cache->first);
216 hb_font_set_scale(harfbuzz_font, upem, upem);
217 FontData* hb_font_data = new FontData(&face_cache->second);
218 hb_font_data->paint_.setTypeface(skia_face);
219 hb_font_data->paint_.setTextSize(text_size);
220 hb_font_set_funcs(harfbuzz_font, GetFontFuncs(), hb_font_data,
221 DeleteByType<FontData>);
222 hb_font_make_immutable(harfbuzz_font);
223 return harfbuzz_font;
224 }
225
226 // Returns true if characters of |block_code| may trigger font fallback.
227 bool IsUnusualBlockCode(UBlockCode block_code) {
228 return block_code == UBLOCK_GEOMETRIC_SHAPES ||
229 block_code == UBLOCK_MISCELLANEOUS_SYMBOLS;
230 }
231
232 // If the given scripts match, returns the one that isn't USCRIPT_COMMON or
233 // USCRIPT_INHERITED, i.e. the more specific one. Otherwise returns
234 // USCRIPT_INVALID_CODE.
235 UScriptCode ScriptIntersect(UScriptCode first, UScriptCode second) {
236 if (first == second ||
237 (second > USCRIPT_INVALID_CODE && second <= USCRIPT_INHERITED)) {
238 return first;
239 }
240 if (first > USCRIPT_INVALID_CODE && first <= USCRIPT_INHERITED)
241 return second;
242 return USCRIPT_INVALID_CODE;
243 }
244
245 // Writes the script and the script extensions of the character with the
246 // Unicode |codepoint|. Returns the number of written scripts.
247 int GetScriptExtensions(UChar32 codepoint, UScriptCode* scripts) {
248 UErrorCode icu_error = U_ZERO_ERROR;
249 // ICU documentation incorrectly states that the result of
250 // |uscript_getScriptExtensions| will contain the regular script property.
251 // Write the character's script property to the first element.
252 scripts[0] = uscript_getScript(codepoint, &icu_error);
253 if (U_FAILURE(icu_error))
254 return 0;
255 // Fill the rest of |scripts| with the extensions.
256 int count = uscript_getScriptExtensions(codepoint, scripts + 1,
257 kMaxScripts - 1, &icu_error);
258 if (U_FAILURE(icu_error))
259 count = 0;
260 return count + 1;
261 }
262
263 // Intersects the script extensions set of |codepoint| with |result| and writes
264 // to |result|, reading and updating |result_size|.
265 void ScriptSetIntersect(UChar32 codepoint,
266 UScriptCode* result,
267 size_t* result_size) {
268 UScriptCode scripts[kMaxScripts] = { USCRIPT_INVALID_CODE };
269 int count = GetScriptExtensions(codepoint, scripts);
270
271 size_t out_size = 0;
272
273 for (size_t i = 0; i < *result_size; ++i) {
274 for (int j = 0; j < count; ++j) {
275 UScriptCode intersection = ScriptIntersect(result[i], scripts[j]);
276 if (intersection != USCRIPT_INVALID_CODE) {
277 result[out_size++] = intersection;
278 break;
279 }
280 }
281 }
282
283 *result_size = out_size;
284 }
285
286 // Find the longest sequence of characters from 0 and up to |length| that
287 // have at least one common UScriptCode value. Writes the common script value to
288 // |script| and returns the length of the sequence. Takes the characters' script
289 // extensions into account. http://www.unicode.org/reports/tr24/#ScriptX
290 //
291 // Consider 3 characters with the script values {Kana}, {Hira, Kana}, {Kana}.
292 // Without script extensions only the first script in each set would be taken
293 // into account, resulting in 3 runs where 1 would be enough.
294 // TODO(ckocagil): Write a unit test for the case above.
295 int ScriptInterval(const base::string16& text,
296 size_t start,
297 size_t length,
298 UScriptCode* script) {
299 DCHECK_GT(length, 0U);
300
301 UScriptCode scripts[kMaxScripts] = { USCRIPT_INVALID_CODE };
302
303 base::i18n::UTF16CharIterator char_iterator(text.c_str() + start, length);
304 size_t scripts_size = GetScriptExtensions(char_iterator.get(), scripts);
305 *script = scripts[0];
306
307 while (char_iterator.Advance()) {
308 ScriptSetIntersect(char_iterator.get(), scripts, &scripts_size);
309 if (scripts_size == 0U)
310 return char_iterator.array_pos();
311 *script = scripts[0];
312 }
313
314 return length;
315 }
316
317 } // namespace
318
319 namespace internal {
320
321 TextRunHarfBuzz::TextRunHarfBuzz()
322 : width(0),
323 preceding_run_widths(0),
324 direction(UBIDI_LTR),
325 level(0),
326 script(USCRIPT_INVALID_CODE),
327 glyph_count(-1),
328 font_size(0),
329 font_style(0),
330 strike(false),
331 diagonal_strike(false),
332 underline(false) {}
333
334 TextRunHarfBuzz::~TextRunHarfBuzz() {}
335
336 size_t TextRunHarfBuzz::CharToGlyph(size_t pos) const {
337 DCHECK(range.start() <= pos && pos < range.end());
338
339 if (direction == UBIDI_LTR) {
340 for (size_t i = 0; i < glyph_count - 1; ++i) {
341 if (pos < glyph_to_char[i + 1])
342 return i;
343 }
344 return glyph_count - 1;
345 }
346
347 for (size_t i = 0; i < glyph_count; ++i) {
348 if (pos >= glyph_to_char[i])
349 return i;
350 }
351 NOTREACHED();
352 return 0;
353 }
354
355 Range TextRunHarfBuzz::CharRangeToGlyphRange(const Range& range) const {
356 DCHECK(range.Contains(range));
357 DCHECK(!range.is_reversed());
358 DCHECK(!range.is_empty());
359
360 const size_t first = CharToGlyph(range.start());
361 const size_t last = CharToGlyph(range.end() - 1);
362 // TODO(ckocagil): What happens when the character has zero or multiple
363 // glyphs? Is the "+ 1" below correct then?
364 return Range(std::min(first, last), std::max(first, last) + 1);
365 }
366
367 // Returns whether the given shaped run contains any missing glyphs.
368 bool TextRunHarfBuzz::HasMissingGlyphs() const {
369 static const int kMissingGlyphId = 0;
370 for (size_t i = 0; i < glyph_count; ++i) {
371 if (glyphs[i] == kMissingGlyphId)
372 return true;
373 }
374 return false;
375 }
376
377 int TextRunHarfBuzz::GetGlyphXBoundary(size_t text_index, bool trailing) const {
378 int x = preceding_run_widths;
379 Range glyph_range;
380 if (text_index == range.end()) {
381 trailing = true;
382 glyph_range = direction == UBIDI_LTR ?
383 Range(glyph_count - 1, glyph_count) : Range(0, 1);
384 } else {
385 glyph_range = CharRangeToGlyphRange(Range(text_index, text_index + 1));
386 }
387 const int trailing_step = trailing ? 1 : 0;
388 const size_t glyph_pos = glyph_range.start() +
389 (direction == UBIDI_LTR ? trailing_step : (1 - trailing_step));
390 x += glyph_pos < glyph_count ?
391 SkScalarRoundToInt(positions[glyph_pos].x()) : width;
392 return x;
393 }
394
395 } // namespace internal
396
397 RenderTextHarfBuzz::RenderTextHarfBuzz()
398 : RenderText(),
399 needs_layout_(false) {}
400
401 RenderTextHarfBuzz::~RenderTextHarfBuzz() {}
402
403 Size RenderTextHarfBuzz::GetStringSize() {
404 EnsureLayout();
405 return Size(lines()[0].size.width(), font_list().GetHeight());
406 }
407
408 SelectionModel RenderTextHarfBuzz::FindCursorPosition(const Point& point) {
409 EnsureLayout();
410
411 int x = ToTextPoint(point).x();
412 int offset = 0;
413 size_t run_index = GetRunContainingXCoord(x, &offset);
414 if (run_index >= runs_.size())
415 return EdgeSelectionModel((x < 0) ? CURSOR_LEFT : CURSOR_RIGHT);
416 const internal::TextRunHarfBuzz& run = *runs_[run_index];
417
418 for (size_t i = 0; i < run.glyph_count; ++i) {
419 const SkScalar end =
420 i + 1 == run.glyph_count ? run.width : run.positions[i + 1].x();
421 const SkScalar middle = (end + run.positions[i].x()) / 2;
422 const bool is_rtl = run.direction == UBIDI_RTL;
423 if (offset < middle) {
424 return SelectionModel(LayoutIndexToTextIndex(
425 run.glyph_to_char[i] + (is_rtl ? 1 : 0)),
426 (is_rtl ? CURSOR_BACKWARD : CURSOR_FORWARD));
427 }
428 if (offset < end) {
429 return SelectionModel(LayoutIndexToTextIndex(
430 run.glyph_to_char[i] + (is_rtl ? 0 : 1)),
431 (is_rtl ? CURSOR_FORWARD : CURSOR_BACKWARD));
432 }
433 }
434 return EdgeSelectionModel(CURSOR_RIGHT);
435 }
436
437 std::vector<RenderText::FontSpan> RenderTextHarfBuzz::GetFontSpansForTesting() {
438 NOTIMPLEMENTED();
439 return std::vector<RenderText::FontSpan>();
440 }
441
442 int RenderTextHarfBuzz::GetLayoutTextBaseline() {
443 EnsureLayout();
444 return lines()[0].baseline;
445 }
446
447 SelectionModel RenderTextHarfBuzz::AdjacentCharSelectionModel(
448 const SelectionModel& selection,
449 VisualCursorDirection direction) {
450 DCHECK(!needs_layout_);
451 internal::TextRunHarfBuzz* run;
452 size_t run_index = GetRunContainingCaret(selection);
453 if (run_index >= runs_.size()) {
454 // The cursor is not in any run: we're at the visual and logical edge.
455 SelectionModel edge = EdgeSelectionModel(direction);
456 if (edge.caret_pos() == selection.caret_pos())
457 return edge;
458 int visual_index = (direction == CURSOR_RIGHT) ? 0 : runs_.size() - 1;
459 run = runs_[visual_to_logical_[visual_index]];
460 } else {
461 // If the cursor is moving within the current run, just move it by one
462 // grapheme in the appropriate direction.
463 run = runs_[run_index];
464 size_t caret = selection.caret_pos();
465 bool forward_motion =
466 (run->direction == UBIDI_RTL) == (direction == CURSOR_LEFT);
467 if (forward_motion) {
468 if (caret < LayoutIndexToTextIndex(run->range.end())) {
469 caret = IndexOfAdjacentGrapheme(caret, CURSOR_FORWARD);
470 return SelectionModel(caret, CURSOR_BACKWARD);
471 }
472 } else {
473 if (caret > LayoutIndexToTextIndex(run->range.start())) {
474 caret = IndexOfAdjacentGrapheme(caret, CURSOR_BACKWARD);
475 return SelectionModel(caret, CURSOR_FORWARD);
476 }
477 }
478 // The cursor is at the edge of a run; move to the visually adjacent run.
479 int visual_index = logical_to_visual_[run_index];
480 visual_index += (direction == CURSOR_LEFT) ? -1 : 1;
481 if (visual_index < 0 || visual_index >= static_cast<int>(runs_.size()))
482 return EdgeSelectionModel(direction);
483 run = runs_[visual_to_logical_[visual_index]];
484 }
485 bool forward_motion =
486 (run->direction == UBIDI_RTL) == (direction == CURSOR_LEFT);
487 return forward_motion ? FirstSelectionModelInsideRun(run) :
488 LastSelectionModelInsideRun(run);
489 }
490
491 SelectionModel RenderTextHarfBuzz::AdjacentWordSelectionModel(
492 const SelectionModel& selection,
493 VisualCursorDirection direction) {
494 // TODO(ckocagil): This implementation currently matches RenderTextWin, but it
495 // should match the native behavior on other platforms.
496 if (obscured())
497 return EdgeSelectionModel(direction);
498
499 base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD);
500 bool success = iter.Init();
501 DCHECK(success);
502 if (!success)
503 return selection;
504
505 size_t pos;
506 if (direction == CURSOR_RIGHT) {
507 pos = std::min(selection.caret_pos() + 1, text().length());
508 while (iter.Advance()) {
509 pos = iter.pos();
510 if (iter.IsWord() && pos > selection.caret_pos())
511 break;
512 }
513 } else { // direction == CURSOR_LEFT
514 // Notes: We always iterate words from the beginning.
515 // This is probably fast enough for our usage, but we may
516 // want to modify WordIterator so that it can start from the
517 // middle of string and advance backwards.
518 pos = std::max<int>(selection.caret_pos() - 1, 0);
519 while (iter.Advance()) {
520 if (iter.IsWord()) {
521 size_t begin = iter.pos() - iter.GetString().length();
522 if (begin == selection.caret_pos()) {
523 // The cursor is at the beginning of a word.
524 // Move to previous word.
525 break;
526 } else if (iter.pos() >= selection.caret_pos()) {
527 // The cursor is in the middle or at the end of a word.
528 // Move to the top of current word.
529 pos = begin;
530 break;
531 }
532 pos = iter.pos() - iter.GetString().length();
533 }
534 }
535 }
536 return SelectionModel(pos, CURSOR_FORWARD);
537 }
538
539 Range RenderTextHarfBuzz::GetGlyphBounds(size_t index) {
540 const size_t run_index =
541 GetRunContainingCaret(SelectionModel(index, CURSOR_FORWARD));
542 // Return edge bounds if the index is invalid or beyond the layout text size.
543 if (run_index >= runs_.size())
544 return Range(GetStringSize().width());
545 const size_t layout_index = TextIndexToLayoutIndex(index);
546 return Range(runs_[run_index]->GetGlyphXBoundary(layout_index, false),
547 runs_[run_index]->GetGlyphXBoundary(layout_index, true));
548 }
549
550 std::vector<Rect> RenderTextHarfBuzz::GetSubstringBounds(const Range& range) {
551 DCHECK(!needs_layout_);
552 DCHECK(Range(0, text().length()).Contains(range));
553 Range layout_range(TextIndexToLayoutIndex(range.start()),
554 TextIndexToLayoutIndex(range.end()));
555 DCHECK(Range(0, GetLayoutText().length()).Contains(layout_range));
556
557 std::vector<Rect> rects;
558 if (layout_range.is_empty())
559 return rects;
560 std::vector<Range> bounds;
561
562 // Add a Range for each run/selection intersection.
563 // TODO(msw): The bounds should probably not always be leading the range ends.
564 for (size_t i = 0; i < runs_.size(); ++i) {
565 const internal::TextRunHarfBuzz* run = runs_[visual_to_logical_[i]];
566 Range intersection = run->range.Intersect(layout_range);
567 if (intersection.IsValid()) {
568 DCHECK(!intersection.is_reversed());
569 Range range_x(run->GetGlyphXBoundary(intersection.start(), false),
570 run->GetGlyphXBoundary(intersection.end(), false));
571 if (range_x.is_empty())
572 continue;
573 range_x = Range(range_x.GetMin(), range_x.GetMax());
574 // Union this with the last range if they're adjacent.
575 DCHECK(bounds.empty() || bounds.back().GetMax() <= range_x.GetMin());
576 if (!bounds.empty() && bounds.back().GetMax() == range_x.GetMin()) {
577 range_x = Range(bounds.back().GetMin(), range_x.GetMax());
578 bounds.pop_back();
579 }
580 bounds.push_back(range_x);
581 }
582 }
583 for (size_t i = 0; i < bounds.size(); ++i) {
584 std::vector<Rect> current_rects = TextBoundsToViewBounds(bounds[i]);
585 rects.insert(rects.end(), current_rects.begin(), current_rects.end());
586 }
587 return rects;
588 }
589
590 size_t RenderTextHarfBuzz::TextIndexToLayoutIndex(size_t index) const {
591 DCHECK_LE(index, text().length());
592 ptrdiff_t i = obscured() ? UTF16IndexToOffset(text(), 0, index) : index;
593 CHECK_GE(i, 0);
594 // Clamp layout indices to the length of the text actually used for layout.
595 return std::min<size_t>(GetLayoutText().length(), i);
596 }
597
598 size_t RenderTextHarfBuzz::LayoutIndexToTextIndex(size_t index) const {
599 if (!obscured())
600 return index;
601
602 DCHECK_LE(index, GetLayoutText().length());
603 const size_t text_index = UTF16OffsetToIndex(text(), 0, index);
604 DCHECK_LE(text_index, text().length());
605 return text_index;
606 }
607
608 bool RenderTextHarfBuzz::IsValidCursorIndex(size_t index) {
609 if (index == 0 || index == text().length())
610 return true;
611 if (!IsValidLogicalIndex(index))
612 return false;
613 EnsureLayout();
614 // Disallow indices amid multi-character graphemes by checking glyph bounds.
615 // These characters are not surrogate-pairs, but may yield a single glyph:
616 // \x0915\x093f - (ki) - one of many Devanagari biconsonantal conjuncts.
617 // \x0e08\x0e33 - (cho chan + sara am) - a Thai consonant and vowel pair.
618 return GetGlyphBounds(index) != GetGlyphBounds(index - 1);
619 }
620
621 void RenderTextHarfBuzz::ResetLayout() {
622 needs_layout_ = true;
623 }
624
625 void RenderTextHarfBuzz::EnsureLayout() {
626 if (needs_layout_) {
627 runs_.clear();
628
629 if (!GetLayoutText().empty()) {
630 ItemizeText();
631
632 for (size_t i = 0; i < runs_.size(); ++i)
633 ShapeRun(runs_[i]);
634
635 // Precalculate run width information.
636 size_t preceding_run_widths = 0;
637 for (size_t i = 0; i < runs_.size(); ++i) {
638 internal::TextRunHarfBuzz* run = runs_[visual_to_logical_[i]];
639 run->preceding_run_widths = preceding_run_widths;
640 preceding_run_widths += run->width;
641 }
642 }
643
644 needs_layout_ = false;
645 std::vector<internal::Line> empty_lines;
646 set_lines(&empty_lines);
647 }
648
649 if (lines().empty()) {
650 std::vector<internal::Line> lines;
651 lines.push_back(internal::Line());
652
653 int current_x = 0;
654 SkPaint paint;
655
656 for (size_t i = 0; i < runs_.size(); ++i) {
657 const internal::TextRunHarfBuzz& run = *runs_[visual_to_logical_[i]];
658 internal::LineSegment segment;
659 segment.x_range = Range(current_x, current_x + run.width);
660 segment.char_range = run.range;
661 segment.run = i;
662 lines[0].segments.push_back(segment);
663
664 paint.setTypeface(run.skia_face.get());
665 paint.setTextSize(run.font_size);
666 SkPaint::FontMetrics metrics;
667 paint.getFontMetrics(&metrics);
668
669 lines[0].size.set_width(lines[0].size.width() + run.width);
670 lines[0].size.set_height(std::max(lines[0].size.height(),
671 SkScalarRoundToInt(metrics.fDescent - metrics.fAscent)));
672 lines[0].baseline = std::max(lines[0].baseline,
673 SkScalarRoundToInt(-metrics.fAscent));
674 }
675
676 set_lines(&lines);
677 }
678 }
679
680 void RenderTextHarfBuzz::DrawVisualText(Canvas* canvas) {
681 DCHECK(!needs_layout_);
682
683 int current_x = 0;
684
685 internal::SkiaTextRenderer renderer(canvas);
686 ApplyFadeEffects(&renderer);
687 ApplyTextShadows(&renderer);
688
689 #if defined(OS_WIN)
690 bool smoothing_enabled;
691 bool cleartype_enabled;
692 GetCachedFontSmoothingSettings(&smoothing_enabled, &cleartype_enabled);
693 // Note that |cleartype_enabled| corresponds to Skia's |enable_lcd_text|.
694 renderer.SetFontSmoothingSettings(
695 smoothing_enabled, cleartype_enabled && !background_is_transparent(),
696 smoothing_enabled /* subpixel_positioning */);
697 #endif
698
699 ApplyCompositionAndSelectionStyles();
700
701 const Vector2d line_offset = GetLineOffset(0);
702
703 for (size_t i = 0; i < runs_.size(); ++i) {
704 const internal::TextRunHarfBuzz& run = *runs_[visual_to_logical_[i]];
705 renderer.SetTypeface(run.skia_face.get());
706 renderer.SetTextSize(run.font_size);
707
708 canvas->Save();
709 Vector2d origin = line_offset + Vector2d(current_x, lines()[0].baseline);
710 canvas->Translate(origin);
711
712 for (BreakList<SkColor>::const_iterator it =
713 colors().GetBreak(run.range.start());
714 it != colors().breaks().end() && it->first < run.range.end();
715 ++it) {
716 const Range intersection = colors().GetRange(it).Intersect(run.range);
717 const Range colored_glyphs = run.CharRangeToGlyphRange(intersection);
718 // The range may be empty if a portion of a multi-character grapheme is
719 // selected, yielding two colors for a single glyph. For now, this just
720 // paints the glyph with a single style, but it should paint it twice,
721 // clipped according to selection bounds. See http://crbug.com/366786
722 if (colored_glyphs.is_empty())
723 continue;
724
725 renderer.SetForegroundColor(it->second);
726 renderer.DrawPosText(&run.positions[colored_glyphs.start()],
727 &run.glyphs[colored_glyphs.start()],
728 colored_glyphs.length());
729 int width = (colored_glyphs.end() == run.glyph_count ? run.width :
730 run.positions[colored_glyphs.end()].x()) -
731 run.positions[colored_glyphs.start()].x();
732 renderer.DrawDecorations(0, 0, width, run.underline, run.strike,
733 run.diagonal_strike);
734 }
735
736 canvas->Restore();
737 current_x += run.width;
738 }
739
740 renderer.EndDiagonalStrike();
741
742 UndoCompositionAndSelectionStyles();
743 }
744
745 size_t RenderTextHarfBuzz::GetRunContainingCaret(
746 const SelectionModel& caret) const {
747 DCHECK(!needs_layout_);
748 size_t layout_position = TextIndexToLayoutIndex(caret.caret_pos());
749 LogicalCursorDirection affinity = caret.caret_affinity();
750 for (size_t run = 0; run < runs_.size(); ++run) {
751 if (RangeContainsCaret(runs_[run]->range, layout_position, affinity))
752 return run;
753 }
754 return runs_.size();
755 }
756
757 size_t RenderTextHarfBuzz::GetRunContainingXCoord(int x, int* offset) const {
758 DCHECK(!needs_layout_);
759 if (x < 0)
760 return runs_.size();
761 // Find the text run containing the argument point (assumed already offset).
762 int current_x = 0;
763 for (size_t i = 0; i < runs_.size(); ++i) {
764 size_t run = visual_to_logical_[i];
765 current_x += runs_[run]->width;
766 if (x < current_x) {
767 *offset = x - (current_x - runs_[run]->width);
768 return run;
769 }
770 }
771 return runs_.size();
772 }
773
774 SelectionModel RenderTextHarfBuzz::FirstSelectionModelInsideRun(
775 const internal::TextRunHarfBuzz* run) {
776 size_t position = LayoutIndexToTextIndex(run->range.start());
777 position = IndexOfAdjacentGrapheme(position, CURSOR_FORWARD);
778 return SelectionModel(position, CURSOR_BACKWARD);
779 }
780
781 SelectionModel RenderTextHarfBuzz::LastSelectionModelInsideRun(
782 const internal::TextRunHarfBuzz* run) {
783 size_t position = LayoutIndexToTextIndex(run->range.end());
784 position = IndexOfAdjacentGrapheme(position, CURSOR_BACKWARD);
785 return SelectionModel(position, CURSOR_FORWARD);
786 }
787
788 void RenderTextHarfBuzz::ItemizeText() {
789 const base::string16& text = GetLayoutText();
790 const bool is_rtl = GetTextDirection() == base::i18n::RIGHT_TO_LEFT;
791 DCHECK_NE(0U, text.length());
792
793 // If ICU fails to itemize the text, we set |fake_runs| and create a run that
794 // spans the entire text. This is needed because early returning and leaving
795 // the runs set empty causes some clients to crash/misbehave since they expect
796 // non-zero text metrics from a non-empty text.
797 bool fake_runs = false;
798 UErrorCode result = U_ZERO_ERROR;
799
800 UBiDi* line = ubidi_openSized(text.length(), 0, &result);
801 if (U_FAILURE(result)) {
802 NOTREACHED();
803 fake_runs = true;
804 } else {
805 ubidi_setPara(line, text.c_str(), text.length(),
806 is_rtl ? UBIDI_DEFAULT_RTL : UBIDI_DEFAULT_LTR, NULL,
807 &result);
808 if (U_FAILURE(result)) {
809 NOTREACHED();
810 fake_runs = true;
811 }
812 }
813
814 // Temporarily apply composition underlines and selection colors.
815 ApplyCompositionAndSelectionStyles();
816
817 // Build the list of runs from the script items and ranged styles. Use an
818 // empty color BreakList to avoid breaking runs at color boundaries.
819 BreakList<SkColor> empty_colors;
820 empty_colors.SetMax(text.length());
821 internal::StyleIterator style(empty_colors, styles());
822
823 for (size_t run_break = 0; run_break < text.length();) {
824 internal::TextRunHarfBuzz* run = new internal::TextRunHarfBuzz;
825 run->range.set_start(run_break);
826 run->font_style = (style.style(BOLD) ? Font::BOLD : 0) |
827 (style.style(ITALIC) ? Font::ITALIC : 0);
828 run->strike = style.style(STRIKE);
829 run->diagonal_strike = style.style(DIAGONAL_STRIKE);
830 run->underline = style.style(UNDERLINE);
831
832 if (fake_runs) {
833 run_break = text.length();
834 } else {
835 int32 script_item_break = 0;
836 ubidi_getLogicalRun(line, run_break, &script_item_break, &run->level);
837 // Find the length and script of this script run.
838 script_item_break = ScriptInterval(text, run_break,
839 script_item_break - run_break, &run->script) + run_break;
840
841 // Find the next break and advance the iterators as needed.
842 run_break = std::min(static_cast<size_t>(script_item_break),
843 TextIndexToLayoutIndex(style.GetRange().end()));
844
845 // Break runs adjacent to character substrings in certain code blocks.
846 // This avoids using their fallback fonts for more characters than needed,
847 // in cases like "\x25B6 Media Title", etc. http://crbug.com/278913
848 if (run_break > run->range.start()) {
849 const size_t run_start = run->range.start();
850 const int32 run_length = static_cast<int32>(run_break - run_start);
851 base::i18n::UTF16CharIterator iter(text.c_str() + run_start,
852 run_length);
853 const UBlockCode first_block_code = ublock_getCode(iter.get());
854 const bool first_block_unusual = IsUnusualBlockCode(first_block_code);
855 while (iter.Advance() && iter.array_pos() < run_length) {
856 const UBlockCode current_block_code = ublock_getCode(iter.get());
857 if (current_block_code != first_block_code &&
858 (first_block_unusual || IsUnusualBlockCode(current_block_code))) {
859 run_break = run_start + iter.array_pos();
860 break;
861 }
862 }
863 }
864 }
865
866 DCHECK(IsValidCodePointIndex(text, run_break));
867 style.UpdatePosition(LayoutIndexToTextIndex(run_break));
868 run->range.set_end(run_break);
869 const UChar* uchar_start = ubidi_getText(line);
870 // TODO(ckocagil): Add |ubidi_getBaseDirection| to i18n::BiDiLineIterator
871 // and remove the bare ICU use here.
872 run->direction = ubidi_getBaseDirection(uchar_start + run->range.start(),
873 run->range.length());
874 if (run->direction == UBIDI_NEUTRAL)
875 run->direction = is_rtl ? UBIDI_RTL : UBIDI_LTR;
876 runs_.push_back(run);
877 }
878
879 ubidi_close(line);
880
881 // Undo the temporarily applied composition underlines and selection colors.
882 UndoCompositionAndSelectionStyles();
883
884 const size_t num_runs = runs_.size();
885 std::vector<UBiDiLevel> levels(num_runs);
886 for (size_t i = 0; i < num_runs; ++i)
887 levels[i] = runs_[i]->level;
888 visual_to_logical_.resize(num_runs);
889 ubidi_reorderVisual(&levels[0], num_runs, &visual_to_logical_[0]);
890 logical_to_visual_.resize(num_runs);
891 ubidi_reorderLogical(&levels[0], num_runs, &logical_to_visual_[0]);
892 }
893
894 void RenderTextHarfBuzz::ShapeRun(internal::TextRunHarfBuzz* run) {
895 const base::string16& text = GetLayoutText();
896 // TODO(ckocagil|yukishiino): Implement font fallback.
897 const Font& primary_font = font_list().GetPrimaryFont();
898 run->skia_face = internal::CreateSkiaTypeface(primary_font.GetFontName(),
899 run->font_style);
900 run->font_size = primary_font.GetFontSize();
901
902 hb_font_t* harfbuzz_font = CreateHarfBuzzFont(run->skia_face.get(),
903 run->font_size);
904
905 // Create a HarfBuzz buffer and add the string to be shaped. The HarfBuzz
906 // buffer holds our text, run information to be used by the shaping engine,
907 // and the resulting glyph data.
908 hb_buffer_t* buffer = hb_buffer_create();
909 hb_buffer_add_utf16(buffer, reinterpret_cast<const uint16*>(text.c_str()),
910 text.length(), run->range.start(), run->range.length());
911 hb_buffer_set_script(buffer, hb_icu_script_to_script(run->script));
912 hb_buffer_set_direction(buffer,
913 run->direction == UBIDI_LTR ? HB_DIRECTION_LTR : HB_DIRECTION_RTL);
914 // TODO(ckocagil): Should we determine the actual language?
915 hb_buffer_set_language(buffer, hb_language_get_default());
916
917 // Shape the text.
918 hb_shape(harfbuzz_font, buffer, NULL, 0);
919
920 // Populate the run fields with the resulting glyph data in the buffer.
921 unsigned int glyph_count = 0;
922 hb_glyph_info_t* infos = hb_buffer_get_glyph_infos(buffer, &glyph_count);
923 hb_glyph_position_t* hb_positions = hb_buffer_get_glyph_positions(buffer,
924 NULL);
925 run->glyph_count = glyph_count;
926 run->glyphs.reset(new uint16[run->glyph_count]);
927 run->glyph_to_char.reset(new uint32[run->glyph_count]);
928 run->positions.reset(new SkPoint[run->glyph_count]);
929 for (size_t i = 0; i < run->glyph_count; ++i) {
930 run->glyphs[i] = infos[i].codepoint;
931 run->glyph_to_char[i] = infos[i].cluster;
932 const int x_offset =
933 SkScalarRoundToInt(SkFixedToScalar(hb_positions[i].x_offset));
934 const int y_offset =
935 SkScalarRoundToInt(SkFixedToScalar(hb_positions[i].y_offset));
936 run->positions[i].set(run->width + x_offset, y_offset);
937 run->width +=
938 SkScalarRoundToInt(SkFixedToScalar(hb_positions[i].x_advance));
939 }
940
941 hb_buffer_destroy(buffer);
942 hb_font_destroy(harfbuzz_font);
943 }
944
945 } // namespace gfx
OLDNEW
« no previous file with comments | « ui/gfx/render_text_harfbuzz.h ('k') | ui/gfx/render_text_mac.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698