Extensions cleanup: Merge IsSyncableApp+Extension, ShouldSyncApp+Extension
[chromium-blink-merge.git] / chrome / browser / ui / cocoa / profiles / avatar_button_controller.mm
blobba88a32f2b25823e313338eae03cdd1b73c28d6a
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"
28 namespace {
30 // NSButtons have a default padding of 5px. This button should have a padding
31 // of 8px.
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();
49 }  // namespace
51 // Button cell with a custom border given by a set of nine-patch image grids.
52 @interface CustomThemeButtonCell : NSButtonCell {
53  @private
54    BOOL isThemedWindow_;
55    BOOL hasError_;
57 - (void)setIsThemedWindow:(BOOL)isThemedWindow;
58 - (void)setHasError:(BOOL)hasError withTitle:(NSString*)title;
60 @end
62 @implementation CustomThemeButtonCell
63 - (id)initWithThemedWindow:(BOOL)isThemedWindow {
64   if ((self = [super init])) {
65     isThemedWindow_ = isThemedWindow;
66     hasError_ = false;
67   }
68   return self;
71 - (NSSize)cellSize {
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;
79   } else {
80     buttonSize.width += 2 * kButtonExtraPadding;
81   }
82   buttonSize.height = kButtonHeight;
83   return buttonSize;
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.
97   if (!hasError_)
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;
107   if (isThemedWindow_)
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)setIsThemedWindow:(BOOL)isThemedWindow {
118   isThemedWindow_ = isThemedWindow;
121 - (void)setHasError:(BOOL)hasError withTitle:(NSString*)title {
122   hasError_ = hasError;
123   int messageId = hasError ?
124       IDS_PROFILES_ACCOUNT_BUTTON_AUTH_ERROR_ACCESSIBLE_NAME :
125       IDS_PROFILES_NEW_AVATAR_BUTTON_ACCESSIBLE_NAME;
127   [self accessibilitySetOverrideValue:l10n_util::GetNSStringF(
128       messageId, base::SysNSStringToUTF16(title))
129                          forAttribute:NSAccessibilityTitleAttribute];
132 @end
134 @interface AvatarButtonController (Private)
135 - (void)updateAvatarButtonAndLayoutParent:(BOOL)layoutParent;
136 - (void)updateErrorStatus:(BOOL)hasError;
137 - (void)dealloc;
138 - (void)themeDidChangeNotification:(NSNotification*)aNotification;
139 @end
141 @implementation AvatarButtonController
143 - (id)initWithBrowser:(Browser*)browser {
144   if ((self = [super initWithBrowser:browser])) {
145     ThemeService* themeService =
146         ThemeServiceFactory::GetForProfile(browser->profile());
147     isThemedWindow_ = !themeService->UsingSystemTheme();
149     AvatarButton* avatarButton =
150         [[AvatarButton alloc] initWithFrame:NSZeroRect];
151     button_.reset(avatarButton);
152     base::scoped_nsobject<CustomThemeButtonCell> cell(
153         [[CustomThemeButtonCell alloc] initWithThemedWindow:isThemedWindow_]);
154     [avatarButton setCell:cell.get()];
156     // Check if the account already has an authentication error.
157     SigninErrorController* errorController =
158         profiles::GetSigninErrorController(browser->profile());
159     hasError_ = errorController && errorController->HasError();
161     [avatarButton setWantsLayer:YES];
162     [self setView:avatarButton];
164     [avatarButton setBezelStyle:NSShadowlessSquareBezelStyle];
165     [avatarButton setButtonType:NSMomentaryChangeButton];
166     [avatarButton setBordered:YES];
168     [avatarButton setAutoresizingMask:NSViewMinXMargin | NSViewMinYMargin];
169     [avatarButton setTarget:self];
170     [avatarButton setAction:@selector(buttonClicked:)];
171     [avatarButton setRightAction:@selector(buttonRightClicked:)];
173     [self updateAvatarButtonAndLayoutParent:NO];
175     NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
176     [center addObserver:self
177                selector:@selector(themeDidChangeNotification:)
178                    name:kBrowserThemeDidChangeNotification
179                  object:nil];
180   }
181   return self;
184 - (void)dealloc {
185   [[NSNotificationCenter defaultCenter] removeObserver:self];
186   [super dealloc];
189 - (void)themeDidChangeNotification:(NSNotification*)aNotification {
190   // Redraw the button if the window has switched between themed and native.
191   ThemeService* themeService =
192       ThemeServiceFactory::GetForProfile(browser_->profile());
193   BOOL updatedIsThemedWindow = !themeService->UsingSystemTheme();
194   if (isThemedWindow_ != updatedIsThemedWindow) {
195     isThemedWindow_ = updatedIsThemedWindow;
196     [[button_ cell] setIsThemedWindow:isThemedWindow_];
197     [self updateAvatarButtonAndLayoutParent:YES];
198   }
201 - (void)updateAvatarButtonAndLayoutParent:(BOOL)layoutParent {
202   // The button text has a black foreground and a white drop shadow for regular
203   // windows, and a light text with a dark drop shadow for guest windows
204   // which are themed with a dark background.
205   base::scoped_nsobject<NSShadow> shadow([[NSShadow alloc] init]);
206   [shadow setShadowOffset:NSMakeSize(0, -1)];
207   [shadow setShadowBlurRadius:0];
209   NSColor* foregroundColor;
210   if (browser_->profile()->IsGuestSession()) {
211     foregroundColor = [NSColor colorWithCalibratedWhite:1.0 alpha:0.9];
212     [shadow setShadowColor:[NSColor colorWithCalibratedWhite:0.0 alpha:0.4]];
213   } else if (!isThemedWindow_) {
214     foregroundColor = [NSColor blackColor];
215     [shadow setShadowColor:[NSColor colorWithCalibratedWhite:1.0 alpha:0.7]];
216   } else {
217     foregroundColor = [NSColor blackColor];
218     [shadow setShadowColor:[NSColor colorWithCalibratedWhite:1.0 alpha:0.4]];
219   }
221   const ProfileInfoCache& cache =
222       g_browser_process->profile_manager()->GetProfileInfoCache();
223   // If there is a single local profile, then use the generic avatar button
224   // instead of the profile name. Never use the generic button if the active
225   // profile is Guest.
226   bool useGenericButton = (!browser_->profile()->IsGuestSession() &&
227                            cache.GetNumberOfProfiles() == 1 &&
228                            !cache.ProfileIsAuthenticatedAtIndex(0));
231   NSString* buttonTitle = base::SysUTF16ToNSString(useGenericButton ?
232       base::string16() :
233       profiles::GetAvatarButtonTextForProfile(browser_->profile()));
234   [[button_ cell] setHasError:hasError_ withTitle:buttonTitle];
236   AvatarButton* button =
237       base::mac::ObjCCastStrict<AvatarButton>(button_);
238   if (useGenericButton) {
239     [button setDefaultImage:GetImageFromResourceID(
240         IDR_AVATAR_MAC_BUTTON_AVATAR)];
241     [button setHoverImage:GetImageFromResourceID(
242         IDR_AVATAR_MAC_BUTTON_AVATAR_HOVER)];
243     [button setPressedImage:GetImageFromResourceID(
244         IDR_AVATAR_MAC_BUTTON_AVATAR_PRESSED)];
245     // This is a workaround for an issue in the HoverImageButton where the
246     // button is initially sized incorrectly unless a default image is provided.
247     // See crbug.com/298501.
248     [button setImage:GetImageFromResourceID(IDR_AVATAR_MAC_BUTTON_AVATAR)];
249     [button setImagePosition:NSImageOnly];
250   } else if (hasError_) {
251     [button setDefaultImage:GetImageFromResourceID(
252         IDR_ICON_PROFILES_AVATAR_BUTTON_ERROR)];
253     [button setHoverImage:nil];
254     [button setPressedImage:nil];
255     [button setImage:GetImageFromResourceID(
256         IDR_ICON_PROFILES_AVATAR_BUTTON_ERROR)];
257     [button setImagePosition:NSImageRight];
258   } else {
259     [button setDefaultImage:nil];
260     [button setHoverImage:nil];
261     [button setPressedImage:nil];
262     [button setImagePosition:NSNoImage];
263   }
265   base::scoped_nsobject<NSMutableParagraphStyle> paragraphStyle(
266       [[NSMutableParagraphStyle alloc] init]);
267   [paragraphStyle setAlignment:NSLeftTextAlignment];
269   base::scoped_nsobject<NSAttributedString> attributedTitle(
270       [[NSAttributedString alloc]
271           initWithString:buttonTitle
272               attributes:@{ NSShadowAttributeName : shadow.get(),
273                             NSForegroundColorAttributeName : foregroundColor,
274                             NSParagraphStyleAttributeName : paragraphStyle }]);
275   [button_ setAttributedTitle:attributedTitle];
276   [button_ sizeToFit];
278   if (layoutParent) {
279     // Because the width of the button might have changed, the parent browser
280     // frame needs to recalculate the button bounds and redraw it.
281     [[BrowserWindowController
282         browserWindowControllerForWindow:browser_->window()->GetNativeWindow()]
283         layoutSubviews];
284   }
287 - (void)updateErrorStatus:(BOOL)hasError {
288   hasError_ = hasError;
289   [self updateAvatarButtonAndLayoutParent:YES];
292 @end