diff options
Diffstat (limited to 'app/gfx')
-rw-r--r-- | app/gfx/color_utils.cc | 266 | ||||
-rw-r--r-- | app/gfx/color_utils.h | 63 | ||||
-rw-r--r-- | app/gfx/text_elider.cc | 517 | ||||
-rw-r--r-- | app/gfx/text_elider.h | 99 | ||||
-rw-r--r-- | app/gfx/text_elider_unittest.cc | 267 |
5 files changed, 1212 insertions, 0 deletions
diff --git a/app/gfx/color_utils.cc b/app/gfx/color_utils.cc new file mode 100644 index 0000000..6378723 --- /dev/null +++ b/app/gfx/color_utils.cc @@ -0,0 +1,266 @@ +// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "app/gfx/color_utils.h" + +#include <math.h> +#if defined(OS_WIN) +#include <windows.h> +#endif + +#include "base/basictypes.h" +#include "base/logging.h" +#include "build/build_config.h" +#if defined(OS_WIN) +#include "skia/ext/skia_utils_win.h" +#endif +#include "skia/include/SkBitmap.h" + +namespace color_utils { + +// These transformations are based on the equations in: +// http://en.wikipedia.org/wiki/Lab_color +// http://en.wikipedia.org/wiki/SRGB_color_space#Specification_of_the_transformation +// See also: +// http://www.brucelindbloom.com/index.html?ColorCalculator.html + +static const double kCIEConversionAlpha = 0.055; +static const double kCIEConversionGamma = 2.2; +static const double kE = 0.008856; +static const double kK = 903.3; + +static double CIEConvertNonLinear(uint8 color_component) { + double color_component_d = static_cast<double>(color_component) / 255.0; + if (color_component_d > 0.04045) { + double base = (color_component_d + kCIEConversionAlpha) / + (1 + kCIEConversionAlpha); + return pow(base, kCIEConversionGamma); + } else { + return color_component_d / 12.92; + } +} + +// Note: this works only for sRGB. +void SkColorToCIEXYZ(SkColor c, CIE_XYZ* xyz) { + uint8 r = SkColorGetR(c); + uint8 g = SkColorGetG(c); + uint8 b = SkColorGetB(c); + + xyz->X = + 0.4124 * CIEConvertNonLinear(r) + + 0.3576 * CIEConvertNonLinear(g) + + 0.1805 * CIEConvertNonLinear(b); + xyz->Y = + 0.2126 * CIEConvertNonLinear(r) + + 0.7152 * CIEConvertNonLinear(g) + + 0.0722 * CIEConvertNonLinear(g); + xyz->Z = + 0.0193 * CIEConvertNonLinear(r) + + 0.1192 * CIEConvertNonLinear(g) + + 0.9505 * CIEConvertNonLinear(b); +} + +static double LabConvertNonLinear(double value) { + if (value > 0.008856) { + double goat = pow(value, static_cast<double>(1) / 3); + return goat; + } + return (kK * value + 16) / 116; +} + +void CIEXYZToLabColor(const CIE_XYZ& xyz, LabColor* lab) { + CIE_XYZ white_xyz; + SkColorToCIEXYZ(SkColorSetRGB(255, 255, 255), &white_xyz); + double fx = LabConvertNonLinear(xyz.X / white_xyz.X); + double fy = LabConvertNonLinear(xyz.Y / white_xyz.Y); + double fz = LabConvertNonLinear(xyz.Z / white_xyz.Z); + lab->L = static_cast<int>(116 * fy) - 16; + lab->a = static_cast<int>(500 * (fx - fy)); + lab->b = static_cast<int>(200 * (fy - fz)); +} + +static uint8 sRGBColorComponentFromLinearComponent(double component) { + double result; + if (component <= 0.0031308) { + result = 12.92 * component; + } else { + result = (1 + kCIEConversionAlpha) * + pow(component, (static_cast<double>(1) / 2.4)) - + kCIEConversionAlpha; + } + return std::min(static_cast<uint8>(255), static_cast<uint8>(result * 255)); +} + +SkColor CIEXYZToSkColor(SkAlpha alpha, const CIE_XYZ& xyz) { + double r_linear = 3.2410 * xyz.X - 1.5374 * xyz.Y - 0.4986 * xyz.Z; + double g_linear = -0.9692 * xyz.X + 1.8760 * xyz.Y + 0.0416 * xyz.Z; + double b_linear = 0.0556 * xyz.X - 0.2040 * xyz.Y + 1.0570 * xyz.Z; + uint8 r = sRGBColorComponentFromLinearComponent(r_linear); + uint8 g = sRGBColorComponentFromLinearComponent(g_linear); + uint8 b = sRGBColorComponentFromLinearComponent(b_linear); + return SkColorSetARGB(alpha, r, g, b); +} + +static double gen_yr(const LabColor& lab) { + if (lab.L > (kE * kK)) + return pow((lab.L + 16.0) / 116, 3.0); + return static_cast<double>(lab.L) / kK; +} + +static double fy(const LabColor& lab) { + double yr = gen_yr(lab); + if (yr > kE) + return (lab.L + 16.0) / 116; + return (kK * yr + 16.0) / 116; +} + +static double fx(const LabColor& lab) { + return (static_cast<double>(lab.a) / 500) + fy(lab); +} + +static double gen_xr(const LabColor& lab) { + double x = fx(lab); + double x_cubed = pow(x, 3.0); + if (x_cubed > kE) + return x_cubed; + return (116.0 * x - 16.0) / kK; +} + +static double fz(const LabColor& lab) { + return fy(lab) - (static_cast<double>(lab.b) / 200); +} + +static double gen_zr(const LabColor& lab) { + double z = fz(lab); + double z_cubed = pow(z, 3.0); + if (z_cubed > kE) + return z_cubed; + return (116.0 * z - 16.0) / kK; +} + +void LabColorToCIEXYZ(const LabColor& lab, CIE_XYZ* xyz) { + CIE_XYZ result; + + CIE_XYZ white_xyz; + SkColorToCIEXYZ(SkColorSetRGB(255, 255, 255), &white_xyz); + + result.X = gen_xr(lab) * white_xyz.X; + result.Y = gen_yr(lab) * white_xyz.Y; + result.Z = gen_zr(lab) * white_xyz.Z; + + *xyz = result; +} + +void SkColorToLabColor(SkColor c, LabColor* lab) { + CIE_XYZ xyz; + SkColorToCIEXYZ(c, &xyz); + CIEXYZToLabColor(xyz, lab); +} + +SkColor LabColorToSkColor(const LabColor& lab, SkAlpha alpha) { + CIE_XYZ xyz; + LabColorToCIEXYZ(lab, &xyz); + return CIEXYZToSkColor(alpha, xyz); +} + +static const int kCloseToBoundary = 64; +static const int kAverageBoundary = 15; + +bool IsColorCloseToTransparent(SkAlpha alpha) { + return alpha < kCloseToBoundary; +} + +bool IsColorCloseToGrey(int r, int g, int b) { + int average = (r + g + b) / 3; + return (abs(r - average) < kAverageBoundary) && + (abs(g - average) < kAverageBoundary) && + (abs(b - average) < kAverageBoundary); +} + +SkColor GetAverageColorOfFavicon(SkBitmap* favicon, SkAlpha alpha) { + int r = 0, g = 0, b = 0; + + SkAutoLockPixels favicon_lock(*favicon); + SkColor* pixels = static_cast<SkColor*>(favicon->getPixels()); + // Assume ARGB_8888 format. + DCHECK(favicon->getConfig() == SkBitmap::kARGB_8888_Config); + SkColor* current_color = pixels; + + DCHECK(favicon->width() <= 16 && favicon->height() <= 16); + + int pixel_count = favicon->width() * favicon->height(); + int color_count = 0; + for (int i = 0; i < pixel_count; ++i, ++current_color) { + // Disregard this color if it is close to black, close to white, or close + // to transparent since any of those pixels do not contribute much to the + // color makeup of this icon. + int cr = SkColorGetR(*current_color); + int cg = SkColorGetG(*current_color); + int cb = SkColorGetB(*current_color); + + if (IsColorCloseToTransparent(SkColorGetA(*current_color)) || + IsColorCloseToGrey(cr, cg, cb)) + continue; + + r += cr; + g += cg; + b += cb; + ++color_count; + } + + SkColor result; + if (color_count > 0) { + result = SkColorSetARGB(alpha, + r / color_count, + g / color_count, + b / color_count); + } else { + result = SkColorSetARGB(alpha, 0, 0, 0); + } + return result; +} + +inline int GetLumaForColor(SkColor* color) { + int r = SkColorGetR(*color); + int g = SkColorGetG(*color); + int b = SkColorGetB(*color); + + int luma = static_cast<int>(0.3*r + 0.59*g + 0.11*b); + if (luma < 0) + luma = 0; + else if (luma > 255) + luma = 255; + + return luma; +} + +void BuildLumaHistogram(SkBitmap* bitmap, int histogram[256]) { + SkAutoLockPixels bitmap_lock(*bitmap); + // Assume ARGB_8888 format. + DCHECK(bitmap->getConfig() == SkBitmap::kARGB_8888_Config); + + int pixel_width = bitmap->width(); + int pixel_height = bitmap->height(); + for (int y = 0; y < pixel_height; ++y) { + SkColor* current_color = static_cast<uint32_t*>(bitmap->getAddr32(0, y)); + for (int x = 0; x < pixel_width; ++x, ++current_color) { + histogram[GetLumaForColor(current_color)]++; + } + } +} + +SkColor SetColorAlpha(SkColor c, SkAlpha alpha) { + return SkColorSetARGB(alpha, SkColorGetR(c), SkColorGetG(c), SkColorGetB(c)); +} + +SkColor GetSysSkColor(int which) { +#if defined(OS_WIN) + return skia::COLORREFToSkColor(::GetSysColor(which)); +#else + NOTIMPLEMENTED(); + return SK_ColorLTGRAY; +#endif +} + +} // namespace color_utils diff --git a/app/gfx/color_utils.h b/app/gfx/color_utils.h new file mode 100644 index 0000000..706361d --- /dev/null +++ b/app/gfx/color_utils.h @@ -0,0 +1,63 @@ +// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef APP_GFX_COLOR_UTILS_H_ +#define APP_GFX_COLOR_UTILS_H_ + +#include "skia/include/SkColor.h" + +class SkBitmap; + +namespace color_utils { + +// Represents set of CIE XYZ tristimulus values. +struct CIE_XYZ { + double X; + double Y; // luminance + double Z; +}; + +// Represents a L*a*b* color value +struct LabColor { + int L; + int a; + int b; +}; + +// Note: these transformations assume sRGB as the source color space + +// Convert between different color spaces +void SkColorToCIEXYZ(SkColor c, CIE_XYZ* xyz); +void CIEXYZToLabColor(const CIE_XYZ& xyz, LabColor* lab); + +SkColor CIEXYZToSkColor(SkAlpha alpha, const CIE_XYZ& xyz); +void LabColorToCIEXYZ(const LabColor& lab, CIE_XYZ* xyz); + +void SkColorToLabColor(SkColor c, LabColor* lab); +SkColor LabColorToSkColor(const LabColor& lab, SkAlpha alpha); + +// Determine if a given alpha value is nearly completely transparent. +bool IsColorCloseToTransparent(SkAlpha alpha); + +// Determine if a color is near grey. +bool IsColorCloseToGrey(int r, int g, int b); + +// Gets a color representing a bitmap. The definition of "representing" is the +// average color in the bitmap. The color returned is modified to have the +// specified alpha. +SkColor GetAverageColorOfFavicon(SkBitmap* bitmap, SkAlpha alpha); + +// Builds a histogram based on the Y' of the Y'UV representation of +// this image. +void BuildLumaHistogram(SkBitmap* bitmap, int histogram[256]); + +// Create a color from a base color and a specific alpha value. +SkColor SetColorAlpha(SkColor c, SkAlpha alpha); + +// Gets a Windows system color as a SkColor +SkColor GetSysSkColor(int which); + +} // namespace color_utils + +#endif // #ifndef APP_GFX_COLOR_UTILS_H_ diff --git a/app/gfx/text_elider.cc b/app/gfx/text_elider.cc new file mode 100644 index 0000000..527f804 --- /dev/null +++ b/app/gfx/text_elider.cc @@ -0,0 +1,517 @@ +// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "app/gfx/chrome_font.h" +#include "app/gfx/text_elider.h" +#include "base/file_path.h" +#include "base/string_util.h" +#include "base/sys_string_conversions.h" +#include "chrome/common/pref_names.h" +#include "chrome/common/pref_service.h" +#include "googleurl/src/gurl.h" +#include "net/base/escape.h" +#include "net/base/net_util.h" +#include "net/base/registry_controlled_domain.h" + +const wchar_t kEllipsis[] = L"\x2026"; + +namespace gfx { + +// Appends the given part of the original URL to the output string formatted for +// the user. The given parsed structure will be updated. The host name formatter +// also takes the same accept languages component as ElideURL. |new_parsed| may +// be null. +static void AppendFormattedHost(const GURL& url, + const std::wstring& languages, + std::wstring* output, + url_parse::Parsed* new_parsed); + +// Calls the unescaper for the substring |in_component| inside of the URL +// |spec|. The decoded string will be appended to |output| and the resulting +// range will be filled into |out_component|. +static void AppendFormattedComponent(const std::string& spec, + const url_parse::Component& in_component, + std::wstring* output, + url_parse::Component* out_component); + +// This function takes a GURL object and elides it. It returns a string +// which composed of parts from subdomain, domain, path, filename and query. +// A "..." is added automatically at the end if the elided string is bigger +// than the available pixel width. For available pixel width = 0, a formatted, +// but un-elided, string is returned. +// +// TODO(pkasting): http://b/119635 This whole function gets +// kerning/ligatures/etc. issues potentially wrong by assuming that the width of +// a rendered string is always the sum of the widths of its substrings. Also I +// suspect it could be made simpler. +std::wstring ElideUrl(const GURL& url, + const ChromeFont& font, + int available_pixel_width, + const std::wstring& languages) { + // Get a formatted string and corresponding parsing of the url. + url_parse::Parsed parsed; + std::wstring url_string = GetCleanStringFromUrl(url, languages, &parsed, + NULL); + if (available_pixel_width <= 0) + return url_string; + + // If non-standard or not file type, return plain eliding. + if (!(url.SchemeIsFile() || url.IsStandard())) + return ElideText(url_string, font, available_pixel_width); + + // Now start eliding url_string to fit within available pixel width. + // Fist pass - check to see whether entire url_string fits. + int pixel_width_url_string = font.GetStringWidth(url_string); + if (available_pixel_width >= pixel_width_url_string) + return url_string; + + // Get the path substring, including query and reference. + size_t path_start_index = parsed.path.begin; + size_t path_len = parsed.path.len; + std::wstring url_path_query_etc = url_string.substr(path_start_index); + std::wstring url_path = url_string.substr(path_start_index, path_len); + + // Return general elided text if url minus the query fits. + std::wstring url_minus_query = url_string.substr(0, path_start_index + + path_len); + if (available_pixel_width >= font.GetStringWidth(url_minus_query)) + return ElideText(url_string, font, available_pixel_width); + + // Get Host. + std::wstring url_host = UTF8ToWide(url.host()); + + // Get domain and registry information from the URL. + std::wstring url_domain = UTF8ToWide( + net::RegistryControlledDomainService::GetDomainAndRegistry(url)); + if (url_domain.empty()) + url_domain = url_host; + + // Add port if required. + if (!url.port().empty()){ + url_host += L":" + UTF8ToWide(url.port()); + url_domain += L":" + UTF8ToWide(url.port()); + } + + // Get sub domain. + std::wstring url_subdomain; + size_t domain_start_index = url_host.find(url_domain); + if (domain_start_index > 0) + url_subdomain = url_host.substr(0, domain_start_index); + if ((url_subdomain == L"www." || url_subdomain.empty() || + url.SchemeIsFile())) { + url_subdomain.clear(); + } + + // If this is a file type, the path is now defined as everything after ":". + // For example, "C:/aa/aa/bb", the path is "/aa/bb/cc". Interesting, the + // domain is now C: - this is a nice hack for eliding to work pleasantly. + if (url.SchemeIsFile()) { + // Split the path string using ":" + std::vector<std::wstring> file_path_split; + SplitString(url_path, L':', &file_path_split); + if (file_path_split.size() > 1) { // File is of type "file:///C:/.." + url_host.clear(); + url_domain.clear(); + url_subdomain.clear(); + + url_host = url_domain = file_path_split.at(0).substr(1) + L":"; + url_path_query_etc = url_path = file_path_split.at(1); + } + } + + // Second Pass - remove scheme - the rest fits. + int pixel_width_url_host = font.GetStringWidth(url_host); + int pixel_width_url_path = font.GetStringWidth(url_path_query_etc); + if (available_pixel_width >= + pixel_width_url_host + pixel_width_url_path) + return url_host + url_path_query_etc; + + // Third Pass: Subdomain, domain and entire path fits. + int pixel_width_url_domain = font.GetStringWidth(url_domain); + int pixel_width_url_subdomain = font.GetStringWidth(url_subdomain); + if (available_pixel_width >= + pixel_width_url_subdomain + pixel_width_url_domain + + pixel_width_url_path) + return url_subdomain + url_domain + url_path_query_etc; + + // Query element. + std::wstring url_query; + const int pixel_width_dots_trailer = font.GetStringWidth(kEllipsis); + if (parsed.query.is_nonempty()) { + url_query = std::wstring(L"?") + url_string.substr(parsed.query.begin); + if (available_pixel_width >= (pixel_width_url_subdomain + + pixel_width_url_domain + pixel_width_url_path - + font.GetStringWidth(url_query))) { + return ElideText(url_subdomain + url_domain + url_path_query_etc, font, + available_pixel_width); + } + } + + // Parse url_path using '/'. + std::vector<std::wstring> url_path_elements; + SplitString(url_path, L'/', &url_path_elements); + + // Get filename - note that for a path ending with / + // such as www.google.com/intl/ads/, the file name is ads/. + int url_path_number_of_elements = static_cast<int> (url_path_elements. + size()); + std::wstring url_filename; + if ((url_path_elements.at(url_path_number_of_elements - 1)).length() > 0) { + url_filename = *(url_path_elements.end()-1); + } else if (url_path_number_of_elements > 1) { // Path ends with a '/'. + url_filename = url_path_elements.at(url_path_number_of_elements - 2) + + L'/'; + url_path_number_of_elements--; + } + + const int kMaxNumberOfUrlPathElementsAllowed = 1024; + if (url_path_number_of_elements <= 1 || + url_path_number_of_elements > kMaxNumberOfUrlPathElementsAllowed) { + // No path to elide, or too long of a path (could overflow in loop below) + // Just elide this as a text string. + return ElideText(url_subdomain + url_domain + url_path_query_etc, font, + available_pixel_width); + } + + // Start eliding the path and replacing elements by "../". + std::wstring an_ellipsis_and_a_slash(kEllipsis); + an_ellipsis_and_a_slash += L'/'; + int pixel_width_url_filename = font.GetStringWidth(url_filename); + int pixel_width_dot_dot_slash = font.GetStringWidth(an_ellipsis_and_a_slash); + int pixel_width_slash = font.GetStringWidth(L"/"); + int pixel_width_url_path_elements[kMaxNumberOfUrlPathElementsAllowed]; + for (int i = 0; i < url_path_number_of_elements; ++i) { + pixel_width_url_path_elements[i] = + font.GetStringWidth(url_path_elements.at(i)); + } + + // Check with both subdomain and domain. + std::wstring elided_path; + int pixel_width_elided_path; + for (int i = url_path_number_of_elements - 1; i >= 1; --i) { + // Add the initial elements of the path. + elided_path.clear(); + pixel_width_elided_path = 0; + for (int j = 0; j < i; ++j) { + elided_path += url_path_elements.at(j) + L'/'; + pixel_width_elided_path += pixel_width_url_path_elements[j] + + pixel_width_slash; + } + + // Add url_file_name. + if (i == (url_path_number_of_elements - 1)) { + elided_path += url_filename; + pixel_width_elided_path += pixel_width_url_filename; + } else { + elided_path += an_ellipsis_and_a_slash + url_filename; + pixel_width_elided_path += pixel_width_dot_dot_slash + + pixel_width_url_filename; + } + + if (available_pixel_width >= + pixel_width_url_subdomain + pixel_width_url_domain + + pixel_width_elided_path) { + return ElideText(url_subdomain + url_domain + elided_path + url_query, + font, available_pixel_width); + } + } + + // Check with only domain. + // If a subdomain is present, add an ellipsis before domain. + // This is added only if the subdomain pixel width is larger than + // the pixel width of kEllipsis. Otherwise, subdomain remains, + // which means that this case has been resolved earlier. + std::wstring url_elided_domain = url_subdomain + url_domain; + int pixel_width_url_elided_domain = pixel_width_url_domain; + if (pixel_width_url_subdomain > pixel_width_dots_trailer) { + if (!url_subdomain.empty()) { + url_elided_domain = kEllipsis + url_domain; + pixel_width_url_elided_domain += pixel_width_dots_trailer; + } else { + url_elided_domain = url_domain; + } + + for (int i = url_path_number_of_elements - 1; i >= 1; --i) { + // Add the initial elements of the path. + elided_path.clear(); + pixel_width_elided_path = 0; + for (int j = 0; j < i; ++j) { + elided_path += url_path_elements.at(j) + L'/'; + pixel_width_elided_path += pixel_width_url_path_elements[j] + + pixel_width_slash; + } + + // Add url_file_name. + if (i == (url_path_number_of_elements - 1)) { + elided_path += url_filename; + pixel_width_elided_path += pixel_width_url_filename; + } else { + elided_path += an_ellipsis_and_a_slash + url_filename; + pixel_width_elided_path += pixel_width_dot_dot_slash + + pixel_width_url_filename; + } + + if (available_pixel_width >= + pixel_width_url_elided_domain + pixel_width_elided_path) { + return ElideText(url_elided_domain + elided_path + url_query, font, + available_pixel_width); + } + } + } + + // Return elided domain/../filename anyway. + std::wstring final_elided_url_string(url_elided_domain); + if ((available_pixel_width - font.GetStringWidth(url_elided_domain)) > + pixel_width_dot_dot_slash + pixel_width_dots_trailer + + font.GetStringWidth(L"UV")) // A hack to prevent trailing "../...". + final_elided_url_string += elided_path; + else + final_elided_url_string += url_path; + + return ElideText(final_elided_url_string, font, available_pixel_width); +} + +std::wstring ElideFilename(const FilePath& filename, + const ChromeFont& font, + int available_pixel_width) { + int full_width = font.GetStringWidth(filename.ToWStringHack()); + if (full_width <= available_pixel_width) + return filename.ToWStringHack(); + +#if defined(OS_WIN) + std::wstring extension = filename.Extension(); +#elif defined(OS_POSIX) + std::wstring extension = base::SysNativeMBToWide(filename.Extension()); +#endif + std::wstring rootname = + filename.BaseName().RemoveExtension().ToWStringHack(); + + if (rootname.empty() || extension.empty()) + return ElideText(filename.ToWStringHack(), font, available_pixel_width); + + int ext_width = font.GetStringWidth(extension); + int root_width = font.GetStringWidth(rootname); + + // We may have trimmed the path. + if (root_width + ext_width <= available_pixel_width) + return rootname + extension; + + int available_root_width = available_pixel_width - ext_width; + return ElideText(rootname, font, available_root_width) + extension; +} + +// This function adds an ellipsis at the end of the text if the text +// does not fit the given pixel width. +std::wstring ElideText(const std::wstring& text, + const ChromeFont& font, + int available_pixel_width){ + if (text.empty()) + return text; + + int current_text_pixel_width = font.GetStringWidth(text); + if (current_text_pixel_width <= available_pixel_width) + return text; + + if (font.GetStringWidth(kEllipsis) > available_pixel_width) + return std::wstring(); + + // Use binary search to compute the elided text. + size_t lo = 0; + size_t hi = text.length() - 1; + size_t guess = hi / 2; + while (lo < hi) { + // We check the length of the whole desired string at once to ensure we + // handle kerning/ligatures/etc. correctly. + std::wstring guess_str = text.substr(0, guess) + kEllipsis; + int guess_length = font.GetStringWidth(guess_str); + if (guess_length > available_pixel_width) { + if (hi == guess) + break; + hi = guess; + } else { + if (lo == guess) + break; + lo = guess; + } + guess = (lo + hi) / 2; + } + + return text.substr(0, lo) + kEllipsis; +} + +void AppendFormattedHost(const GURL& url, + const std::wstring& languages, + std::wstring* output, + url_parse::Parsed* new_parsed) { + const url_parse::Component& host = + url.parsed_for_possibly_invalid_spec().host; + + if (host.is_nonempty()) { + // Handle possible IDN in the host name. + if (new_parsed) + new_parsed->host.begin = static_cast<int>(output->length()); + + const std::string& spec = url.possibly_invalid_spec(); + DCHECK(host.begin >= 0 && + ((spec.length() == 0 && host.begin == 0) || + host.begin < static_cast<int>(spec.length()))); + net::IDNToUnicode(&spec[host.begin], host.len, languages, output); + + if (new_parsed) { + new_parsed->host.len = + static_cast<int>(output->length()) - new_parsed->host.begin; + } + } else if (new_parsed) { + new_parsed->host.reset(); + } +} + +void AppendFormattedComponent(const std::string& spec, + const url_parse::Component& in_component, + std::wstring* output, + url_parse::Component* out_component) { + if (in_component.is_nonempty()) { + out_component->begin = static_cast<int>(output->length()); + + output->append(UnescapeAndDecodeUTF8URLComponent( + spec.substr(in_component.begin, in_component.len), + UnescapeRule::NORMAL)); + + out_component->len = + static_cast<int>(output->length()) - out_component->begin; + } else { + out_component->reset(); + } +} + +std::wstring GetCleanStringFromUrl(const GURL& url, + const std::wstring& languages, + url_parse::Parsed* new_parsed, + size_t* prefix_end) { + url_parse::Parsed parsed_temp; + if (!new_parsed) + new_parsed = &parsed_temp; + + std::wstring url_string; + + // Check for empty URLs or 0 available text width. + if (url.is_empty()) { + if (prefix_end) + *prefix_end = 0; + return url_string; + } + + // We handle both valid and invalid URLs (this will give us the spec + // regardless of validity). + const std::string& spec = url.possibly_invalid_spec(); + const url_parse::Parsed& parsed = url.parsed_for_possibly_invalid_spec(); + + // Construct a new URL with the username and password fields removed. We + // don't want to display those to the user since they can be used for + // attacks, e.g. "http://google.com:search@evil.ru/" + // + // Copy everything before the host name we want (the scheme and the + // separators), minus the username start we computed above. These are ASCII. + int pre_end = parsed.CountCharactersBefore( + url_parse::Parsed::USERNAME, true); + for (int i = 0; i < pre_end; ++i) + url_string.push_back(spec[i]); + if (prefix_end) + *prefix_end = static_cast<size_t>(pre_end); + new_parsed->scheme = parsed.scheme; + new_parsed->username.reset(); + new_parsed->password.reset(); + + AppendFormattedHost(url, languages, &url_string, new_parsed); + + // Port. + if (parsed.port.is_nonempty()) { + url_string.push_back(':'); + for (int i = parsed.port.begin; i < parsed.port.end(); ++i) + url_string.push_back(spec[i]); + } + + // Path and query both get the same general unescape & convert treatment. + AppendFormattedComponent(spec, parsed.path, &url_string, &new_parsed->path); + if (parsed.query.is_valid()) + url_string.push_back('?'); + AppendFormattedComponent(spec, parsed.query, &url_string, &new_parsed->query); + + // Reference is stored in valid, unescaped UTF-8, so we can just convert. + if (parsed.ref.is_valid()) { + url_string.push_back('#'); + if (parsed.ref.len > 0) + url_string.append(UTF8ToWide(std::string(&spec[parsed.ref.begin], + parsed.ref.len))); + } + + return url_string; +} + +SortedDisplayURL::SortedDisplayURL(const GURL& url, + const std::wstring& languages) { + std::wstring host; + AppendFormattedHost(url, languages, &host, NULL); + sort_host_ = WideToUTF16Hack(host); + string16 host_minus_www = WideToUTF16Hack(net::StripWWW(host)); + url_parse::Parsed parsed; + display_url_ = WideToUTF16Hack(GetCleanStringFromUrl(url, languages, + &parsed, &prefix_end_)); + if (sort_host_.length() > host_minus_www.length()) { + prefix_end_ += sort_host_.length() - host_minus_www.length(); + sort_host_.swap(host_minus_www); + } +} + +int SortedDisplayURL::Compare(const SortedDisplayURL& other, + Collator* collator) const { + // Compare on hosts first. The host won't contain 'www.'. + UErrorCode compare_status = U_ZERO_ERROR; + UCollationResult host_compare_result = collator->compare( + static_cast<const UChar*>(sort_host_.c_str()), + static_cast<int>(sort_host_.length()), + static_cast<const UChar*>(other.sort_host_.c_str()), + static_cast<int>(other.sort_host_.length()), + compare_status); + DCHECK(U_SUCCESS(compare_status)); + if (host_compare_result != 0) + return host_compare_result; + + // Hosts match, compare on the portion of the url after the host. + string16 path = this->AfterHost(); + string16 o_path = other.AfterHost(); + compare_status = U_ZERO_ERROR; + UCollationResult path_compare_result = collator->compare( + static_cast<const UChar*>(path.c_str()), + static_cast<int>(path.length()), + static_cast<const UChar*>(o_path.c_str()), + static_cast<int>(o_path.length()), + compare_status); + DCHECK(U_SUCCESS(compare_status)); + if (path_compare_result != 0) + return path_compare_result; + + // Hosts and paths match, compare on the complete url. This'll push the www. + // ones to the end. + compare_status = U_ZERO_ERROR; + UCollationResult display_url_compare_result = collator->compare( + static_cast<const UChar*>(display_url_.c_str()), + static_cast<int>(display_url_.length()), + static_cast<const UChar*>(other.display_url_.c_str()), + static_cast<int>(other.display_url_.length()), + compare_status); + DCHECK(U_SUCCESS(compare_status)); + return display_url_compare_result; +} + +string16 SortedDisplayURL::AfterHost() const { + size_t slash_index = display_url_.find(sort_host_, prefix_end_); + if (slash_index == string16::npos) { + NOTREACHED(); + return string16(); + } + return display_url_.substr(slash_index + sort_host_.length()); +} + +} // namespace gfx. diff --git a/app/gfx/text_elider.h b/app/gfx/text_elider.h new file mode 100644 index 0000000..61bfada --- /dev/null +++ b/app/gfx/text_elider.h @@ -0,0 +1,99 @@ +// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_COMMON_GFX_TEXT_ELIDER_H_ +#define CHROME_COMMON_GFX_TEXT_ELIDER_H_ + +#include <unicode/coll.h> +#include <unicode/uchar.h> + +#include "app/gfx/chrome_font.h" +#include "base/basictypes.h" +#include "base/string16.h" + +class FilePath; +class GURL; + +namespace url_parse { +struct Parsed; +} + +// TODO(port): this file should deal in string16s rather than wstrings. +namespace gfx { + +// A function to get URL string from a GURL that will be suitable for display +// to the user. The parsing of the URL may change because various parts of the +// string will change lengths. The new parsing will be placed in the given out +// parameter. |prefix_end| is set to the end of the prefix (spec and separator +// characters before host). +// |languages|, |new_parsed|, and |prefix_end| may all be empty or NULL. +std::wstring GetCleanStringFromUrl(const GURL& url, + const std::wstring& languages, + url_parse::Parsed* new_parsed, + size_t* prefix_end); + +// This function takes a GURL object and elides it. It returns a string +// which composed of parts from subdomain, domain, path, filename and query. +// A "..." is added automatically at the end if the elided string is bigger +// than the available pixel width. For available pixel width = 0, empty +// string is returned. |languages| is a comma separted list of ISO 639 +// language codes and is used to determine what characters are understood +// by a user. It should come from |prefs::kAcceptLanguages|. +// +// Note: in RTL locales, if the URL returned by this function is going to be +// displayed in the UI, then it is likely that the string needs to be marked +// as an LTR string (using l10n_util::WrapStringWithLTRFormatting()) so that it +// is displayed properly in an RTL context. Please refer to +// http://crbug.com/6487 for more information. +std::wstring ElideUrl(const GURL& url, + const ChromeFont& font, + int available_pixel_width, + const std::wstring& languages); + +std::wstring ElideText(const std::wstring& text, + const ChromeFont& font, + int available_pixel_width); + +// Elide a filename to fit a given pixel width, with an emphasis on not hiding +// the extension unless we have to. If filename contains a path, the path will +// be removed if filename doesn't fit into available_pixel_width. +std::wstring ElideFilename(const FilePath& filename, + const ChromeFont& font, + int available_pixel_width); + +// SortedDisplayURL maintains a string from a URL suitable for display to the +// use. SortedDisplayURL also provides a function used for comparing two +// SortedDisplayURLs for use in visually ordering the SortedDisplayURLs. +// +// SortedDisplayURL is relatively cheap and supports value semantics. +class SortedDisplayURL { + public: + SortedDisplayURL(const GURL& url, const std::wstring& languages); + SortedDisplayURL() {} + + // Compares this SortedDisplayURL to |url| using |collator|. Returns a value + // < 0, = 1 or > 0 as to whether this url is less then, equal to or greater + // than the supplied url. + int Compare(const SortedDisplayURL& other, Collator* collator) const; + + // Returns the display string for the URL. + const string16& display_url() const { return display_url_; } + + private: + // Returns everything after the host. This is used by Compare if the hosts + // match. + string16 AfterHost() const; + + // Host name minus 'www.'. Used by Compare. + string16 sort_host_; + + // End of the prefix (spec and separator) in display_url_. + size_t prefix_end_; + + string16 display_url_; +}; + +} // namespace gfx. + +#endif // CHROME_COMMON_GFX_TEXT_ELIDER_H_ diff --git a/app/gfx/text_elider_unittest.cc b/app/gfx/text_elider_unittest.cc new file mode 100644 index 0000000..0f17f9f --- /dev/null +++ b/app/gfx/text_elider_unittest.cc @@ -0,0 +1,267 @@ +// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "app/gfx/chrome_font.h" +#include "app/gfx/text_elider.h" +#include "base/file_path.h" +#include "base/string_util.h" +#include "googleurl/src/gurl.h" +#include "testing/gtest/include/gtest/gtest.h" + +using namespace gfx; + +namespace { + +const wchar_t kEllipsis[] = L"\x2026"; + +struct Testcase { + const std::string input; + const std::wstring output; +}; + +struct FileTestcase { + const FilePath::StringType input; + const std::wstring output; +}; + +struct WideTestcase { + const std::wstring input; + const std::wstring output; +}; + +struct TestData { + const std::string a; + const std::string b; + const int compare_result; +}; + +void RunTest(Testcase* testcases, size_t num_testcases) { + static const ChromeFont font; + for (size_t i = 0; i < num_testcases; ++i) { + const GURL url(testcases[i].input); + // Should we test with non-empty language list? + // That's kinda redundant with net_util_unittests. + EXPECT_EQ(testcases[i].output, + ElideUrl(url, font, font.GetStringWidth(testcases[i].output), + std::wstring())); + } +} + +} // namespace + +// Test eliding of commonplace URLs. +TEST(TextEliderTest, TestGeneralEliding) { + const std::wstring kEllipsisStr(kEllipsis); + Testcase testcases[] = { + {"http://www.google.com/intl/en/ads/", + L"http://www.google.com/intl/en/ads/"}, + {"http://www.google.com/intl/en/ads/", L"www.google.com/intl/en/ads/"}, +// TODO(port): make this test case work on mac. +#if !defined(OS_MACOSX) + {"http://www.google.com/intl/en/ads/", + L"google.com/intl/" + kEllipsisStr + L"/ads/"}, +#endif + {"http://www.google.com/intl/en/ads/", + L"google.com/" + kEllipsisStr + L"/ads/"}, + {"http://www.google.com/intl/en/ads/", L"google.com/" + kEllipsisStr}, + {"http://www.google.com/intl/en/ads/", L"goog" + kEllipsisStr}, + {"https://subdomain.foo.com/bar/filename.html", + L"subdomain.foo.com/bar/filename.html"}, + {"https://subdomain.foo.com/bar/filename.html", + L"subdomain.foo.com/" + kEllipsisStr + L"/filename.html"}, + {"http://subdomain.foo.com/bar/filename.html", + kEllipsisStr + L"foo.com/" + kEllipsisStr + L"/filename.html"}, + {"http://www.google.com/intl/en/ads/?aLongQueryWhichIsNotRequired", + L"http://www.google.com/intl/en/ads/?aLongQ" + kEllipsisStr}, + }; + + RunTest(testcases, arraysize(testcases)); +} + +// Test eliding of empty strings, URLs with ports, passwords, queries, etc. +TEST(TextEliderTest, TestMoreEliding) { + const std::wstring kEllipsisStr(kEllipsis); + Testcase testcases[] = { + {"http://www.google.com/foo?bar", L"http://www.google.com/foo?bar"}, + {"http://xyz.google.com/foo?bar", L"xyz.google.com/foo?" + kEllipsisStr}, + {"http://xyz.google.com/foo?bar", L"xyz.google.com/foo" + kEllipsisStr}, + {"http://xyz.google.com/foo?bar", L"xyz.google.com/fo" + kEllipsisStr}, + {"http://a.b.com/pathname/c?d", L"a.b.com/" + kEllipsisStr + L"/c?d"}, + {"", L""}, + {"http://foo.bar..example.com...hello/test/filename.html", + L"foo.bar..example.com...hello/" + kEllipsisStr + L"/filename.html"}, + {"http://foo.bar../", L"http://foo.bar../"}, + {"http://xn--1lq90i.cn/foo", L"http://\x5317\x4eac.cn/foo"}, + {"http://me:mypass@secrethost.com:99/foo?bar#baz", + L"http://secrethost.com:99/foo?bar#baz"}, + {"http://me:mypass@ss%xxfdsf.com/foo", L"http://ss%25xxfdsf.com/foo"}, + {"mailto:elgoato@elgoato.com", L"mailto:elgoato@elgoato.com"}, + {"javascript:click(0)", L"javascript:click(0)"}, + {"https://chess.eecs.berkeley.edu:4430/login/arbitfilename", + L"chess.eecs.berkeley.edu:4430/login/arbitfilename"}, + {"https://chess.eecs.berkeley.edu:4430/login/arbitfilename", + kEllipsisStr + L"berkeley.edu:4430/" + kEllipsisStr + L"/arbitfilename"}, + + // Unescaping. + {"http://www/%E4%BD%A0%E5%A5%BD?q=%E4%BD%A0%E5%A5%BD#\xe4\xbd\xa0", + L"http://www/\x4f60\x597d?q=\x4f60\x597d#\x4f60"}, + + // Invalid unescaping for path. The ref will always be valid UTF-8. We don't + // bother to do too many edge cases, since these are handled by the escaper + // unittest. + {"http://www/%E4%A0%E5%A5%BD?q=%E4%BD%A0%E5%A5%BD#\xe4\xbd\xa0", + L"http://www/%E4%A0%E5%A5%BD?q=\x4f60\x597d#\x4f60"}, + }; + + RunTest(testcases, arraysize(testcases)); +} + +// Test eliding of file: URLs. +TEST(TextEliderTest, TestFileURLEliding) { + const std::wstring kEllipsisStr(kEllipsis); + Testcase testcases[] = { + {"file:///C:/path1/path2/path3/filename", + L"file:///C:/path1/path2/path3/filename"}, + {"file:///C:/path1/path2/path3/filename", + L"C:/path1/path2/path3/filename"}, +// GURL parses "file:///C:path" differently on windows than it does on posix. +#if defined(OS_WIN) + {"file:///C:path1/path2/path3/filename", + L"C:/path1/path2/" + kEllipsisStr + L"/filename"}, + {"file:///C:path1/path2/path3/filename", + L"C:/path1/" + kEllipsisStr + L"/filename"}, + {"file:///C:path1/path2/path3/filename", + L"C:/" + kEllipsisStr + L"/filename"}, +#endif + {"file://filer/foo/bar/file", L"filer/foo/bar/file"}, + {"file://filer/foo/bar/file", L"filer/foo/" + kEllipsisStr + L"/file"}, + {"file://filer/foo/bar/file", L"filer/" + kEllipsisStr + L"/file"}, + }; + + RunTest(testcases, arraysize(testcases)); +} + +TEST(TextEliderTest, TestFilenameEliding) { + const std::wstring kEllipsisStr(kEllipsis); + const FilePath::StringType kPathSeparator = + FilePath::StringType().append(1, FilePath::kSeparators[0]); + + FileTestcase testcases[] = { + {FILE_PATH_LITERAL(""), L""}, + {FILE_PATH_LITERAL("."), L"."}, + {FILE_PATH_LITERAL("filename.exe"), L"filename.exe"}, + {FILE_PATH_LITERAL(".longext"), L".longext"}, + {FILE_PATH_LITERAL("pie"), L"pie"}, + {FILE_PATH_LITERAL("c:") + kPathSeparator + FILE_PATH_LITERAL("path") + + kPathSeparator + FILE_PATH_LITERAL("filename.pie"), + L"filename.pie"}, + {FILE_PATH_LITERAL("c:") + kPathSeparator + FILE_PATH_LITERAL("path") + + kPathSeparator + FILE_PATH_LITERAL("longfilename.pie"), + L"long" + kEllipsisStr + L".pie"}, + {FILE_PATH_LITERAL("http://path.com/filename.pie"), L"filename.pie"}, + {FILE_PATH_LITERAL("http://path.com/longfilename.pie"), + L"long" + kEllipsisStr + L".pie"}, + {FILE_PATH_LITERAL("piesmashingtacularpants"), L"pie" + kEllipsisStr}, + {FILE_PATH_LITERAL(".piesmashingtacularpants"), L".pie" + kEllipsisStr}, + {FILE_PATH_LITERAL("cheese."), L"cheese."}, + {FILE_PATH_LITERAL("file name.longext"), + L"file" + kEllipsisStr + L".longext"}, + {FILE_PATH_LITERAL("fil ename.longext"), + L"fil " + kEllipsisStr + L".longext"}, + {FILE_PATH_LITERAL("filename.longext"), + L"file" + kEllipsisStr + L".longext"}, + {FILE_PATH_LITERAL("filename.middleext.longext"), + L"filename.mid" + kEllipsisStr + L".longext"} + }; + + static const ChromeFont font; + for (size_t i = 0; i < arraysize(testcases); ++i) { + FilePath filepath(testcases[i].input); + EXPECT_EQ(testcases[i].output, ElideFilename(filepath, + font, + font.GetStringWidth(testcases[i].output))); + } +} + +TEST(TextEliderTest, ElideTextLongStrings) { + const std::wstring kEllipsisStr(kEllipsis); + std::wstring data_scheme(L"data:text/plain,"); + + std::wstring ten_a(10, L'a'); + std::wstring hundred_a(100, L'a'); + std::wstring thousand_a(1000, L'a'); + std::wstring ten_thousand_a(10000, L'a'); + std::wstring hundred_thousand_a(100000, L'a'); + std::wstring million_a(1000000, L'a'); + + WideTestcase testcases[] = { + {data_scheme + ten_a, + data_scheme + ten_a}, + {data_scheme + hundred_a, + data_scheme + hundred_a}, + {data_scheme + thousand_a, + data_scheme + std::wstring(156, L'a') + kEllipsisStr}, + {data_scheme + ten_thousand_a, + data_scheme + std::wstring(156, L'a') + kEllipsisStr}, + {data_scheme + hundred_thousand_a, + data_scheme + std::wstring(156, L'a') + kEllipsisStr}, + {data_scheme + million_a, + data_scheme + std::wstring(156, L'a') + kEllipsisStr}, + }; + + const ChromeFont font; + int ellipsis_width = font.GetStringWidth(kEllipsisStr); + for (size_t i = 0; i < arraysize(testcases); ++i) { + // Compare sizes rather than actual contents because if the test fails, + // output is rather long. + EXPECT_EQ(testcases[i].output.size(), + ElideText(testcases[i].input, font, + font.GetStringWidth(testcases[i].output)).size()); + EXPECT_EQ(kEllipsisStr, + ElideText(testcases[i].input, font, ellipsis_width)); + } +} + +// Verifies display_url is set correctly. +TEST(TextEliderTest, SortedDisplayURL) { + gfx::SortedDisplayURL d_url(GURL("http://www.google.com/"), std::wstring()); + EXPECT_EQ("http://www.google.com/", UTF16ToASCII(d_url.display_url())); +} + +// Verifies DisplayURL::Compare works correctly. +TEST(TextEliderTest, SortedDisplayURLCompare) { + UErrorCode create_status = U_ZERO_ERROR; + scoped_ptr<Collator> collator(Collator::createInstance(create_status)); + if (!U_SUCCESS(create_status)) + return; + + TestData tests[] = { + // IDN comparison. Hosts equal, so compares on path. + { "http://xn--1lq90i.cn/a", "http://xn--1lq90i.cn/b", -1}, + + // Because the host and after host match, this compares the full url. + { "http://www.x/b", "http://x/b", -1 }, + + // Because the host and after host match, this compares the full url. + { "http://www.a:1/b", "http://a:1/b", 1 }, + + // The hosts match, so these end up comparing on the after host portion. + { "http://www.x:0/b", "http://x:1/b", -1 }, + { "http://www.x/a", "http://x/b", -1 }, + { "http://x/b", "http://www.x/a", 1 }, + + // Trivial Equality. + { "http://a/", "http://a/", 0 }, + + // Compares just hosts. + { "http://www.a/", "http://b/", -1 }, + }; + + for (size_t i = 0; i < arraysize(tests); ++i) { + gfx::SortedDisplayURL url1(GURL(tests[i].a), std::wstring()); + gfx::SortedDisplayURL url2(GURL(tests[i].b), std::wstring()); + EXPECT_EQ(tests[i].compare_result, url1.Compare(url2, collator.get())); + EXPECT_EQ(-tests[i].compare_result, url2.Compare(url1, collator.get())); + } +} |