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. 4 5#include "ui/gfx/canvas.h" 6 7#include <cmath> 8 9#import <Cocoa/Cocoa.h> 10 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" 16 17namespace gfx { 18 19namespace { 20 21// Returns the pixel width of the string via calling the native method 22// -sizeWithAttributes. 23float 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; 31} 32 33} // namespace 34 35class CanvasTestMac : public testing::Test { 36 protected: 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); 46 47 float mac_width = GetStringNativeWidth(text16, font_list); 48 int mac_height = font_list.GetHeight(); 49 50 float canvas_width = kReallyLargeNumber; 51 float canvas_height = kReallyLargeNumber; 52 Canvas::SizeStringFloat( 53 text16, font_list, &canvas_width, &canvas_height, 0, 0); 54 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. 59 EXPECT_EQ(mac_height, 60 static_cast<int>(canvas_height)) << " height for " << text; 61 } 62 63 private: 64 Font font_; 65}; 66 67 // Tests that Canvas' SizeStringFloat yields result consistent with a native 68 // implementation. 69 TEST_F(CanvasTestMac, StringSizeIdenticalForSkia) { 70 CompareSizes(""); 71 CompareSizes("Foo"); 72 CompareSizes("Longword"); 73 CompareSizes("This is a complete sentence."); 74} 75 76TEST_F(CanvasTestMac, FractionalWidth) { 77 const float kReallyLargeNumber = 12345678; 78 float width = kReallyLargeNumber; 79 float height = kReallyLargeNumber; 80 81 FontList font_list; 82 Canvas::SizeStringFloat( 83 base::UTF8ToUTF16("Test"), font_list, &width, &height, 0, 0); 84 85 EXPECT_GT(width, static_cast<int>(width)); 86} 87 88} // namespace gfx 89