1// Copyright (c) 2012 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/canvas.h"
6
7#include "base/i18n/rtl.h"
8#include "base/logging.h"
9#include "base/memory/scoped_ptr.h"
10#include "ui/gfx/font_list.h"
11#include "ui/gfx/insets.h"
12#include "ui/gfx/range/range.h"
13#include "ui/gfx/rect.h"
14#include "ui/gfx/render_text.h"
15#include "ui/gfx/shadow_value.h"
16#include "ui/gfx/text_elider.h"
17#include "ui/gfx/text_utils.h"
18
19namespace gfx {
20
21namespace {
22
23#if defined(OS_WIN)
24// If necessary, wraps |text| with RTL/LTR directionality characters based on
25// |flags| and |text| content.
26// Returns true if the text will be rendered right-to-left.
27// TODO(msw): Nix this, now that RenderTextWin supports directionality directly.
28bool AdjustStringDirection(int flags, base::string16* text) {
29  // TODO(msw): FORCE_LTR_DIRECTIONALITY does not work for RTL text now.
30
31  // If the string is empty or LTR was forced, simply return false since the
32  // default RenderText directionality is already LTR.
33  if (text->empty() || (flags & Canvas::FORCE_LTR_DIRECTIONALITY))
34    return false;
35
36  // If RTL is forced, apply it to the string.
37  if (flags & Canvas::FORCE_RTL_DIRECTIONALITY) {
38    base::i18n::WrapStringWithRTLFormatting(text);
39    return true;
40  }
41
42  // If a direction wasn't forced but the UI language is RTL and there were
43  // strong RTL characters, ensure RTL is applied.
44  if (base::i18n::IsRTL() && base::i18n::StringContainsStrongRTLChars(*text)) {
45    base::i18n::WrapStringWithRTLFormatting(text);
46    return true;
47  }
48
49  // In the default case, the string should be rendered as LTR. RenderText's
50  // default directionality is LTR, so the text doesn't need to be wrapped.
51  // Note that individual runs within the string may still be rendered RTL
52  // (which will be the case for RTL text under non-RTL locales, since under RTL
53  // locales it will be handled by the if statement above).
54  return false;
55}
56#endif  // defined(OS_WIN)
57
58// Checks each pixel immediately adjacent to the given pixel in the bitmap. If
59// any of them are not the halo color, returns true. This defines the halo of
60// pixels that will appear around the text. Note that we have to check each
61// pixel against both the halo color and transparent since
62// |DrawStringRectWithHalo| will modify the bitmap as it goes, and cleared
63// pixels shouldn't count as changed.
64bool PixelShouldGetHalo(const SkBitmap& bitmap,
65                        int x, int y,
66                        SkColor halo_color) {
67  if (x > 0 &&
68      *bitmap.getAddr32(x - 1, y) != halo_color &&
69      *bitmap.getAddr32(x - 1, y) != 0)
70    return true;  // Touched pixel to the left.
71  if (x < bitmap.width() - 1 &&
72      *bitmap.getAddr32(x + 1, y) != halo_color &&
73      *bitmap.getAddr32(x + 1, y) != 0)
74    return true;  // Touched pixel to the right.
75  if (y > 0 &&
76      *bitmap.getAddr32(x, y - 1) != halo_color &&
77      *bitmap.getAddr32(x, y - 1) != 0)
78    return true;  // Touched pixel above.
79  if (y < bitmap.height() - 1 &&
80      *bitmap.getAddr32(x, y + 1) != halo_color &&
81      *bitmap.getAddr32(x, y + 1) != 0)
82    return true;  // Touched pixel below.
83  return false;
84}
85
86// Strips accelerator character prefixes in |text| if needed, based on |flags|.
87// Returns a range in |text| to underline or Range::InvalidRange() if
88// underlining is not needed.
89Range StripAcceleratorChars(int flags, base::string16* text) {
90  if (flags & (Canvas::SHOW_PREFIX | Canvas::HIDE_PREFIX)) {
91    int char_pos = -1;
92    int char_span = 0;
93    *text = RemoveAcceleratorChar(*text, '&', &char_pos, &char_span);
94    if ((flags & Canvas::SHOW_PREFIX) && char_pos != -1)
95      return Range(char_pos, char_pos + char_span);
96  }
97  return Range::InvalidRange();
98}
99
100// Elides |text| and adjusts |range| appropriately. If eliding causes |range|
101// to no longer point to the same character in |text|, |range| is made invalid.
102void ElideTextAndAdjustRange(const FontList& font_list,
103                             int width,
104                             base::string16* text,
105                             Range* range) {
106  const base::char16 start_char =
107      (range->IsValid() ? text->at(range->start()) : 0);
108  *text = ElideText(*text, font_list, width, ELIDE_TAIL);
109  if (!range->IsValid())
110    return;
111  if (range->start() >= text->length() ||
112      text->at(range->start()) != start_char) {
113    *range = Range::InvalidRange();
114  }
115}
116
117// Updates |render_text| from the specified parameters.
118void UpdateRenderText(const Rect& rect,
119                      const base::string16& text,
120                      const FontList& font_list,
121                      int flags,
122                      SkColor color,
123                      RenderText* render_text) {
124  render_text->SetFontList(font_list);
125  render_text->SetText(text);
126  render_text->SetCursorEnabled(false);
127  render_text->SetDisplayRect(rect);
128
129  // Set the text alignment explicitly based on the directionality of the UI,
130  // if not specified.
131  if (!(flags & (Canvas::TEXT_ALIGN_CENTER |
132                 Canvas::TEXT_ALIGN_RIGHT |
133                 Canvas::TEXT_ALIGN_LEFT))) {
134    flags |= Canvas::DefaultCanvasTextAlignment();
135  }
136
137  if (flags & Canvas::TEXT_ALIGN_RIGHT)
138    render_text->SetHorizontalAlignment(ALIGN_RIGHT);
139  else if (flags & Canvas::TEXT_ALIGN_CENTER)
140    render_text->SetHorizontalAlignment(ALIGN_CENTER);
141  else
142    render_text->SetHorizontalAlignment(ALIGN_LEFT);
143
144  if (flags & Canvas::NO_SUBPIXEL_RENDERING)
145    render_text->set_background_is_transparent(true);
146
147  render_text->SetColor(color);
148  const int font_style = font_list.GetFontStyle();
149  render_text->SetStyle(BOLD, (font_style & Font::BOLD) != 0);
150  render_text->SetStyle(ITALIC, (font_style & Font::ITALIC) != 0);
151  render_text->SetStyle(UNDERLINE, (font_style & Font::UNDERLINE) != 0);
152}
153
154}  // namespace
155
156// static
157void Canvas::SizeStringFloat(const base::string16& text,
158                             const FontList& font_list,
159                             float* width, float* height,
160                             int line_height,
161                             int flags) {
162  DCHECK_GE(*width, 0);
163  DCHECK_GE(*height, 0);
164
165  base::string16 adjusted_text = text;
166#if defined(OS_WIN)
167  AdjustStringDirection(flags, &adjusted_text);
168#endif
169
170  if ((flags & MULTI_LINE) && *width != 0) {
171    WordWrapBehavior wrap_behavior = TRUNCATE_LONG_WORDS;
172    if (flags & CHARACTER_BREAK)
173      wrap_behavior = WRAP_LONG_WORDS;
174    else if (!(flags & NO_ELLIPSIS))
175      wrap_behavior = ELIDE_LONG_WORDS;
176
177    Rect rect(*width, INT_MAX);
178    std::vector<base::string16> strings;
179    ElideRectangleText(adjusted_text, font_list, rect.width(), rect.height(),
180                       wrap_behavior, &strings);
181    scoped_ptr<RenderText> render_text(RenderText::CreateInstance());
182    UpdateRenderText(rect, base::string16(), font_list, flags, 0,
183                     render_text.get());
184
185    float h = 0;
186    float w = 0;
187    for (size_t i = 0; i < strings.size(); ++i) {
188      StripAcceleratorChars(flags, &strings[i]);
189      render_text->SetText(strings[i]);
190      const SizeF& string_size = render_text->GetStringSizeF();
191      w = std::max(w, string_size.width());
192      h += (i > 0 && line_height > 0) ? line_height : string_size.height();
193    }
194    *width = w;
195    *height = h;
196  } else {
197    // If the string is too long, the call by |RenderTextWin| to |ScriptShape()|
198    // will inexplicably fail with result E_INVALIDARG. Guard against this.
199    const size_t kMaxRenderTextLength = 5000;
200    if (adjusted_text.length() >= kMaxRenderTextLength) {
201      *width = font_list.GetExpectedTextWidth(adjusted_text.length());
202      *height = font_list.GetHeight();
203    } else {
204      scoped_ptr<RenderText> render_text(RenderText::CreateInstance());
205      Rect rect(*width, *height);
206      StripAcceleratorChars(flags, &adjusted_text);
207      UpdateRenderText(rect, adjusted_text, font_list, flags, 0,
208                       render_text.get());
209      const SizeF& string_size = render_text->GetStringSizeF();
210      *width = string_size.width();
211      *height = string_size.height();
212    }
213  }
214}
215
216void Canvas::DrawStringRectWithShadows(const base::string16& text,
217                                       const FontList& font_list,
218                                       SkColor color,
219                                       const Rect& text_bounds,
220                                       int line_height,
221                                       int flags,
222                                       const ShadowValues& shadows) {
223  if (!IntersectsClipRect(text_bounds))
224    return;
225
226  Rect clip_rect(text_bounds);
227  clip_rect.Inset(ShadowValue::GetMargin(shadows));
228
229  canvas_->save();
230  ClipRect(clip_rect);
231
232  Rect rect(text_bounds);
233  base::string16 adjusted_text = text;
234
235#if defined(OS_WIN)
236  AdjustStringDirection(flags, &adjusted_text);
237#endif
238
239  scoped_ptr<RenderText> render_text(RenderText::CreateInstance());
240  render_text->set_shadows(shadows);
241
242  if (flags & MULTI_LINE) {
243    WordWrapBehavior wrap_behavior = IGNORE_LONG_WORDS;
244    if (flags & CHARACTER_BREAK)
245      wrap_behavior = WRAP_LONG_WORDS;
246    else if (!(flags & NO_ELLIPSIS))
247      wrap_behavior = ELIDE_LONG_WORDS;
248
249    std::vector<base::string16> strings;
250    ElideRectangleText(adjusted_text, font_list, text_bounds.width(),
251                       text_bounds.height(), wrap_behavior, &strings);
252
253    for (size_t i = 0; i < strings.size(); i++) {
254      Range range = StripAcceleratorChars(flags, &strings[i]);
255      UpdateRenderText(rect, strings[i], font_list, flags, color,
256                       render_text.get());
257      int line_padding = 0;
258      if (line_height > 0)
259        line_padding = line_height - render_text->GetStringSize().height();
260      else
261        line_height = render_text->GetStringSize().height();
262
263      // TODO(msw|asvitkine): Center Windows multi-line text: crbug.com/107357
264#if !defined(OS_WIN)
265      if (i == 0) {
266        // TODO(msw|asvitkine): Support multi-line text with varied heights.
267        const int text_height = strings.size() * line_height - line_padding;
268        rect += Vector2d(0, (text_bounds.height() - text_height) / 2);
269      }
270#endif
271
272      rect.set_height(line_height - line_padding);
273
274      if (range.IsValid())
275        render_text->ApplyStyle(UNDERLINE, true, range);
276      render_text->SetDisplayRect(rect);
277      render_text->Draw(this);
278      rect += Vector2d(0, line_height);
279    }
280  } else {
281    Range range = StripAcceleratorChars(flags, &adjusted_text);
282    bool elide_text = ((flags & NO_ELLIPSIS) == 0);
283
284#if defined(OS_LINUX)
285    // On Linux, eliding really means fading the end of the string. But only
286    // for LTR text. RTL text is still elided (on the left) with "...".
287    if (elide_text) {
288      render_text->SetText(adjusted_text);
289      if (render_text->GetTextDirection() == base::i18n::LEFT_TO_RIGHT) {
290        render_text->SetElideBehavior(FADE_TAIL);
291        elide_text = false;
292      }
293    }
294#endif
295
296    if (elide_text) {
297      ElideTextAndAdjustRange(font_list, text_bounds.width(), &adjusted_text,
298                              &range);
299    }
300
301    UpdateRenderText(rect, adjusted_text, font_list, flags, color,
302                     render_text.get());
303    if (range.IsValid())
304      render_text->ApplyStyle(UNDERLINE, true, range);
305    render_text->Draw(this);
306  }
307
308  canvas_->restore();
309}
310
311void Canvas::DrawStringRectWithHalo(const base::string16& text,
312                                    const FontList& font_list,
313                                    SkColor text_color,
314                                    SkColor halo_color_in,
315                                    const Rect& display_rect,
316                                    int flags) {
317  // Some callers will have semitransparent halo colors, which we don't handle
318  // (since the resulting image can have 1-bit transparency only).
319  SkColor halo_color = SkColorSetA(halo_color_in, 0xFF);
320
321  // Create a temporary buffer filled with the halo color. It must leave room
322  // for the 1-pixel border around the text.
323  Size size(display_rect.width() + 2, display_rect.height() + 2);
324  Canvas text_canvas(size, image_scale(), false);
325  SkPaint bkgnd_paint;
326  bkgnd_paint.setColor(halo_color);
327  text_canvas.DrawRect(Rect(size), bkgnd_paint);
328
329  // Draw the text into the temporary buffer. This will have correct
330  // ClearType since the background color is the same as the halo color.
331  text_canvas.DrawStringRectWithFlags(
332      text, font_list, text_color,
333      Rect(1, 1, display_rect.width(), display_rect.height()), flags);
334
335  uint32_t halo_premul = SkPreMultiplyColor(halo_color);
336  SkBitmap& text_bitmap = const_cast<SkBitmap&>(
337      skia::GetTopDevice(*text_canvas.sk_canvas())->accessBitmap(true));
338
339  for (int cur_y = 0; cur_y < text_bitmap.height(); cur_y++) {
340    uint32_t* text_row = text_bitmap.getAddr32(0, cur_y);
341    for (int cur_x = 0; cur_x < text_bitmap.width(); cur_x++) {
342      if (text_row[cur_x] == halo_premul) {
343        // This pixel was not touched by the text routines. See if it borders
344        // a touched pixel in any of the 4 directions (not diagonally).
345        if (!PixelShouldGetHalo(text_bitmap, cur_x, cur_y, halo_premul))
346          text_row[cur_x] = 0;  // Make transparent.
347      } else {
348        text_row[cur_x] |= 0xff << SK_A32_SHIFT;  // Make opaque.
349      }
350    }
351  }
352
353  // Draw the halo bitmap with blur.
354  ImageSkia text_image = ImageSkia(ImageSkiaRep(text_bitmap,
355      text_canvas.image_scale()));
356  DrawImageInt(text_image, display_rect.x() - 1, display_rect.y() - 1);
357}
358
359void Canvas::DrawFadedString(const base::string16& text,
360                             const FontList& font_list,
361                             SkColor color,
362                             const Rect& display_rect,
363                             int flags) {
364  // If the whole string fits in the destination then just draw it directly.
365  if (GetStringWidth(text, font_list) <= display_rect.width()) {
366    DrawStringRectWithFlags(text, font_list, color, display_rect, flags);
367    return;
368  }
369
370  // Align with forced content directionality, overriding alignment flags.
371  if (flags & FORCE_RTL_DIRECTIONALITY) {
372    flags &= ~(TEXT_ALIGN_CENTER | TEXT_ALIGN_LEFT);
373    flags |= TEXT_ALIGN_RIGHT;
374  } else if (flags & FORCE_LTR_DIRECTIONALITY) {
375    flags &= ~(TEXT_ALIGN_CENTER | TEXT_ALIGN_RIGHT);
376    flags |= TEXT_ALIGN_LEFT;
377  } else if (!(flags & TEXT_ALIGN_LEFT) && !(flags & TEXT_ALIGN_RIGHT)) {
378    // Also align with content directionality instead of fading both ends.
379    flags &= ~TEXT_ALIGN_CENTER;
380    const bool is_rtl = base::i18n::GetFirstStrongCharacterDirection(text) ==
381                        base::i18n::RIGHT_TO_LEFT;
382    flags |= is_rtl ? TEXT_ALIGN_RIGHT : TEXT_ALIGN_LEFT;
383  }
384  flags |= NO_ELLIPSIS;
385
386  scoped_ptr<RenderText> render_text(RenderText::CreateInstance());
387  Rect rect = display_rect;
388  UpdateRenderText(rect, text, font_list, flags, color, render_text.get());
389  render_text->SetElideBehavior(FADE_TAIL);
390
391  canvas_->save();
392  ClipRect(display_rect);
393  render_text->Draw(this);
394  canvas_->restore();
395}
396
397}  // namespace gfx
398