1 // Copyright 2014 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 #import "chrome/browser/ui/cocoa/profiles/avatar_button_controller.h"
7 #include "base/mac/foundation_util.h"
8 #include "base/strings/sys_string_conversions.h"
9 #include "chrome/browser/browser_process.h"
10 #include "chrome/browser/profiles/profile_manager.h"
11 #include "chrome/browser/profiles/profiles_state.h"
12 #include "chrome/browser/themes/theme_service.h"
13 #include "chrome/browser/themes/theme_service_factory.h"
14 #include "chrome/browser/ui/browser.h"
15 #include "chrome/browser/ui/browser_window.h"
16 #import "chrome/browser/ui/cocoa/browser_window_controller.h"
17 #import "chrome/browser/ui/cocoa/profiles/avatar_button.h"
18 #include "chrome/grit/generated_resources.h"
19 #include "components/signin/core/browser/signin_error_controller.h"
20 #include "grit/theme_resources.h"
21 #import "ui/base/cocoa/appkit_utils.h"
22 #include "ui/base/l10n/l10n_util_mac.h"
23 #include "ui/base/nine_image_painter_factory.h"
24 #include "ui/base/resource/resource_bundle.h"
25 #include "ui/gfx/image/image_skia_operations.h"
26 #include "ui/gfx/image/image_skia_util_mac.h"
30 // NSButtons have a default padding of 5px. This button should have a padding
32 const CGFloat kButtonExtraPadding = 8 - 5;
33 const CGFloat kButtonHeight = 28;
35 const ui::NinePartImageIds kNormalBorderImageIds =
36 IMAGE_GRID(IDR_AVATAR_MAC_BUTTON_NORMAL);
37 const ui::NinePartImageIds kHoverBorderImageIds =
38 IMAGE_GRID(IDR_AVATAR_MAC_BUTTON_HOVER);
39 const ui::NinePartImageIds kPressedBorderImageIds =
40 IMAGE_GRID(IDR_AVATAR_MAC_BUTTON_PRESSED);
41 const ui::NinePartImageIds kThemedBorderImageIds =
42 IMAGE_GRID(IDR_AVATAR_THEMED_MAC_BUTTON_NORMAL);
44 NSImage* GetImageFromResourceID(int resourceId) {
45 return ui::ResourceBundle::GetSharedInstance().GetNativeImageNamed(
46 resourceId).ToNSImage();
51 // Button cell with a custom border given by a set of nine-patch image grids.
52 @interface CustomThemeButtonCell : NSButtonCell {
57 - (void)setIsThemedWindow:(BOOL)isThemedWindow;
58 - (void)setHasError:(BOOL)hasError withTitle:(NSString*)title;
62 @implementation CustomThemeButtonCell
63 - (id)initWithThemedWindow:(BOOL)isThemedWindow {
64 if ((self = [super init])) {
65 isThemedWindow_ = isThemedWindow;
72 NSSize buttonSize = [super cellSize];
74 // An image and no error means we are drawing the generic button, which
75 // is square. Otherwise, we are displaying the profile's name and an
76 // optional authentication error icon.
77 if ([self image] && !hasError_) {
78 buttonSize.width = kButtonHeight;
80 buttonSize.width += 2 * kButtonExtraPadding;
82 buttonSize.height = kButtonHeight;
86 - (void)drawInteriorWithFrame:(NSRect)frame inView:(NSView*)controlView {
87 NSRect frameAfterPadding = NSInsetRect(frame, kButtonExtraPadding, 0);
88 [super drawInteriorWithFrame:frameAfterPadding inView:controlView];
91 - (void)drawImage:(NSImage*)image
92 withFrame:(NSRect)frame
93 inView:(NSView*)controlView {
94 // The image used in the generic button case needs to be shifted down
95 // slightly to be centered correctly.
96 // TODO(noms): When the assets are fixed, remove this latter offset.
98 frame = NSOffsetRect(frame, 0, 1);
99 [super drawImage:image withFrame:frame inView:controlView];
102 - (void)drawBezelWithFrame:(NSRect)frame
103 inView:(NSView*)controlView {
104 HoverState hoverState =
105 [base::mac::ObjCCastStrict<AvatarButton>(controlView) hoverState];
106 ui::NinePartImageIds imageIds = kNormalBorderImageIds;
108 imageIds = kThemedBorderImageIds;
110 if (hoverState == kHoverStateMouseDown)
111 imageIds = kPressedBorderImageIds;
112 else if (hoverState == kHoverStateMouseOver)
113 imageIds = kHoverBorderImageIds;
114 ui::DrawNinePartImage(frame, imageIds, NSCompositeSourceOver, 1.0, true);
117 - (void)drawFocusRingMaskWithFrame:(NSRect)frame inView:(NSView*)view {
118 // Match the bezel's shape.
119 [[NSBezierPath bezierPathWithRoundedRect:NSInsetRect(frame, 2, 2)
124 - (void)setIsThemedWindow:(BOOL)isThemedWindow {
125 isThemedWindow_ = isThemedWindow;
128 - (void)setHasError:(BOOL)hasError withTitle:(NSString*)title {
129 hasError_ = hasError;
130 int messageId = hasError ?
131 IDS_PROFILES_ACCOUNT_BUTTON_AUTH_ERROR_ACCESSIBLE_NAME :
132 IDS_PROFILES_NEW_AVATAR_BUTTON_ACCESSIBLE_NAME;
134 [self accessibilitySetOverrideValue:l10n_util::GetNSStringF(
135 messageId, base::SysNSStringToUTF16(title))
136 forAttribute:NSAccessibilityTitleAttribute];
141 @interface AvatarButtonController (Private)
142 - (void)updateAvatarButtonAndLayoutParent:(BOOL)layoutParent;
143 - (void)updateErrorStatus:(BOOL)hasError;
145 - (void)themeDidChangeNotification:(NSNotification*)aNotification;
148 @implementation AvatarButtonController
150 - (id)initWithBrowser:(Browser*)browser {
151 if ((self = [super initWithBrowser:browser])) {
152 ThemeService* themeService =
153 ThemeServiceFactory::GetForProfile(browser->profile());
154 isThemedWindow_ = !themeService->UsingSystemTheme();
156 AvatarButton* avatarButton =
157 [[AvatarButton alloc] initWithFrame:NSZeroRect];
158 button_.reset(avatarButton);
159 base::scoped_nsobject<CustomThemeButtonCell> cell(
160 [[CustomThemeButtonCell alloc] initWithThemedWindow:isThemedWindow_]);
161 [avatarButton setCell:cell.get()];
163 // Check if the account already has an authentication error.
164 SigninErrorController* errorController =
165 profiles::GetSigninErrorController(browser->profile());
166 hasError_ = errorController && errorController->HasError();
168 [avatarButton setWantsLayer:YES];
169 [self setView:avatarButton];
171 [avatarButton setBezelStyle:NSShadowlessSquareBezelStyle];
172 [avatarButton setButtonType:NSMomentaryChangeButton];
173 [avatarButton setBordered:YES];
175 [avatarButton setAutoresizingMask:NSViewMinXMargin | NSViewMinYMargin];
176 [avatarButton setTarget:self];
177 [avatarButton setAction:@selector(buttonClicked:)];
178 [avatarButton setRightAction:@selector(buttonRightClicked:)];
180 [self updateAvatarButtonAndLayoutParent:NO];
182 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
183 [center addObserver:self
184 selector:@selector(themeDidChangeNotification:)
185 name:kBrowserThemeDidChangeNotification
192 [[NSNotificationCenter defaultCenter] removeObserver:self];
196 - (void)themeDidChangeNotification:(NSNotification*)aNotification {
197 // Redraw the button if the window has switched between themed and native.
198 ThemeService* themeService =
199 ThemeServiceFactory::GetForProfile(browser_->profile());
200 BOOL updatedIsThemedWindow = !themeService->UsingSystemTheme();
201 if (isThemedWindow_ != updatedIsThemedWindow) {
202 isThemedWindow_ = updatedIsThemedWindow;
203 [[button_ cell] setIsThemedWindow:isThemedWindow_];
204 [self updateAvatarButtonAndLayoutParent:YES];
208 - (void)updateAvatarButtonAndLayoutParent:(BOOL)layoutParent {
209 // The button text has a black foreground and a white drop shadow for regular
210 // windows, and a light text with a dark drop shadow for guest windows
211 // which are themed with a dark background.
212 base::scoped_nsobject<NSShadow> shadow([[NSShadow alloc] init]);
213 [shadow setShadowOffset:NSMakeSize(0, -1)];
214 [shadow setShadowBlurRadius:0];
216 NSColor* foregroundColor;
217 if (browser_->profile()->IsGuestSession()) {
218 foregroundColor = [NSColor colorWithCalibratedWhite:1.0 alpha:0.9];
219 [shadow setShadowColor:[NSColor colorWithCalibratedWhite:0.0 alpha:0.4]];
220 } else if (!isThemedWindow_) {
221 foregroundColor = [NSColor blackColor];
222 [shadow setShadowColor:[NSColor colorWithCalibratedWhite:1.0 alpha:0.7]];
224 foregroundColor = [NSColor blackColor];
225 [shadow setShadowColor:[NSColor colorWithCalibratedWhite:1.0 alpha:0.4]];
228 const ProfileInfoCache& cache =
229 g_browser_process->profile_manager()->GetProfileInfoCache();
230 // If there is a single local profile, then use the generic avatar button
231 // instead of the profile name. Never use the generic button if the active
233 bool useGenericButton = (!browser_->profile()->IsGuestSession() &&
234 cache.GetNumberOfProfiles() == 1 &&
235 !cache.ProfileIsAuthenticatedAtIndex(0));
238 NSString* buttonTitle = base::SysUTF16ToNSString(useGenericButton ?
240 profiles::GetAvatarButtonTextForProfile(browser_->profile()));
241 [[button_ cell] setHasError:hasError_ withTitle:buttonTitle];
243 AvatarButton* button =
244 base::mac::ObjCCastStrict<AvatarButton>(button_);
245 if (useGenericButton) {
246 [button setDefaultImage:GetImageFromResourceID(
247 IDR_AVATAR_MAC_BUTTON_AVATAR)];
248 [button setHoverImage:GetImageFromResourceID(
249 IDR_AVATAR_MAC_BUTTON_AVATAR_HOVER)];
250 [button setPressedImage:GetImageFromResourceID(
251 IDR_AVATAR_MAC_BUTTON_AVATAR_PRESSED)];
252 // This is a workaround for an issue in the HoverImageButton where the
253 // button is initially sized incorrectly unless a default image is provided.
254 // See crbug.com/298501.
255 [button setImage:GetImageFromResourceID(IDR_AVATAR_MAC_BUTTON_AVATAR)];
256 [button setImagePosition:NSImageOnly];
257 } else if (hasError_) {
258 [button setDefaultImage:GetImageFromResourceID(
259 IDR_ICON_PROFILES_AVATAR_BUTTON_ERROR)];
260 [button setHoverImage:nil];
261 [button setPressedImage:nil];
262 [button setImage:GetImageFromResourceID(
263 IDR_ICON_PROFILES_AVATAR_BUTTON_ERROR)];
264 [button setImagePosition:NSImageRight];
266 [button setDefaultImage:nil];
267 [button setHoverImage:nil];
268 [button setPressedImage:nil];
269 [button setImagePosition:NSNoImage];
272 base::scoped_nsobject<NSMutableParagraphStyle> paragraphStyle(
273 [[NSMutableParagraphStyle alloc] init]);
274 [paragraphStyle setAlignment:NSLeftTextAlignment];
276 base::scoped_nsobject<NSAttributedString> attributedTitle(
277 [[NSAttributedString alloc]
278 initWithString:buttonTitle
279 attributes:@{ NSShadowAttributeName : shadow.get(),
280 NSForegroundColorAttributeName : foregroundColor,
281 NSParagraphStyleAttributeName : paragraphStyle }]);
282 [button_ setAttributedTitle:attributedTitle];
286 // Because the width of the button might have changed, the parent browser
287 // frame needs to recalculate the button bounds and redraw it.
288 [[BrowserWindowController
289 browserWindowControllerForWindow:browser_->window()->GetNativeWindow()]
294 - (void)updateErrorStatus:(BOOL)hasError {
295 hasError_ = hasError;
296 [self updateAvatarButtonAndLayoutParent:YES];