1 // Copyright 2013 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.
5 #include "ui/gfx/canvas.h"
9 #import <Cocoa/Cocoa.h>
11 #include "base/strings/utf_string_conversions.h"
12 #include "base/strings/sys_string_conversions.h"
13 #include "testing/gtest/include/gtest/gtest.h"
14 #include "ui/gfx/font.h"
15 #include "ui/gfx/font_list.h"
21 // Returns the pixel width of the string via calling the native method
22 // -sizeWithAttributes.
23 float GetStringNativeWidth(const base::string16& text,
24 const FontList& font_list) {
25 NSFont* native_font = font_list.GetPrimaryFont().GetNativeFont();
26 NSString* ns_string = base::SysUTF16ToNSString(text);
27 NSDictionary* attributes =
28 [NSDictionary dictionaryWithObject:native_font
29 forKey:NSFontAttributeName];
30 return [ns_string sizeWithAttributes:attributes].width;
35 class CanvasTestMac : public testing::Test {
37 // Compare the size returned by Canvas::SizeStringInt to the size generated
38 // by the platform-specific version in CanvasMac_SizeStringInt. Will generate
39 // expectation failure on any mismatch. Only works for single-line text
40 // without specified line height, since that is all the platform
41 // implementation supports.
42 void CompareSizes(const char* text) {
43 const float kReallyLargeNumber = 12345678;
44 FontList font_list(font_);
45 base::string16 text16 = base::UTF8ToUTF16(text);
47 float mac_width = GetStringNativeWidth(text16, font_list);
48 int mac_height = font_list.GetHeight();
50 float canvas_width = kReallyLargeNumber;
51 float canvas_height = kReallyLargeNumber;
52 Canvas::SizeStringFloat(
53 text16, font_list, &canvas_width, &canvas_height, 0, 0);
55 EXPECT_NE(kReallyLargeNumber, mac_width) << "no width for " << text;
56 EXPECT_NE(kReallyLargeNumber, mac_height) << "no height for " << text;
57 EXPECT_EQ(mac_width, canvas_width) << " width for " << text;
58 // FontList::GetHeight returns a truncated height.
60 static_cast<int>(canvas_height)) << " height for " << text;
67 // Tests that Canvas' SizeStringFloat yields result consistent with a native
69 TEST_F(CanvasTestMac, StringSizeIdenticalForSkia) {
72 CompareSizes("Longword");
73 CompareSizes("This is a complete sentence.");
76 TEST_F(CanvasTestMac, FractionalWidth) {
77 const float kReallyLargeNumber = 12345678;
78 float width = kReallyLargeNumber;
79 float height = kReallyLargeNumber;
82 Canvas::SizeStringFloat(
83 base::UTF8ToUTF16("Test"), font_list, &width, &height, 0, 0);
85 EXPECT_GT(width, static_cast<int>(width));