1// Copyright (c) 2012 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 <limits>
8
9#include "base/strings/utf_string_conversions.h"
10#include "testing/gtest/include/gtest/gtest.h"
11#include "ui/gfx/font_list.h"
12#include "ui/gfx/geometry/rect.h"
13#include "ui/gfx/geometry/rect_f.h"
14#include "ui/gfx/skia_util.h"
15
16namespace gfx {
17
18class CanvasTest : public testing::Test {
19 protected:
20  int GetStringWidth(const char *text) {
21    return Canvas::GetStringWidth(base::UTF8ToUTF16(text), font_list_);
22  }
23
24  gfx::Size SizeStringInt(const char *text, int width, int line_height) {
25    base::string16 text16 = base::UTF8ToUTF16(text);
26    int height = 0;
27    int flags =
28        (text16.find('\n') != base::string16::npos) ? Canvas::MULTI_LINE : 0;
29    Canvas::SizeStringInt(text16, font_list_, &width, &height, line_height,
30                          flags);
31    return gfx::Size(width, height);
32  }
33
34 private:
35  FontList font_list_;
36};
37
38TEST_F(CanvasTest, StringWidth) {
39  EXPECT_GT(GetStringWidth("Test"), 0);
40}
41
42TEST_F(CanvasTest, StringWidthEmptyString) {
43  EXPECT_EQ(0, GetStringWidth(""));
44}
45
46TEST_F(CanvasTest, StringSizeEmptyString) {
47  gfx::Size size = SizeStringInt("", 0, 0);
48  EXPECT_EQ(0, size.width());
49  EXPECT_GT(size.height(), 0);
50}
51
52// Verifies GetClipBounds() returns the correct value.
53TEST_F(CanvasTest, ClipRectWithScaling) {
54  Canvas canvas(gfx::Size(200, 100), 2.25, true);
55  canvas.sk_canvas()->clipRect(RectFToSkRect(gfx::RectF(100, 0, 20, 1.7f)));
56  gfx::Rect clip_rect;
57  ASSERT_TRUE(canvas.GetClipBounds(&clip_rect));
58  // Use Contains() rather than Equals() as skia may extend the rect in certain
59  // directions. None-the-less the clip must contain the region we damaged.
60  EXPECT_TRUE(clip_rect.Contains(gfx::Rect(100, 0, 20, 2)));
61}
62
63// Line height is only supported on Skia.
64#if defined(OS_MACOSX) || defined(OS_ANDROID)
65#define MAYBE_StringSizeWithLineHeight DISABLED_StringSizeWithLineHeight
66#else
67#define MAYBE_StringSizeWithLineHeight StringSizeWithLineHeight
68#endif
69
70TEST_F(CanvasTest, MAYBE_StringSizeWithLineHeight) {
71  gfx::Size one_line_size = SizeStringInt("Q", 0, 0);
72  gfx::Size four_line_size = SizeStringInt("Q\nQ\nQ\nQ", 1000000, 1000);
73  EXPECT_EQ(one_line_size.width(), four_line_size.width());
74  EXPECT_EQ(3 * 1000 + one_line_size.height(), four_line_size.height());
75}
76
77}  // namespace gfx
78