OLD | NEW |
---|---|
(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(const UBlockCode block_code) { | |
Alexei Svitkine (slow)
2014/05/21 07:39:02
Nit: No need for const
ckocagil
2014/05/21 14:34:39
Done.
| |
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 // Call |uscript_getScript| to get the script property. | |
252 scripts[0] = uscript_getScript(codepoint, &icu_error); | |
253 if (U_FAILURE(icu_error)) | |
254 return 0; | |
255 int count = uscript_getScriptExtensions(codepoint, scripts + 1, | |
Alexei Svitkine (slow)
2014/05/21 07:39:02
Nit: Might be good to add a comment explaining the
ckocagil
2014/05/21 14:34:39
Done.
| |
256 kMaxScripts - 1, &icu_error); | |
257 if (U_FAILURE(icu_error)) | |
258 count = 0; | |
259 return count + 1; | |
260 } | |
261 | |
262 // Intersects the script extensions set of |codepoint| with |result| and writes | |
263 // to |result|, reading and updating |result_size|. | |
264 void ScriptSetIntersect(UChar32 codepoint, | |
265 UScriptCode* result, | |
266 size_t* result_size) { | |
267 UScriptCode scripts[kMaxScripts] = { USCRIPT_INVALID_CODE }; | |
268 int count = GetScriptExtensions(codepoint, scripts); | |
269 | |
270 size_t out_size = 0; | |
271 | |
272 for (size_t i = 0; i < *result_size; ++i) { | |
273 for (int j = 0; j < count; ++j) { | |
274 UScriptCode intersection = ScriptIntersect(result[i], scripts[j]); | |
275 if (intersection != USCRIPT_INVALID_CODE) { | |
276 result[out_size++] = intersection; | |
277 break; | |
278 } | |
279 } | |
280 } | |
281 | |
282 *result_size = out_size; | |
283 } | |
284 | |
285 // Find the longest sequence of characters from 0 and up to |length| that | |
286 // have at least one common UScriptCode value. Writes the common script value to | |
287 // |script| and returns the length of the sequence. Takes the characters' script | |
288 // extensions into account. http://www.unicode.org/reports/tr24/#ScriptX | |
289 // | |
290 // Consider 3 characters with the script values {Kana}, {Hira, Kana}, {Kana}. | |
291 // Without script extensions only the first script in each set would be taken | |
292 // into account, resulting in 3 runs where 1 would be enough. | |
293 // TODO(ckocagil): Write a unit test for the case above. | |
294 int ScriptInterval(const base::string16& text, | |
295 size_t start, | |
296 size_t length, | |
297 UScriptCode* script) { | |
298 DCHECK_GT(length, 0U); | |
299 | |
300 UScriptCode scripts[kMaxScripts] = { USCRIPT_INVALID_CODE }; | |
301 | |
302 base::i18n::UTF16CharIterator char_iterator(text.c_str() + start, length); | |
303 size_t scripts_size = GetScriptExtensions(char_iterator.get(), scripts); | |
304 *script = scripts[0]; | |
305 | |
306 while (char_iterator.Advance()) { | |
307 ScriptSetIntersect(char_iterator.get(), scripts, &scripts_size); | |
308 if (scripts_size == 0U) | |
309 return char_iterator.array_pos(); | |
310 *script = scripts[0]; | |
311 } | |
312 | |
313 return length; | |
314 } | |
315 | |
316 } // namespace | |
317 | |
318 namespace internal { | |
319 | |
320 TextRunHarfBuzz::TextRunHarfBuzz() | |
321 : width(0), | |
322 preceding_run_widths(0), | |
323 direction(UBIDI_LTR), | |
324 level(0), | |
325 script(USCRIPT_INVALID_CODE), | |
326 glyph_count(-1), | |
327 font_size(0), | |
328 font_style(0), | |
329 strike(false), | |
330 diagonal_strike(false), | |
331 underline(false) {} | |
332 | |
333 TextRunHarfBuzz::~TextRunHarfBuzz() {} | |
334 | |
335 size_t TextRunHarfBuzz::CharToGlyph(size_t pos) const { | |
336 DCHECK(range.start() <= pos && pos < range.end()); | |
337 | |
338 if (direction == UBIDI_LTR) { | |
339 for (size_t i = 0; i < glyph_count - 1; ++i) { | |
340 if (pos < glyph_to_char[i + 1]) | |
341 return i; | |
342 } | |
343 return glyph_count - 1; | |
344 } | |
345 | |
346 for (size_t i = 0; i < glyph_count; ++i) { | |
347 if (pos >= glyph_to_char[i]) | |
348 return i; | |
349 } | |
350 NOTREACHED(); | |
351 return 0; | |
352 } | |
353 | |
354 Range TextRunHarfBuzz::CharRangeToGlyphRange(const Range& range) const { | |
355 DCHECK(range.Contains(range)); | |
356 DCHECK(!range.is_reversed()); | |
357 DCHECK(!range.is_empty()); | |
358 | |
359 const size_t first = CharToGlyph(range.start()); | |
360 const size_t last = CharToGlyph(range.end() - 1); | |
361 // TODO(ckocagil): What happens when the character has zero or multiple | |
362 // glyphs? Is the "+ 1" below correct then? | |
363 return Range(std::min(first, last), std::max(first, last) + 1); | |
364 } | |
365 | |
366 // Returns whether the given shaped run contains any missing glyphs. | |
367 bool TextRunHarfBuzz::HasMissingGlyphs() const { | |
368 static const int kMissingGlyphId = 0; | |
369 for (size_t i = 0; i < glyph_count; ++i) { | |
370 if (glyphs[i] == kMissingGlyphId) | |
371 return true; | |
372 } | |
373 return false; | |
374 } | |
375 | |
376 } // namespace internal | |
377 | |
378 RenderTextHarfBuzz::RenderTextHarfBuzz() | |
379 : RenderText(), | |
380 needs_layout_(false) {} | |
381 | |
382 RenderTextHarfBuzz::~RenderTextHarfBuzz() {} | |
383 | |
384 Size RenderTextHarfBuzz::GetStringSize() { | |
385 EnsureLayout(); | |
386 return Size(lines()[0].size.width(), font_list().GetHeight()); | |
387 } | |
388 | |
389 SelectionModel RenderTextHarfBuzz::FindCursorPosition(const Point& point) { | |
390 EnsureLayout(); | |
391 | |
392 int x = ToTextPoint(point).x(); | |
393 int offset = 0; | |
394 size_t run_index = GetRunContainingXCoord(x, &offset); | |
395 if (run_index >= runs_.size()) | |
396 return EdgeSelectionModel((x < 0) ? CURSOR_LEFT : CURSOR_RIGHT); | |
397 const internal::TextRunHarfBuzz& run = *runs_[run_index]; | |
398 | |
399 for (size_t i = 0; i < run.glyph_count; ++i) { | |
400 const SkScalar end = | |
401 i + 1 == run.glyph_count ? run.width : run.positions[i + 1].x(); | |
402 const SkScalar middle = (end + run.positions[i].x()) / 2; | |
403 const bool is_rtl = run.direction == UBIDI_RTL; | |
404 if (offset < middle) { | |
405 return SelectionModel(LayoutIndexToTextIndex( | |
406 run.glyph_to_char[i] + (is_rtl ? 1 : 0)), | |
407 (is_rtl ? CURSOR_BACKWARD : CURSOR_FORWARD)); | |
408 } | |
409 if (offset < end) { | |
410 return SelectionModel(LayoutIndexToTextIndex( | |
411 run.glyph_to_char[i] + (is_rtl ? 0 : 1)), | |
412 (is_rtl ? CURSOR_FORWARD : CURSOR_BACKWARD)); | |
413 } | |
414 } | |
415 return EdgeSelectionModel(CURSOR_RIGHT); | |
416 } | |
417 | |
418 std::vector<RenderText::FontSpan> RenderTextHarfBuzz::GetFontSpansForTesting() { | |
419 NOTIMPLEMENTED(); | |
420 return std::vector<RenderText::FontSpan>(); | |
421 } | |
422 | |
423 int RenderTextHarfBuzz::GetLayoutTextBaseline() { | |
424 EnsureLayout(); | |
425 return lines()[0].baseline; | |
426 } | |
427 | |
428 SelectionModel RenderTextHarfBuzz::AdjacentCharSelectionModel( | |
429 const SelectionModel& selection, | |
430 VisualCursorDirection direction) { | |
431 DCHECK(!needs_layout_); | |
432 internal::TextRunHarfBuzz* run; | |
433 size_t run_index = GetRunContainingCaret(selection); | |
434 if (run_index >= runs_.size()) { | |
435 // The cursor is not in any run: we're at the visual and logical edge. | |
436 SelectionModel edge = EdgeSelectionModel(direction); | |
437 if (edge.caret_pos() == selection.caret_pos()) | |
438 return edge; | |
439 int visual_index = (direction == CURSOR_RIGHT) ? 0 : runs_.size() - 1; | |
440 run = runs_[visual_to_logical_[visual_index]]; | |
441 } else { | |
442 // If the cursor is moving within the current run, just move it by one | |
443 // grapheme in the appropriate direction. | |
444 run = runs_[run_index]; | |
445 size_t caret = selection.caret_pos(); | |
446 bool forward_motion = | |
447 (run->direction == UBIDI_RTL) == (direction == CURSOR_LEFT); | |
448 if (forward_motion) { | |
449 if (caret < LayoutIndexToTextIndex(run->range.end())) { | |
450 caret = IndexOfAdjacentGrapheme(caret, CURSOR_FORWARD); | |
451 return SelectionModel(caret, CURSOR_BACKWARD); | |
452 } | |
453 } else { | |
454 if (caret > LayoutIndexToTextIndex(run->range.start())) { | |
455 caret = IndexOfAdjacentGrapheme(caret, CURSOR_BACKWARD); | |
456 return SelectionModel(caret, CURSOR_FORWARD); | |
457 } | |
458 } | |
459 // The cursor is at the edge of a run; move to the visually adjacent run. | |
460 int visual_index = logical_to_visual_[run_index]; | |
461 visual_index += (direction == CURSOR_LEFT) ? -1 : 1; | |
462 if (visual_index < 0 || visual_index >= static_cast<int>(runs_.size())) | |
463 return EdgeSelectionModel(direction); | |
464 run = runs_[visual_to_logical_[visual_index]]; | |
465 } | |
466 bool forward_motion = | |
467 (run->direction == UBIDI_RTL) == (direction == CURSOR_LEFT); | |
468 return forward_motion ? FirstSelectionModelInsideRun(run) : | |
469 LastSelectionModelInsideRun(run); | |
470 } | |
471 | |
472 SelectionModel RenderTextHarfBuzz::AdjacentWordSelectionModel( | |
473 const SelectionModel& selection, | |
474 VisualCursorDirection direction) { | |
475 // TODO(ckocagil): This implementation currently matches RenderTextWin, but it | |
476 // should match the native behavior on other platforms. | |
477 if (obscured()) | |
478 return EdgeSelectionModel(direction); | |
479 | |
480 base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD); | |
481 bool success = iter.Init(); | |
482 DCHECK(success); | |
483 if (!success) | |
484 return selection; | |
485 | |
486 size_t pos; | |
487 if (direction == CURSOR_RIGHT) { | |
488 pos = std::min(selection.caret_pos() + 1, text().length()); | |
489 while (iter.Advance()) { | |
490 pos = iter.pos(); | |
491 if (iter.IsWord() && pos > selection.caret_pos()) | |
492 break; | |
493 } | |
494 } else { // direction == CURSOR_LEFT | |
495 // Notes: We always iterate words from the beginning. | |
496 // This is probably fast enough for our usage, but we may | |
497 // want to modify WordIterator so that it can start from the | |
498 // middle of string and advance backwards. | |
499 pos = std::max<int>(selection.caret_pos() - 1, 0); | |
500 while (iter.Advance()) { | |
501 if (iter.IsWord()) { | |
502 size_t begin = iter.pos() - iter.GetString().length(); | |
503 if (begin == selection.caret_pos()) { | |
504 // The cursor is at the beginning of a word. | |
505 // Move to previous word. | |
506 break; | |
507 } else if (iter.pos() >= selection.caret_pos()) { | |
508 // The cursor is in the middle or at the end of a word. | |
509 // Move to the top of current word. | |
510 pos = begin; | |
511 break; | |
512 } | |
513 pos = iter.pos() - iter.GetString().length(); | |
514 } | |
515 } | |
516 } | |
517 return SelectionModel(pos, CURSOR_FORWARD); | |
518 } | |
519 | |
520 Range RenderTextHarfBuzz::GetGlyphBounds(size_t index) { | |
521 const size_t run_index = | |
522 GetRunContainingCaret(SelectionModel(index, CURSOR_FORWARD)); | |
523 // Return edge bounds if the index is invalid or beyond the layout text size. | |
524 if (run_index >= runs_.size()) | |
525 return Range(GetStringSize().width()); | |
526 const size_t layout_index = TextIndexToLayoutIndex(index); | |
527 return Range(GetGlyphXBoundary(run_index, layout_index, false), | |
528 GetGlyphXBoundary(run_index, layout_index, true)); | |
529 } | |
530 | |
531 std::vector<Rect> RenderTextHarfBuzz::GetSubstringBounds(const Range& range) { | |
532 DCHECK(!needs_layout_); | |
533 DCHECK(Range(0, text().length()).Contains(range)); | |
534 Range layout_range(TextIndexToLayoutIndex(range.start()), | |
535 TextIndexToLayoutIndex(range.end())); | |
536 DCHECK(Range(0, GetLayoutText().length()).Contains(layout_range)); | |
537 | |
538 std::vector<Rect> rects; | |
539 if (layout_range.is_empty()) | |
540 return rects; | |
541 std::vector<Range> bounds; | |
542 | |
543 // Add a Range for each run/selection intersection. | |
544 // TODO(msw): The bounds should probably not always be leading the range ends. | |
545 for (size_t i = 0; i < runs_.size(); ++i) { | |
546 const internal::TextRunHarfBuzz* run = runs_[visual_to_logical_[i]]; | |
547 Range intersection = run->range.Intersect(layout_range); | |
548 if (intersection.IsValid()) { | |
549 DCHECK(!intersection.is_reversed()); | |
550 Range range_x(GetGlyphXBoundary(i, intersection.start(), false), | |
551 GetGlyphXBoundary(i, intersection.end(), false)); | |
552 if (range_x.is_empty()) | |
553 continue; | |
554 range_x = Range(range_x.GetMin(), range_x.GetMax()); | |
555 // Union this with the last range if they're adjacent. | |
556 DCHECK(bounds.empty() || bounds.back().GetMax() <= range_x.GetMin()); | |
557 if (!bounds.empty() && bounds.back().GetMax() == range_x.GetMin()) { | |
558 range_x = Range(bounds.back().GetMin(), range_x.GetMax()); | |
559 bounds.pop_back(); | |
560 } | |
561 bounds.push_back(range_x); | |
562 } | |
563 } | |
564 for (size_t i = 0; i < bounds.size(); ++i) { | |
565 std::vector<Rect> current_rects = TextBoundsToViewBounds(bounds[i]); | |
566 rects.insert(rects.end(), current_rects.begin(), current_rects.end()); | |
567 } | |
568 return rects; | |
569 } | |
570 | |
571 size_t RenderTextHarfBuzz::TextIndexToLayoutIndex(size_t index) const { | |
572 DCHECK_LE(index, text().length()); | |
573 ptrdiff_t i = obscured() ? UTF16IndexToOffset(text(), 0, index) : index; | |
574 CHECK_GE(i, 0); | |
575 // Clamp layout indices to the length of the text actually used for layout. | |
576 return std::min<size_t>(GetLayoutText().length(), i); | |
577 } | |
578 | |
579 size_t RenderTextHarfBuzz::LayoutIndexToTextIndex(size_t index) const { | |
580 if (!obscured()) | |
581 return index; | |
582 | |
583 DCHECK_LE(index, GetLayoutText().length()); | |
584 const size_t text_index = UTF16OffsetToIndex(text(), 0, index); | |
585 DCHECK_LE(text_index, text().length()); | |
586 return text_index; | |
587 } | |
588 | |
589 bool RenderTextHarfBuzz::IsValidCursorIndex(size_t index) { | |
590 if (index == 0 || index == text().length()) | |
591 return true; | |
592 if (!IsValidLogicalIndex(index)) | |
593 return false; | |
594 EnsureLayout(); | |
595 // Disallow indices amid multi-character graphemes by checking glyph bounds. | |
596 // These characters are not surrogate-pairs, but may yield a single glyph: | |
597 // \x0915\x093f - (ki) - one of many Devanagari biconsonantal conjuncts. | |
598 // \x0e08\x0e33 - (cho chan + sara am) - a Thai consonant and vowel pair. | |
599 return GetGlyphBounds(index) != GetGlyphBounds(index - 1); | |
600 } | |
601 | |
602 void RenderTextHarfBuzz::ResetLayout() { | |
603 needs_layout_ = true; | |
604 } | |
605 | |
606 void RenderTextHarfBuzz::EnsureLayout() { | |
607 if (needs_layout_) { | |
608 runs_.clear(); | |
609 | |
610 if (!GetLayoutText().empty()) { | |
611 ItemizeText(); | |
612 | |
613 for (size_t i = 0; i < runs_.size(); ++i) | |
614 ShapeRun(runs_[i]); | |
615 | |
616 // Precalculate run width information. | |
617 size_t preceding_run_widths = 0; | |
618 for (size_t i = 0; i < runs_.size(); ++i) { | |
619 internal::TextRunHarfBuzz* run = runs_[visual_to_logical_[i]]; | |
620 run->preceding_run_widths = preceding_run_widths; | |
621 preceding_run_widths += run->width; | |
622 } | |
623 } | |
624 | |
625 needs_layout_ = false; | |
626 std::vector<internal::Line> empty_lines; | |
627 set_lines(&empty_lines); | |
628 } | |
629 | |
630 if (lines().empty()) { | |
631 std::vector<internal::Line> lines; | |
632 lines.push_back(internal::Line()); | |
633 | |
634 int current_x = 0; | |
635 SkPaint paint; | |
636 | |
637 for (size_t i = 0; i < runs_.size(); ++i) { | |
638 const internal::TextRunHarfBuzz& run = *runs_[visual_to_logical_[i]]; | |
639 internal::LineSegment segment; | |
640 segment.x_range = Range(current_x, current_x + run.width); | |
641 segment.char_range = run.range; | |
642 segment.run = i; | |
643 lines[0].segments.push_back(segment); | |
644 | |
645 paint.setTypeface(run.skia_face.get()); | |
646 paint.setTextSize(run.font_size); | |
647 SkPaint::FontMetrics metrics; | |
648 paint.getFontMetrics(&metrics); | |
649 | |
650 lines[0].size.set_width(lines[0].size.width() + run.width); | |
651 lines[0].size.set_height(std::max(lines[0].size.height(), | |
652 SkScalarRoundToInt(metrics.fDescent - metrics.fAscent))); | |
653 lines[0].baseline = std::max(lines[0].baseline, | |
654 SkScalarRoundToInt(-metrics.fAscent)); | |
655 } | |
656 | |
657 set_lines(&lines); | |
658 } | |
659 } | |
660 | |
661 void RenderTextHarfBuzz::DrawVisualText(Canvas* canvas) { | |
662 DCHECK(!needs_layout_); | |
663 | |
664 int current_x = 0; | |
665 | |
666 internal::SkiaTextRenderer renderer(canvas); | |
667 ApplyFadeEffects(&renderer); | |
668 ApplyTextShadows(&renderer); | |
669 | |
670 #if defined(OS_WIN) | |
671 bool smoothing_enabled; | |
672 bool cleartype_enabled; | |
673 GetCachedFontSmoothingSettings(&smoothing_enabled, &cleartype_enabled); | |
674 // Note that |cleartype_enabled| corresponds to Skia's |enable_lcd_text|. | |
675 renderer.SetFontSmoothingSettings( | |
676 smoothing_enabled, cleartype_enabled && !background_is_transparent(), | |
677 smoothing_enabled /* subpixel_positioning */); | |
678 #endif | |
679 | |
680 ApplyCompositionAndSelectionStyles(); | |
681 | |
682 const Vector2d line_offset = GetLineOffset(0); | |
683 | |
684 for (size_t i = 0; i < runs_.size(); ++i) { | |
685 const internal::TextRunHarfBuzz& run = *runs_[visual_to_logical_[i]]; | |
686 renderer.SetTypeface(run.skia_face.get()); | |
687 renderer.SetTextSize(run.font_size); | |
688 | |
689 canvas->Save(); | |
690 Vector2d origin = line_offset + Vector2d(current_x, lines()[0].baseline); | |
691 canvas->Translate(origin); | |
692 | |
693 for (BreakList<SkColor>::const_iterator it = | |
694 colors().GetBreak(run.range.start()); | |
695 it != colors().breaks().end() && it->first < run.range.end(); | |
696 ++it) { | |
697 const Range intersection = colors().GetRange(it).Intersect(run.range); | |
698 const Range colored_glyphs = run.CharRangeToGlyphRange(intersection); | |
699 // The range may be empty if a portion of a multi-character grapheme is | |
700 // selected, yielding two colors for a single glyph. For now, this just | |
701 // paints the glyph with a single style, but it should paint it twice, | |
702 // clipped according to selection bounds. See http://crbug.com/366786 | |
703 if (colored_glyphs.is_empty()) | |
704 continue; | |
705 | |
706 renderer.SetForegroundColor(it->second); | |
707 renderer.DrawPosText(&run.positions[colored_glyphs.start()], | |
708 &run.glyphs[colored_glyphs.start()], | |
709 colored_glyphs.length()); | |
710 int width = (colored_glyphs.end() == run.glyph_count ? run.width : | |
711 run.positions[colored_glyphs.end()].x()) - | |
712 run.positions[colored_glyphs.start()].x(); | |
713 renderer.DrawDecorations(0, 0, width, run.underline, run.strike, | |
714 run.diagonal_strike); | |
715 } | |
716 | |
717 canvas->Restore(); | |
718 current_x += run.width; | |
719 } | |
720 | |
721 renderer.EndDiagonalStrike(); | |
722 | |
723 UndoCompositionAndSelectionStyles(); | |
724 } | |
725 | |
726 size_t RenderTextHarfBuzz::GetRunContainingCaret( | |
727 const SelectionModel& caret) const { | |
728 DCHECK(!needs_layout_); | |
729 size_t layout_position = TextIndexToLayoutIndex(caret.caret_pos()); | |
730 LogicalCursorDirection affinity = caret.caret_affinity(); | |
731 for (size_t run = 0; run < runs_.size(); ++run) { | |
732 if (RangeContainsCaret(runs_[run]->range, layout_position, affinity)) | |
733 return run; | |
734 } | |
735 return runs_.size(); | |
736 } | |
737 | |
738 size_t RenderTextHarfBuzz::GetRunContainingXCoord(int x, int* offset) const { | |
739 DCHECK(!needs_layout_); | |
740 if (x < 0) | |
741 return runs_.size(); | |
742 // Find the text run containing the argument point (assumed already offset). | |
743 int current_x = 0; | |
744 for (size_t i = 0; i < runs_.size(); ++i) { | |
745 size_t run = visual_to_logical_[i]; | |
746 current_x += runs_[run]->width; | |
747 if (x < current_x) { | |
748 *offset = x - (current_x - runs_[run]->width); | |
749 return run; | |
750 } | |
751 } | |
752 return runs_.size(); | |
753 } | |
754 | |
755 int RenderTextHarfBuzz::GetGlyphXBoundary(size_t run_index, | |
Alexei Svitkine (slow)
2014/05/21 07:39:02
Nit: Can this be a member method of TextRunHarfBuz
ckocagil
2014/05/21 14:34:39
Done.
| |
756 size_t text_index, | |
757 bool trailing) { | |
758 const internal::TextRunHarfBuzz& run = *runs_[run_index]; | |
759 int x = run.preceding_run_widths; | |
760 | |
761 Range glyph_range; | |
762 if (text_index == run.range.end()) { | |
763 trailing = true; | |
764 glyph_range = run.direction == UBIDI_LTR ? | |
765 Range(run.glyph_count - 1, run.glyph_count) : Range(0, 1); | |
766 } else { | |
767 glyph_range = run.CharRangeToGlyphRange(Range(text_index, text_index + 1)); | |
768 } | |
769 const int trailing_step = trailing ? 1 : 0; | |
770 const size_t glyph_pos = glyph_range.start() + | |
771 (run.direction == UBIDI_LTR ? trailing_step : (1 - trailing_step)); | |
772 x += glyph_pos < run.glyph_count ? | |
773 SkScalarRoundToInt(run.positions[glyph_pos].x()) : run.width; | |
774 return x; | |
775 } | |
776 | |
777 SelectionModel RenderTextHarfBuzz::FirstSelectionModelInsideRun( | |
778 const internal::TextRunHarfBuzz* run) { | |
779 size_t position = LayoutIndexToTextIndex(run->range.start()); | |
780 position = IndexOfAdjacentGrapheme(position, CURSOR_FORWARD); | |
781 return SelectionModel(position, CURSOR_BACKWARD); | |
782 } | |
783 | |
784 SelectionModel RenderTextHarfBuzz::LastSelectionModelInsideRun( | |
785 const internal::TextRunHarfBuzz* run) { | |
786 size_t position = LayoutIndexToTextIndex(run->range.end()); | |
787 position = IndexOfAdjacentGrapheme(position, CURSOR_BACKWARD); | |
788 return SelectionModel(position, CURSOR_FORWARD); | |
789 } | |
790 | |
791 void RenderTextHarfBuzz::ItemizeText() { | |
792 const base::string16& text = GetLayoutText(); | |
793 const bool is_rtl = GetTextDirection() == base::i18n::RIGHT_TO_LEFT; | |
794 DCHECK_NE(0U, text.length()); | |
795 | |
796 bool fake_runs = false; | |
Alexei Svitkine (slow)
2014/05/21 07:39:02
Nit: Add a comment about why we have this.
ckocagil
2014/05/21 14:34:39
Done.
| |
797 UErrorCode result = U_ZERO_ERROR; | |
798 | |
799 UBiDi* line = ubidi_openSized(text.length(), 0, &result); | |
800 if (U_FAILURE(result)) { | |
801 NOTREACHED(); | |
802 fake_runs = true; | |
803 } else { | |
804 ubidi_setPara(line, text.c_str(), text.length(), | |
805 is_rtl ? UBIDI_DEFAULT_RTL : UBIDI_DEFAULT_LTR, NULL, | |
806 &result); | |
807 if (U_FAILURE(result)) { | |
808 NOTREACHED(); | |
809 fake_runs = true; | |
810 } | |
811 } | |
812 | |
813 // Temporarily apply composition underlines and selection colors. | |
814 ApplyCompositionAndSelectionStyles(); | |
815 | |
816 // Build the list of runs from the script items and ranged styles. Use an | |
817 // empty color BreakList to avoid breaking runs at color boundaries. | |
818 BreakList<SkColor> empty_colors; | |
819 empty_colors.SetMax(text.length()); | |
820 internal::StyleIterator style(empty_colors, styles()); | |
821 | |
822 for (size_t run_break = 0; run_break < text.length();) { | |
823 internal::TextRunHarfBuzz* run = new internal::TextRunHarfBuzz; | |
824 run->range.set_start(run_break); | |
825 run->font_style = (style.style(BOLD) ? Font::BOLD : 0) | | |
826 (style.style(ITALIC) ? Font::ITALIC : 0); | |
827 run->strike = style.style(STRIKE); | |
828 run->diagonal_strike = style.style(DIAGONAL_STRIKE); | |
829 run->underline = style.style(UNDERLINE); | |
830 | |
831 if (fake_runs) { | |
832 run_break = text.length(); | |
833 } else { | |
834 int32 script_item_break = 0; | |
835 ubidi_getLogicalRun(line, run_break, &script_item_break, &run->level); | |
836 // Find the length and script of this script run. | |
837 script_item_break = ScriptInterval(text, run_break, | |
838 script_item_break - run_break, &run->script) + run_break; | |
839 | |
840 // Find the next break and advance the iterators as needed. | |
841 run_break = std::min(static_cast<size_t>(script_item_break), | |
842 TextIndexToLayoutIndex(style.GetRange().end())); | |
843 | |
844 // Break runs adjacent to character substrings in certain code blocks. | |
845 // This avoids using their fallback fonts for more characters than needed, | |
846 // in cases like "\x25B6 Media Title", etc. http://crbug.com/278913 | |
847 if (run_break > run->range.start()) { | |
848 const size_t run_start = run->range.start(); | |
849 const int32 run_length = static_cast<int32>(run_break - run_start); | |
850 base::i18n::UTF16CharIterator iter(text.c_str() + run_start, | |
851 run_length); | |
852 const UBlockCode first_block_code = ublock_getCode(iter.get()); | |
853 const bool first_block_unusual = IsUnusualBlockCode(first_block_code); | |
854 while (iter.Advance() && iter.array_pos() < run_length) { | |
855 const UBlockCode current_block_code = ublock_getCode(iter.get()); | |
856 if (current_block_code != first_block_code && | |
857 (first_block_unusual || IsUnusualBlockCode(current_block_code))) { | |
858 run_break = run_start + iter.array_pos(); | |
859 break; | |
860 } | |
861 } | |
862 } | |
863 } | |
864 | |
865 DCHECK(IsValidCodePointIndex(text, run_break)); | |
866 style.UpdatePosition(LayoutIndexToTextIndex(run_break)); | |
867 run->range.set_end(run_break); | |
868 const UChar* uchar_start = ubidi_getText(line); | |
869 // TODO(ckocagil): Add |ubidi_getBaseDirection| to i18n::BiDiLineIterator | |
870 // and remove the bare ICU use here. | |
871 run->direction = ubidi_getBaseDirection(uchar_start + run->range.start(), | |
872 run->range.length()); | |
873 if (run->direction == UBIDI_NEUTRAL) | |
874 run->direction = is_rtl ? UBIDI_RTL : UBIDI_LTR; | |
875 runs_.push_back(run); | |
876 } | |
877 | |
878 ubidi_close(line); | |
879 | |
880 // Undo the temporarily applied composition underlines and selection colors. | |
881 UndoCompositionAndSelectionStyles(); | |
882 | |
883 const size_t num_runs = runs_.size(); | |
884 scoped_ptr<UBiDiLevel[]> levels(new UBiDiLevel[num_runs]); | |
Alexei Svitkine (slow)
2014/05/21 07:39:02
Nit: Can this be a std::vector<UBiDiLevel> instead
ckocagil
2014/05/21 14:34:39
Done.
| |
885 for (size_t i = 0; i < num_runs; ++i) | |
886 levels[i] = runs_[i]->level; | |
887 visual_to_logical_.resize(num_runs); | |
888 ubidi_reorderVisual(levels.get(), num_runs, &visual_to_logical_[0]); | |
889 logical_to_visual_.resize(num_runs); | |
890 ubidi_reorderLogical(levels.get(), num_runs, &logical_to_visual_[0]); | |
891 } | |
892 | |
893 void RenderTextHarfBuzz::ShapeRun(internal::TextRunHarfBuzz* run) { | |
894 const base::string16& text = GetLayoutText(); | |
895 // TODO(ckocagil|yukishiino): Implement font fallback. | |
896 const Font& primary_font = font_list().GetPrimaryFont(); | |
897 run->skia_face = internal::CreateSkiaTypeface(primary_font.GetFontName(), | |
898 run->font_style); | |
899 run->font_size = primary_font.GetFontSize(); | |
900 | |
901 hb_font_t* harfbuzz_font = CreateHarfBuzzFont(run->skia_face.get(), | |
902 run->font_size); | |
903 | |
904 // Create a HarfBuzz buffer and add the string to be shaped. The HarfBuzz | |
905 // buffer holds our text, run information to be used by the shaping engine, | |
906 // and the resulting glyph data. | |
907 hb_buffer_t* buffer = hb_buffer_create(); | |
908 hb_buffer_add_utf16(buffer, reinterpret_cast<const uint16*>(text.c_str()), | |
909 text.length(), run->range.start(), run->range.length()); | |
910 hb_buffer_set_script(buffer, hb_icu_script_to_script(run->script)); | |
911 hb_buffer_set_direction(buffer, | |
912 run->direction == UBIDI_LTR ? HB_DIRECTION_LTR : HB_DIRECTION_RTL); | |
913 // TODO(ckocagil): Should we determine the actual language? | |
914 hb_buffer_set_language(buffer, hb_language_get_default()); | |
915 | |
916 // Shape the text. | |
917 hb_shape(harfbuzz_font, buffer, NULL, 0); | |
918 | |
919 // Populate the run fields with the resulting glyph data in the buffer. | |
920 hb_glyph_info_t* infos = hb_buffer_get_glyph_infos(buffer, &run->glyph_count); | |
921 hb_glyph_position_t* hb_positions = hb_buffer_get_glyph_positions(buffer, | |
922 NULL); | |
923 run->glyphs.reset(new uint16[run->glyph_count]); | |
924 run->glyph_to_char.reset(new uint32[run->glyph_count]); | |
925 run->positions.reset(new SkPoint[run->glyph_count]); | |
926 for (size_t i = 0; i < run->glyph_count; ++i) { | |
927 run->glyphs[i] = infos[i].codepoint; | |
928 run->glyph_to_char[i] = infos[i].cluster; | |
929 const int x_offset = | |
930 SkScalarRoundToInt(SkFixedToScalar(hb_positions[i].x_offset)); | |
931 const int y_offset = | |
932 SkScalarRoundToInt(SkFixedToScalar(hb_positions[i].y_offset)); | |
933 run->positions[i].set(run->width + x_offset, y_offset); | |
934 run->width += | |
935 SkScalarRoundToInt(SkFixedToScalar(hb_positions[i].x_advance)); | |
936 } | |
937 | |
938 hb_buffer_destroy(buffer); | |
939 hb_font_destroy(harfbuzz_font); | |
940 } | |
941 | |
942 } // namespace gfx | |
OLD | NEW |