OLD | NEW |
| (Empty) |
1 // Copyright (c) 2010 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 "gfx/font.h" | |
6 | |
7 #include <Cocoa/Cocoa.h> | |
8 | |
9 #include "base/logging.h" | |
10 #include "base/scoped_nsobject.h" | |
11 #include "base/sys_string_conversions.h" | |
12 #include "gfx/canvas_skia.h" | |
13 | |
14 namespace gfx { | |
15 | |
16 // static | |
17 Font Font::CreateFont(const std::wstring& font_name, int font_size) { | |
18 return Font(font_name, font_size, NORMAL); | |
19 } | |
20 | |
21 Font::Font(const std::wstring& font_name, int font_size, int style) | |
22 : font_name_(font_name), | |
23 font_size_(font_size), | |
24 style_(style) { | |
25 calculateMetrics(); | |
26 } | |
27 | |
28 Font::Font() | |
29 : font_size_([NSFont systemFontSize]), | |
30 style_(NORMAL) { | |
31 NSFont* system_font = [NSFont systemFontOfSize:font_size_]; | |
32 font_name_ = base::SysNSStringToWide([system_font fontName]); | |
33 calculateMetrics(); | |
34 } | |
35 | |
36 void Font::calculateMetrics() { | |
37 NSFont* font = nativeFont(); | |
38 scoped_nsobject<NSLayoutManager> layout_manager( | |
39 [[NSLayoutManager alloc] init]); | |
40 height_ = [layout_manager defaultLineHeightForFont:font]; | |
41 ascent_ = [font ascender]; | |
42 avg_width_ = [font boundingRectForGlyph:[font glyphWithName:@"x"]].size.width; | |
43 } | |
44 | |
45 Font Font::DeriveFont(int size_delta, int style) const { | |
46 return Font(font_name_, font_size_ + size_delta, style); | |
47 } | |
48 | |
49 int Font::height() const { | |
50 return height_; | |
51 } | |
52 | |
53 int Font::baseline() const { | |
54 return ascent_; | |
55 } | |
56 | |
57 int Font::ave_char_width() const { | |
58 return avg_width_; | |
59 } | |
60 | |
61 int Font::GetStringWidth(const std::wstring& text) const { | |
62 int width = 0, height = 0; | |
63 CanvasSkia::SizeStringInt(text, *this, &width, &height, | |
64 gfx::Canvas::NO_ELLIPSIS); | |
65 return width; | |
66 } | |
67 | |
68 int Font::GetExpectedTextWidth(int length) const { | |
69 return length * avg_width_; | |
70 } | |
71 | |
72 int Font::style() const { | |
73 return style_; | |
74 } | |
75 | |
76 const std::wstring& Font::FontName() const { | |
77 return font_name_; | |
78 } | |
79 | |
80 int Font::FontSize() { | |
81 return font_size_; | |
82 } | |
83 | |
84 NativeFont Font::nativeFont() const { | |
85 // TODO(pinkerton): apply |style_| to font. http://crbug.com/34667 | |
86 // We could cache this, but then we'd have to conditionally change the | |
87 // dtor just for MacOS. Not sure if we want to/need to do that. | |
88 return [NSFont fontWithName:base::SysWideToNSString(font_name_) | |
89 size:font_size_]; | |
90 } | |
91 | |
92 } // namespace gfx | |
OLD | NEW |