Home | History | Annotate | Download | only in gfx
      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 
     19 namespace gfx {
     20 
     21 namespace {
     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.
     28 bool 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.
     64 bool 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 gfx::Range::InvalidRange() if
     88 // underlining is not needed.
     89 Range 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.
    102 void 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 = gfx::ElideText(*text, font_list, width, gfx::ELIDE_AT_END);
    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.
    118 void 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 
    128   Rect display_rect = rect;
    129   display_rect.set_height(font_list.GetHeight());
    130   render_text->SetDisplayRect(display_rect);
    131 
    132   // Set the text alignment explicitly based on the directionality of the UI,
    133   // if not specified.
    134   if (!(flags & (Canvas::TEXT_ALIGN_CENTER |
    135                  Canvas::TEXT_ALIGN_RIGHT |
    136                  Canvas::TEXT_ALIGN_LEFT))) {
    137     flags |= Canvas::DefaultCanvasTextAlignment();
    138   }
    139 
    140   if (flags & Canvas::TEXT_ALIGN_RIGHT)
    141     render_text->SetHorizontalAlignment(ALIGN_RIGHT);
    142   else if (flags & Canvas::TEXT_ALIGN_CENTER)
    143     render_text->SetHorizontalAlignment(ALIGN_CENTER);
    144   else
    145     render_text->SetHorizontalAlignment(ALIGN_LEFT);
    146 
    147   if (flags & Canvas::NO_SUBPIXEL_RENDERING)
    148     render_text->set_background_is_transparent(true);
    149 
    150   render_text->SetColor(color);
    151   const int font_style = font_list.GetFontStyle();
    152   render_text->SetStyle(BOLD, (font_style & Font::BOLD) != 0);
    153   render_text->SetStyle(ITALIC, (font_style & Font::ITALIC) != 0);
    154   render_text->SetStyle(UNDERLINE, (font_style & Font::UNDERLINE) != 0);
    155 }
    156 
    157 }  // namespace
    158 
    159 // static
    160 void Canvas::SizeStringFloat(const base::string16& text,
    161                              const FontList& font_list,
    162                              float* width, float* height,
    163                              int line_height,
    164                              int flags) {
    165   DCHECK_GE(*width, 0);
    166   DCHECK_GE(*height, 0);
    167 
    168   base::string16 adjusted_text = text;
    169 #if defined(OS_WIN)
    170   AdjustStringDirection(flags, &adjusted_text);
    171 #endif
    172 
    173   if ((flags & MULTI_LINE) && *width != 0) {
    174     gfx::WordWrapBehavior wrap_behavior = gfx::TRUNCATE_LONG_WORDS;
    175     if (flags & CHARACTER_BREAK)
    176       wrap_behavior = gfx::WRAP_LONG_WORDS;
    177     else if (!(flags & NO_ELLIPSIS))
    178       wrap_behavior = gfx::ELIDE_LONG_WORDS;
    179 
    180     Rect rect(*width, INT_MAX);
    181     std::vector<base::string16> strings;
    182     gfx::ElideRectangleText(adjusted_text, font_list,
    183                            rect.width(), rect.height(),
    184                            wrap_behavior, &strings);
    185     scoped_ptr<RenderText> render_text(RenderText::CreateInstance());
    186     UpdateRenderText(rect, base::string16(), font_list, flags, 0,
    187                      render_text.get());
    188 
    189     float h = 0;
    190     float w = 0;
    191     for (size_t i = 0; i < strings.size(); ++i) {
    192       StripAcceleratorChars(flags, &strings[i]);
    193       render_text->SetText(strings[i]);
    194       const SizeF& string_size = render_text->GetStringSizeF();
    195       w = std::max(w, string_size.width());
    196       h += (i > 0 && line_height > 0) ? line_height : string_size.height();
    197     }
    198     *width = w;
    199     *height = h;
    200   } else {
    201     // If the string is too long, the call by |RenderTextWin| to |ScriptShape()|
    202     // will inexplicably fail with result E_INVALIDARG. Guard against this.
    203     const size_t kMaxRenderTextLength = 5000;
    204     if (adjusted_text.length() >= kMaxRenderTextLength) {
    205       *width = font_list.GetExpectedTextWidth(adjusted_text.length());
    206       *height = font_list.GetHeight();
    207     } else {
    208       scoped_ptr<RenderText> render_text(RenderText::CreateInstance());
    209       Rect rect(*width, *height);
    210       StripAcceleratorChars(flags, &adjusted_text);
    211       UpdateRenderText(rect, adjusted_text, font_list, flags, 0,
    212                        render_text.get());
    213       const SizeF& string_size = render_text->GetStringSizeF();
    214       *width = string_size.width();
    215       *height = string_size.height();
    216     }
    217   }
    218 }
    219 
    220 void Canvas::DrawStringRectWithShadows(const base::string16& text,
    221                                        const FontList& font_list,
    222                                        SkColor color,
    223                                        const Rect& text_bounds,
    224                                        int line_height,
    225                                        int flags,
    226                                        const ShadowValues& shadows) {
    227   if (!IntersectsClipRect(text_bounds))
    228     return;
    229 
    230   Rect clip_rect(text_bounds);
    231   clip_rect.Inset(ShadowValue::GetMargin(shadows));
    232 
    233   canvas_->save(SkCanvas::kClip_SaveFlag);
    234   ClipRect(clip_rect);
    235 
    236   Rect rect(text_bounds);
    237   base::string16 adjusted_text = text;
    238 
    239 #if defined(OS_WIN)
    240   AdjustStringDirection(flags, &adjusted_text);
    241 #endif
    242 
    243   scoped_ptr<RenderText> render_text(RenderText::CreateInstance());
    244   render_text->SetTextShadows(shadows);
    245 
    246   if (flags & MULTI_LINE) {
    247     gfx::WordWrapBehavior wrap_behavior = gfx::IGNORE_LONG_WORDS;
    248     if (flags & CHARACTER_BREAK)
    249       wrap_behavior = gfx::WRAP_LONG_WORDS;
    250     else if (!(flags & NO_ELLIPSIS))
    251       wrap_behavior = gfx::ELIDE_LONG_WORDS;
    252 
    253     std::vector<base::string16> strings;
    254     gfx::ElideRectangleText(adjusted_text,
    255                            font_list,
    256                            text_bounds.width(), text_bounds.height(),
    257                            wrap_behavior,
    258                            &strings);
    259 
    260     for (size_t i = 0; i < strings.size(); i++) {
    261       Range range = StripAcceleratorChars(flags, &strings[i]);
    262       UpdateRenderText(rect, strings[i], font_list, flags, color,
    263                        render_text.get());
    264       int line_padding = 0;
    265       if (line_height > 0)
    266         line_padding = line_height - render_text->GetStringSize().height();
    267       else
    268         line_height = render_text->GetStringSize().height();
    269 
    270       // TODO(msw|asvitkine): Center Windows multi-line text: crbug.com/107357
    271 #if !defined(OS_WIN)
    272       if (i == 0) {
    273         // TODO(msw|asvitkine): Support multi-line text with varied heights.
    274         const int text_height = strings.size() * line_height - line_padding;
    275         rect += Vector2d(0, (text_bounds.height() - text_height) / 2);
    276       }
    277 #endif
    278 
    279       rect.set_height(line_height - line_padding);
    280 
    281       if (range.IsValid())
    282         render_text->ApplyStyle(UNDERLINE, true, range);
    283       render_text->SetDisplayRect(rect);
    284       render_text->Draw(this);
    285       rect += Vector2d(0, line_height);
    286     }
    287   } else {
    288     Range range = StripAcceleratorChars(flags, &adjusted_text);
    289     bool elide_text = ((flags & NO_ELLIPSIS) == 0);
    290 
    291 #if defined(OS_LINUX)
    292     // On Linux, eliding really means fading the end of the string. But only
    293     // for LTR text. RTL text is still elided (on the left) with "...".
    294     if (elide_text) {
    295       render_text->SetText(adjusted_text);
    296       if (render_text->GetTextDirection() == base::i18n::LEFT_TO_RIGHT) {
    297         render_text->set_fade_tail(true);
    298         elide_text = false;
    299       }
    300     }
    301 #endif
    302 
    303     if (elide_text) {
    304       ElideTextAndAdjustRange(font_list,
    305                               text_bounds.width(),
    306                               &adjusted_text,
    307                               &range);
    308     }
    309 
    310     UpdateRenderText(rect, adjusted_text, font_list, flags, color,
    311                      render_text.get());
    312 
    313     const int text_height = render_text->GetStringSize().height();
    314     // Center the text vertically.
    315     rect += Vector2d(0, (text_bounds.height() - text_height) / 2);
    316     rect.set_height(text_height);
    317     render_text->SetDisplayRect(rect);
    318     if (range.IsValid())
    319       render_text->ApplyStyle(UNDERLINE, true, range);
    320     render_text->Draw(this);
    321   }
    322 
    323   canvas_->restore();
    324 }
    325 
    326 void Canvas::DrawStringRectWithHalo(const base::string16& text,
    327                                     const FontList& font_list,
    328                                     SkColor text_color,
    329                                     SkColor halo_color_in,
    330                                     const Rect& display_rect,
    331                                     int flags) {
    332   // Some callers will have semitransparent halo colors, which we don't handle
    333   // (since the resulting image can have 1-bit transparency only).
    334   SkColor halo_color = SkColorSetA(halo_color_in, 0xFF);
    335 
    336   // Create a temporary buffer filled with the halo color. It must leave room
    337   // for the 1-pixel border around the text.
    338   Size size(display_rect.width() + 2, display_rect.height() + 2);
    339   Canvas text_canvas(size, image_scale(), false);
    340   SkPaint bkgnd_paint;
    341   bkgnd_paint.setColor(halo_color);
    342   text_canvas.DrawRect(Rect(size), bkgnd_paint);
    343 
    344   // Draw the text into the temporary buffer. This will have correct
    345   // ClearType since the background color is the same as the halo color.
    346   text_canvas.DrawStringRectWithFlags(
    347       text, font_list, text_color,
    348       Rect(1, 1, display_rect.width(), display_rect.height()), flags);
    349 
    350   uint32_t halo_premul = SkPreMultiplyColor(halo_color);
    351   SkBitmap& text_bitmap = const_cast<SkBitmap&>(
    352       skia::GetTopDevice(*text_canvas.sk_canvas())->accessBitmap(true));
    353 
    354   for (int cur_y = 0; cur_y < text_bitmap.height(); cur_y++) {
    355     uint32_t* text_row = text_bitmap.getAddr32(0, cur_y);
    356     for (int cur_x = 0; cur_x < text_bitmap.width(); cur_x++) {
    357       if (text_row[cur_x] == halo_premul) {
    358         // This pixel was not touched by the text routines. See if it borders
    359         // a touched pixel in any of the 4 directions (not diagonally).
    360         if (!PixelShouldGetHalo(text_bitmap, cur_x, cur_y, halo_premul))
    361           text_row[cur_x] = 0;  // Make transparent.
    362       } else {
    363         text_row[cur_x] |= 0xff << SK_A32_SHIFT;  // Make opaque.
    364       }
    365     }
    366   }
    367 
    368   // Draw the halo bitmap with blur.
    369   ImageSkia text_image = ImageSkia(ImageSkiaRep(text_bitmap,
    370       text_canvas.image_scale()));
    371   DrawImageInt(text_image, display_rect.x() - 1, display_rect.y() - 1);
    372 }
    373 
    374 void Canvas::DrawFadeTruncatingStringRect(
    375     const base::string16& text,
    376     TruncateFadeMode truncate_mode,
    377     const FontList& font_list,
    378     SkColor color,
    379     const Rect& display_rect) {
    380   DrawFadeTruncatingStringRectWithFlags(
    381       text, truncate_mode, font_list, color, display_rect, NO_ELLIPSIS);
    382 }
    383 
    384 void Canvas::DrawFadeTruncatingStringRectWithFlags(
    385     const base::string16& text,
    386     TruncateFadeMode truncate_mode,
    387     const FontList& font_list,
    388     SkColor color,
    389     const Rect& display_rect,
    390     int flags) {
    391   // If the whole string fits in the destination then just draw it directly.
    392   if (GetStringWidth(text, font_list) <= display_rect.width()) {
    393     DrawStringRectWithFlags(text, font_list, color, display_rect, flags);
    394     return;
    395   }
    396 
    397   scoped_ptr<RenderText> render_text(RenderText::CreateInstance());
    398   const bool is_rtl = base::i18n::GetFirstStrongCharacterDirection(text) ==
    399                       base::i18n::RIGHT_TO_LEFT;
    400 
    401   switch (truncate_mode) {
    402     case TruncateFadeTail:
    403       render_text->set_fade_tail(true);
    404       if (is_rtl)
    405         flags |= TEXT_ALIGN_RIGHT;
    406       break;
    407     case TruncateFadeHead:
    408       render_text->set_fade_head(true);
    409       if (!is_rtl)
    410         flags |= TEXT_ALIGN_RIGHT;
    411       break;
    412   }
    413 
    414   // Default to left alignment unless right alignment was chosen above.
    415   if (!(flags & TEXT_ALIGN_RIGHT))
    416     flags |= TEXT_ALIGN_LEFT;
    417 
    418   Rect rect = display_rect;
    419   UpdateRenderText(rect, text, font_list, flags, color, render_text.get());
    420 
    421   const int line_height = render_text->GetStringSize().height();
    422   // Center the text vertically.
    423   rect += Vector2d(0, (display_rect.height() - line_height) / 2);
    424   rect.set_height(line_height);
    425   render_text->SetDisplayRect(rect);
    426 
    427   canvas_->save(SkCanvas::kClip_SaveFlag);
    428   ClipRect(display_rect);
    429   render_text->Draw(this);
    430   canvas_->restore();
    431 }
    432 
    433 }  // namespace gfx
    434