tooltip_manager.cc revision 5821806d5e7f356e8fa4b058a389a808ea183019
1// Copyright (c) 2011 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/views/widget/tooltip_manager.h"
6
7#include <vector>
8
9#include "base/string_split.h"
10#include "base/utf_string_conversions.h"
11#include "ui/base/text/text_elider.h"
12
13namespace {
14
15// Maximum number of characters we allow in a tooltip.
16const size_t kMaxTooltipLength = 1024;
17
18// Maximum number of lines we allow in the tooltip.
19const size_t kMaxLines = 6;
20
21}  // namespace
22
23namespace views {
24
25// static
26void TooltipManager::TrimTooltipToFit(string16* text,
27                                      int* max_width,
28                                      int* line_count,
29                                      int x,
30                                      int y,
31                                      gfx::NativeView context) {
32  *max_width = 0;
33  *line_count = 0;
34
35  // Clamp the tooltip length to kMaxTooltipLength so that we don't
36  // accidentally DOS the user with a mega tooltip.
37  if (text->length() > kMaxTooltipLength)
38    *text = text->substr(0, kMaxTooltipLength);
39
40  // Determine the available width for the tooltip.
41  int available_width = GetMaxWidth(x, y, context);
42
43  // Split the string into at most kMaxLines lines.
44  std::vector<string16> lines;
45  base::SplitString(*text, '\n', &lines);
46  if (lines.size() > kMaxLines)
47    lines.resize(kMaxLines);
48  *line_count = static_cast<int>(lines.size());
49
50  // Format each line to fit.
51  gfx::Font font = GetDefaultFont();
52  string16 result;
53  for (std::vector<string16>::iterator i = lines.begin(); i != lines.end();
54       ++i) {
55    string16 elided_text =
56        ui::ElideText(*i, font, available_width, ui::ELIDE_AT_END);
57    *max_width = std::max(*max_width, font.GetStringWidth(elided_text));
58    if (!result.empty())
59      result.push_back('\n');
60    result.append(elided_text);
61  }
62  *text = result;
63}
64
65}  // namespace views
66