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