summaryrefslogtreecommitdiffstats
path: root/chrome/browser/ui/cocoa/profiles/avatar_menu_bubble_controller.mm
blob: 588fdea9347c1ac9f41c41f8d9638c264c36d600 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import "chrome/browser/ui/cocoa/profiles/avatar_menu_bubble_controller.h"

#include "base/mac/bundle_locations.h"
#include "base/strings/sys_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/avatar_menu.h"
#include "chrome/browser/profiles/profile_info_cache.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/profiles/profile_metrics.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#import "chrome/browser/ui/cocoa/info_bubble_view.h"
#import "chrome/browser/ui/cocoa/info_bubble_window.h"
#include "chrome/grit/generated_resources.h"
#include "grit/theme_resources.h"
#import "third_party/google_toolbox_for_mac/src/AppKit/GTMUILocalizerAndLayoutTweaker.h"
#import "ui/base/cocoa/cocoa_base_utils.h"
#import "ui/base/cocoa/controls/hyperlink_button_cell.h"
#include "ui/base/l10n/l10n_util_mac.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/image/image.h"

@interface AvatarMenuBubbleController (Private)
- (AvatarMenu*)menu;
- (NSView*)configureSupervisedUserInformation:(CGFloat)width;
- (NSButton*)configureNewUserButton:(CGFloat)yOffset
                  updateWidthAdjust:(CGFloat*)widthAdjust;
- (NSButton*)configureSwitchUserButton:(CGFloat)yOffset
                     updateWidthAdjust:(CGFloat*)widthAdjust;
- (AvatarMenuItemController*)initAvatarItem:(int)itemIndex
                          updateWidthAdjust:(CGFloat*)widthAdjust
                                 setYOffset:(CGFloat)yOffset;
- (void)setWindowFrame:(CGFloat)yOffset widthAdjust:(CGFloat)width;
- (void)initMenuContents;
- (void)initSupervisedUserContents;
- (void)keyDown:(NSEvent*)theEvent;
- (void)moveDown:(id)sender;
- (void)moveUp:(id)sender;
- (void)insertNewline:(id)sender;
- (void)highlightNextItemByDelta:(NSInteger)delta;
- (void)highlightItem:(AvatarMenuItemController*)newItem;
@end

namespace {

// Constants taken from the Windows/Views implementation at:
//    chrome/browser/ui/views/avatar_menu_bubble_view.cc
const CGFloat kBubbleMinWidth = 175;
const CGFloat kBubbleMaxWidth = 800;
const CGFloat kMaxItemTextWidth = 200;

// Values derived from the XIB.
const CGFloat kVerticalSpacing = 10.0;
const CGFloat kLinkSpacing = 15.0;
const CGFloat kLabelInset = 49.0;

// The offset of the supervised user information label and the "switch user"
// link.
const CGFloat kSupervisedUserSpacing = 26.0;

}  // namespace

@implementation AvatarMenuBubbleController

- (id)initWithBrowser:(Browser*)parentBrowser
           anchoredAt:(NSPoint)point {

  // Pass in a NULL observer. Rebuilding while the bubble is open will cause it
  // to be positioned incorrectly. Since the bubble will be dismissed on losing
  // key status, it's impossible for the user to edit the information in a
  // meaningful way such that it would need to be redrawn.
  AvatarMenu* menu = new AvatarMenu(
      &g_browser_process->profile_manager()->GetProfileInfoCache(),
      NULL, parentBrowser);
  menu->RebuildMenu();

  if ((self = [self initWithMenu:menu
                     parentWindow:parentBrowser->window()->GetNativeWindow()
                       anchoredAt:point])) {
  }
  return self;
}

- (IBAction)newProfile:(id)sender {
  menu_->AddNewProfile(ProfileMetrics::ADD_NEW_USER_ICON);
}

- (IBAction)switchToProfile:(id)sender {
  // Check the event flags to see if a new window should be crated.
  bool always_create = ui::WindowOpenDispositionFromNSEvent(
      [NSApp currentEvent]) == NEW_WINDOW;
  menu_->SwitchToProfile([sender menuIndex], always_create,
                         ProfileMetrics::SWITCH_PROFILE_ICON);
}

- (IBAction)editProfile:(id)sender {
  menu_->EditProfile([sender menuIndex]);
}

- (IBAction)switchProfile:(id)sender {
  expanded_ = YES;
  [self performLayout];
}

// Private /////////////////////////////////////////////////////////////////////

- (id)initWithMenu:(AvatarMenu*)menu
       parentWindow:(NSWindow*)parent
         anchoredAt:(NSPoint)point {
  // Use an arbitrary height because it will reflect the size of the content.
  NSRect contentRect = NSMakeRect(0, 0, kBubbleMinWidth, 150);
  // Create an empty window into which content is placed.
  base::scoped_nsobject<InfoBubbleWindow> window(
      [[InfoBubbleWindow alloc] initWithContentRect:contentRect
                                          styleMask:NSBorderlessWindowMask
                                            backing:NSBackingStoreBuffered
                                              defer:NO]);
  if ((self = [super initWithWindow:window
                       parentWindow:parent
                         anchoredAt:point])) {
    menu_.reset(menu);

    [window accessibilitySetOverrideValue:
        l10n_util::GetNSString(IDS_PROFILES_BUBBLE_ACCESSIBLE_NAME)
                             forAttribute:NSAccessibilityTitleAttribute];
    [window accessibilitySetOverrideValue:
        l10n_util::GetNSString(IDS_PROFILES_BUBBLE_ACCESSIBLE_DESCRIPTION)
                             forAttribute:NSAccessibilityHelpAttribute];

    [[self bubble] setArrowLocation:info_bubble::kTopRight];
    [self performLayout];
  }
  return self;
}

- (AvatarMenuItemController*)initAvatarItem:(int)itemIndex
                          updateWidthAdjust:(CGFloat*)widthAdjust
                                 setYOffset:(CGFloat)yOffset {
  ResourceBundle& rb = ResourceBundle::GetSharedInstance();
  const AvatarMenu::Item& item = menu_->GetItemAt(itemIndex);
  // Create the item view controller. Autorelease it because it will be owned
  // by the |items_| array.
  AvatarMenuItemController* itemView =
      [[[AvatarMenuItemController alloc] initWithMenuIndex:itemIndex
                                             menuController:self] autorelease];
  itemView.iconView.image = item.icon.ToNSImage();

  // Adjust the name field to fit the string. If it overflows, record by how
  // much the window needs to grow to accomodate the new size of the field.
  NSTextField* nameField = itemView.nameField;
  nameField.stringValue = base::SysUTF16ToNSString(item.name);
  NSSize delta = [GTMUILocalizerAndLayoutTweaker sizeToFitView:nameField];
  if (NSWidth([nameField frame]) > kMaxItemTextWidth) {
    delta.width -= (NSWidth([nameField frame]) - kMaxItemTextWidth);
    NSRect frame = [nameField frame];
    frame.size.width = kMaxItemTextWidth;
    [nameField setFrame:frame];
  }
  *widthAdjust = std::max(*widthAdjust, delta.width);

  // Repeat for the sync state/email.
  NSTextField* emailField = itemView.emailField;
  emailField.stringValue = base::SysUTF16ToNSString(item.sync_state);
  delta = [GTMUILocalizerAndLayoutTweaker sizeToFitView:emailField];
  if (NSWidth([emailField frame]) > kMaxItemTextWidth) {
    delta.width -= (NSWidth([emailField frame]) - kMaxItemTextWidth);
    NSRect frame = [emailField frame];
    frame.size.width = kMaxItemTextWidth;
    [emailField setFrame:frame];
  }
  *widthAdjust = std::max(*widthAdjust, delta.width);

  if (!item.active) {
    // In the inactive case, hide additional UI.
    [itemView.activeView setHidden:YES];
    [itemView.editButton setHidden:YES];
  } else {
    // Otherwise, set up the edit button and its three interaction states.
    itemView.activeView.image =
        rb.GetImageNamed(IDR_PROFILE_SELECTED).ToNSImage();
  }

  // Add the item to the content view.
  [[itemView view] setFrameOrigin:NSMakePoint(0, yOffset)];

  // Keep track of the view controller.
  [items_ addObject:itemView];
  return itemView;
}

- (void)setWindowFrame:(CGFloat)yOffset widthAdjust:(CGFloat)width {
  // Set the window frame, clamping the width at a sensible max.
  NSRect frame = [[self window] frame];
  // Adjust the origin after we have switched from the supervised user menu to
  // the regular menu.
  CGFloat newWidth = std::min(kBubbleMinWidth + width, kBubbleMaxWidth);
  if (expanded_) {
    frame.origin.x += frame.size.width - newWidth;
    frame.origin.y += frame.size.height - yOffset;
  }
  frame.size.height = yOffset;
  frame.size.width = newWidth;
  [[self window] setFrame:frame display:YES];
}

- (void)initMenuContents {
  NSView* contentView = [[self window] contentView];

  // |yOffset| is the next position at which to draw in contentView coordinates.
  // Use a little more vertical spacing because the items have padding built-
  // into the xib, and this gives a little more space to visually match.
  CGFloat yOffset = kLinkSpacing;
  CGFloat widthAdjust = 0;

  if (menu_->ShouldShowAddNewProfileLink()) {
    // Since drawing happens bottom-up, start with the "New User" link.
    NSButton* newButton =
        [self configureNewUserButton:yOffset updateWidthAdjust:&widthAdjust];
    [contentView addSubview:newButton];
    yOffset += NSHeight([newButton frame]) + kVerticalSpacing;

    NSBox* separator = [self horizontalSeparatorWithFrame:
        NSMakeRect(10, yOffset, NSWidth([contentView frame]) - 20, 0)];
    [separator setAutoresizingMask:NSViewWidthSizable];
    [contentView addSubview:separator];

    yOffset += NSHeight([separator frame]);
  } else {
    yOffset = 7;
  }

  // Loop over the profiles in reverse, constructing the menu items.
  for (int i = menu_->GetNumberOfItems() - 1; i >= 0; --i) {
    AvatarMenuItemController* itemView = [self initAvatarItem:i
                                            updateWidthAdjust:&widthAdjust
                                                   setYOffset:yOffset];
    [contentView addSubview:[itemView view]];
    yOffset += NSHeight([[itemView view] frame]);
  }

  yOffset += kVerticalSpacing * 1.5;
  [self setWindowFrame:yOffset widthAdjust:widthAdjust];
}

- (void)initSupervisedUserContents {
  NSView* contentView = [[self window] contentView];

  // |yOffset| is the next position at which to draw in contentView coordinates.
  // Use a little more vertical spacing because the items have padding built-
  // into the xib, and this gives a little more space to visually match.
  CGFloat yOffset = kLinkSpacing;
  CGFloat widthAdjust = 0;

  // Since drawing happens bottom-up, start with the "Switch User" link.
  NSButton* newButton =
      [self configureSwitchUserButton:yOffset updateWidthAdjust:&widthAdjust];
  [contentView addSubview:newButton];
  yOffset += NSHeight([newButton frame]) + kVerticalSpacing;

  NSBox* separator = [self horizontalSeparatorWithFrame:
      NSMakeRect(10, yOffset, NSWidth([contentView frame]) - 20, 0)];
  [separator setAutoresizingMask:NSViewWidthSizable];
  [contentView addSubview:separator];

  yOffset += NSHeight([separator frame]) + kVerticalSpacing;

  // First init the active profile in order to determine the required width. We
  // will have to adjust its frame later after adding general information about
  // supervised users.
  AvatarMenuItemController* itemView =
      [self initAvatarItem:menu_->GetActiveProfileIndex()
          updateWidthAdjust:&widthAdjust
                 setYOffset:yOffset];

  // Don't increase the width too much (the total size should be at most
  // |kBubbleMaxWidth|).
  widthAdjust = std::min(widthAdjust, kBubbleMaxWidth - kBubbleMinWidth);
  CGFloat newWidth = kBubbleMinWidth + widthAdjust;

  // Add general information about supervised users.
  NSView* info = [self configureSupervisedUserInformation:newWidth];
  [info setFrameOrigin:NSMakePoint(0, yOffset)];
  [contentView addSubview:info];
  yOffset += NSHeight([info frame]) + kVerticalSpacing;

  separator = [self horizontalSeparatorWithFrame:
      NSMakeRect(10, yOffset, NSWidth([contentView frame]) - 20, 0)];
  [separator setAutoresizingMask:NSViewWidthSizable];
  [contentView addSubview:separator];

  yOffset += NSHeight([separator frame]);

  // Now update the frame of the active profile and add it.
  NSRect frame = [[itemView view] frame];
  frame.origin.y = yOffset;
  [[itemView view] setFrame:frame];
  [contentView addSubview:[itemView view]];

  yOffset += NSHeight(frame) + kVerticalSpacing * 1.5;
  [self setWindowFrame:yOffset widthAdjust:widthAdjust];
}

- (void)performLayout {
  NSView* contentView = [[self window] contentView];

  // Reset the array of controllers and remove all the views.
  items_.reset([[NSMutableArray alloc] init]);
  [contentView setSubviews:[NSArray array]];

  if (menu_->GetSupervisedUserInformation().empty() || expanded_)
    [self initMenuContents];
  else
    [self initSupervisedUserContents];
}

- (NSView*)configureSupervisedUserInformation:(CGFloat)width {
  base::scoped_nsobject<NSView> container(
      [[NSView alloc] initWithFrame:NSZeroRect]);

  // Add the limited user icon on the left side of the information TextView.
  base::scoped_nsobject<NSImageView> iconView(
      [[NSImageView alloc] initWithFrame:NSMakeRect(5, 0, 16, 16)]);
  [iconView setImage:menu_->GetSupervisedUserIcon().ToNSImage()];
  [container addSubview:iconView];

  NSString* info =
      base::SysUTF16ToNSString(menu_->GetSupervisedUserInformation());
  NSDictionary* attributes =
      @{ NSFontAttributeName : [NSFont labelFontOfSize:12] };
  base::scoped_nsobject<NSAttributedString> attrString(
      [[NSAttributedString alloc] initWithString:info attributes:attributes]);
  base::scoped_nsobject<NSTextView> label(
      [[NSTextView alloc] initWithFrame:NSMakeRect(
          kSupervisedUserSpacing, 0, width - kSupervisedUserSpacing - 5, 0)]);
  [[label textStorage] setAttributedString:attrString];
  [label setHorizontallyResizable:NO];
  [label setEditable:NO];
  [label sizeToFit];
  [container addSubview:label];
  [container setFrameSize:NSMakeSize(width, NSHeight([label frame]))];

  // Reposition the limited user icon so that it is on top.
  [iconView setFrameOrigin:NSMakePoint(5, NSHeight([label frame]) - 16)];
  return container.autorelease();
}

- (NSButton*)configureNewUserButton:(CGFloat)yOffset
                  updateWidthAdjust:(CGFloat*)widthAdjust {
  base::scoped_nsobject<NSButton> newButton([[NSButton alloc] initWithFrame:
          NSMakeRect(kLabelInset, yOffset, kBubbleMinWidth - kLabelInset, 16)]);
  base::scoped_nsobject<HyperlinkButtonCell> buttonCell(
      [[HyperlinkButtonCell alloc] initTextCell:
              l10n_util::GetNSString(IDS_PROFILES_CREATE_NEW_PROFILE_LINK)]);
  [newButton setCell:buttonCell.get()];
  [newButton setFont:[NSFont labelFontOfSize:12.0]];
  [newButton setBezelStyle:NSRegularSquareBezelStyle];
  [newButton setTarget:self];
  [newButton setAction:@selector(newProfile:)];
  NSSize delta = [GTMUILocalizerAndLayoutTweaker sizeToFitView:newButton];
  if (delta.width > 0)
    *widthAdjust = std::max(*widthAdjust, delta.width);
  return newButton.autorelease();
}

- (NSButton*)configureSwitchUserButton:(CGFloat)yOffset
                     updateWidthAdjust:(CGFloat*)widthAdjust {
  base::scoped_nsobject<NSButton> newButton(
      [[NSButton alloc] initWithFrame:NSMakeRect(
          kSupervisedUserSpacing, yOffset, kBubbleMinWidth - kLabelInset, 16)]);
  base::scoped_nsobject<HyperlinkButtonCell> buttonCell(
      [[HyperlinkButtonCell alloc] initTextCell:
              l10n_util::GetNSString(IDS_PROFILES_SWITCH_PROFILE_LINK)]);
  [newButton setCell:buttonCell.get()];
  [newButton setFont:[NSFont labelFontOfSize:12.0]];
  [newButton setBezelStyle:NSRegularSquareBezelStyle];
  [newButton setTarget:self];
  [newButton setAction:@selector(switchProfile:)];
  NSSize delta = [GTMUILocalizerAndLayoutTweaker sizeToFitView:newButton];
  if (delta.width > 0)
    *widthAdjust = std::max(*widthAdjust, delta.width);
  return newButton.autorelease();
}

- (NSMutableArray*)items {
  return items_.get();
}

- (void)keyDown:(NSEvent*)theEvent {
  [self interpretKeyEvents:[NSArray arrayWithObject:theEvent]];
}

- (void)moveDown:(id)sender {
  [self highlightNextItemByDelta:-1];
}

- (void)moveUp:(id)sender {
  [self highlightNextItemByDelta:1];
}

- (void)insertNewline:(id)sender {
  for (AvatarMenuItemController* item in items_.get()) {
    if ([item isHighlighted]) {
      [self switchToProfile:item];
      return;
    }
  }
}

- (void)highlightNextItemByDelta:(NSInteger)delta {
  NSUInteger count = [items_ count];
  if (count == 0)
    return;

  NSInteger old_index = -1;
  for (NSUInteger i = 0; i < count; ++i) {
    if ([[items_ objectAtIndex:i] isHighlighted]) {
      old_index = i;
      break;
    }
  }

  NSInteger new_index;
  // If nothing is selected then start at the top if we're going down and start
  // at the bottom if we're going up.
  if (old_index == -1)
    new_index = delta < 0 ? (count - 1) : 0;
  else
    new_index = old_index + delta;

  // Cap the index. We don't wrap around to match the behavior of Mac menus.
  new_index =
      std::min(std::max(static_cast<NSInteger>(0), new_index),
               static_cast<NSInteger>(count - 1));

  [self highlightItem:[items_ objectAtIndex:new_index]];
}

- (void)highlightItem:(AvatarMenuItemController*)newItem {
  AvatarMenuItemController* oldItem = nil;
  for (AvatarMenuItemController* item in items_.get()) {
    if ([item isHighlighted]) {
      oldItem = item;
      break;
    }
  }

  if (oldItem == newItem)
    return;

  [oldItem setIsHighlighted:NO];
  [newItem setIsHighlighted:YES];
}


@end

// Menu Item Controller ////////////////////////////////////////////////////////

@interface AvatarMenuItemController (Private)
- (void)animateFromView:(NSView*)outView toView:(NSView*)inView;
@end

@implementation AvatarMenuItemController

@synthesize menuIndex = menuIndex_;
@synthesize isHighlighted = isHighlighted_;
@synthesize iconView = iconView_;
@synthesize activeView = activeView_;
@synthesize nameField = nameField_;
@synthesize emailField = emailField_;
@synthesize editButton = editButton_;

- (id)initWithMenuIndex:(size_t)menuIndex
          menuController:(AvatarMenuBubbleController*)controller {
  if ((self = [super initWithNibName:@"AvatarMenuItem"
                              bundle:base::mac::FrameworkBundle()])) {
    menuIndex_ = menuIndex;
    controller_ = controller;
    [self loadView];
    [nameField_ setAutoresizingMask:NSViewNotSizable];
    [[nameField_ cell] setLineBreakMode:NSLineBreakByTruncatingTail];
    [emailField_ setAutoresizingMask:NSViewNotSizable];
    [[emailField_ cell] setLineBreakMode:NSLineBreakByTruncatingTail];
  }
  return self;
}

- (void)dealloc {
  static_cast<AvatarMenuItemView*>(self.view).viewController = nil;
  [linkAnimation_ stopAnimation];
  [linkAnimation_ setDelegate:nil];
  [super dealloc];
}

- (void)awakeFromNib {
  [GTMUILocalizerAndLayoutTweaker sizeToFitView:self.editButton];
  self.editButton.hidden = YES;
}

- (IBAction)switchToProfile:(id)sender {
  [controller_ switchToProfile:self];
}

- (IBAction)editProfile:(id)sender {
  [controller_ editProfile:self];
}

- (void)highlightForEventType:(NSEventType)type {
  switch (type) {
    case NSMouseEntered:
      [controller_ highlightItem:self];
      break;

    case NSMouseExited:
      [controller_ highlightItem:nil];
      break;

    default:
      NOTREACHED();
  };
}

- (void)setIsHighlighted:(BOOL)isHighlighted {
  if (isHighlighted_ == isHighlighted)
    return;

  isHighlighted_ = isHighlighted;
  [[self view] setNeedsDisplay:YES];

  // Cancel any running animation.
  if (linkAnimation_.get()) {
    [NSObject cancelPreviousPerformRequestsWithTarget:linkAnimation_
                                             selector:@selector(startAnimation)
                                               object:nil];
  }

  // Fade the edit link in or out only if this is the active view.
  if (self.activeView.isHidden)
    return;

  if (isHighlighted_) {
    [self animateFromView:self.emailField toView:self.editButton];
  } else {
    // If the edit button is visible or the animation to make it so is
    // running, stop the animation and fade it back to the email. If not, then
    // don't run an animation to prevent flickering.
    if (!self.editButton.isHidden || [linkAnimation_ isAnimating]) {
      [linkAnimation_ stopAnimation];
      linkAnimation_.reset();
      [self animateFromView:self.editButton toView:self.emailField];
    }
  }
}

- (void)animateFromView:(NSView*)outView toView:(NSView*)inView {
  const NSTimeInterval kAnimationDuration = 0.175;

  NSDictionary* outDict = [NSDictionary dictionaryWithObjectsAndKeys:
      outView, NSViewAnimationTargetKey,
      NSViewAnimationFadeOutEffect, NSViewAnimationEffectKey,
      nil
  ];
  NSDictionary* inDict = [NSDictionary dictionaryWithObjectsAndKeys:
      inView, NSViewAnimationTargetKey,
      NSViewAnimationFadeInEffect, NSViewAnimationEffectKey,
      nil
  ];

  linkAnimation_.reset([[NSViewAnimation alloc] initWithViewAnimations:
      [NSArray arrayWithObjects:outDict, inDict, nil]]);
  [linkAnimation_ setDelegate:self];
  [linkAnimation_ setDuration:kAnimationDuration];

  [self willStartAnimation:linkAnimation_];

  [linkAnimation_ performSelector:@selector(startAnimation)
                       withObject:nil
                       afterDelay:0.2];
}

- (void)willStartAnimation:(NSAnimation*)animation {
}

- (void)animationDidEnd:(NSAnimation*)animation {
  if (animation == linkAnimation_.get())
    linkAnimation_.reset();
}

- (void)animationDidStop:(NSAnimation*)animation {
  if (animation == linkAnimation_.get())
    linkAnimation_.reset();
}

@end

// Profile Switch Button ///////////////////////////////////////////////////////

@implementation AvatarMenuItemView

@synthesize viewController = viewController_;

- (void)awakeFromNib {
  [self updateTrackingAreas];
}

- (void)updateTrackingAreas {
  if (trackingArea_.get())
    [self removeTrackingArea:trackingArea_.get()];

  trackingArea_.reset(
      [[CrTrackingArea alloc] initWithRect:[self bounds]
                                   options:NSTrackingMouseEnteredAndExited |
                                           NSTrackingActiveInKeyWindow
                                     owner:self
                                  userInfo:nil]);
  [self addTrackingArea:trackingArea_.get()];

  [super updateTrackingAreas];
}

- (void)mouseEntered:(id)sender {
  [viewController_ highlightForEventType:[[NSApp currentEvent] type]];
  [self setNeedsDisplay:YES];
}

- (void)mouseExited:(id)sender {
  [viewController_ highlightForEventType:[[NSApp currentEvent] type]];
  [self setNeedsDisplay:YES];
}

- (void)mouseUp:(id)sender {
  [viewController_ switchToProfile:self];
}

- (void)drawRect:(NSRect)dirtyRect {
  NSColor* backgroundColor = nil;
  if ([viewController_ isHighlighted]) {
    backgroundColor = [NSColor colorWithCalibratedRed:223.0/255
                                                green:238.0/255
                                                 blue:246.0/255
                                                alpha:1.0];
  } else {
    backgroundColor = [NSColor clearColor];
  }

  [backgroundColor set];
  [NSBezierPath fillRect:[self bounds]];
}

// Make sure the element is focusable for accessibility.
- (BOOL)canBecomeKeyView {
  return YES;
}

- (BOOL)accessibilityIsIgnored {
  return NO;
}

- (NSArray*)accessibilityAttributeNames {
  NSMutableArray* attributes =
      [[super accessibilityAttributeNames] mutableCopy];
  [attributes addObject:NSAccessibilityTitleAttribute];
  [attributes addObject:NSAccessibilityEnabledAttribute];

  return [attributes autorelease];
}

- (NSArray*)accessibilityActionNames {
  NSArray* parentActions = [super accessibilityActionNames];
  return [parentActions arrayByAddingObject:NSAccessibilityPressAction];
}

- (id)accessibilityAttributeValue:(NSString*)attribute {
  if ([attribute isEqual:NSAccessibilityRoleAttribute])
    return NSAccessibilityButtonRole;

  if ([attribute isEqual:NSAccessibilityRoleDescriptionAttribute])
    return NSAccessibilityRoleDescription(NSAccessibilityButtonRole, nil);

  if ([attribute isEqual:NSAccessibilityTitleAttribute]) {
    return l10n_util::GetNSStringF(
        IDS_PROFILES_SWITCH_TO_PROFILE_ACCESSIBLE_NAME,
        base::SysNSStringToUTF16(self.viewController.nameField.stringValue));
  }

  if ([attribute isEqual:NSAccessibilityEnabledAttribute])
    return [NSNumber numberWithBool:YES];

  return [super accessibilityAttributeValue:attribute];
}

- (void)accessibilityPerformAction:(NSString*)action {
  if ([action isEqual:NSAccessibilityPressAction]) {
    [viewController_ switchToProfile:self];
    return;
  }

  [super accessibilityPerformAction:action];
}

@end

////////////////////////////////////////////////////////////////////////////////

@implementation AccessibilityIgnoredImageCell
- (BOOL)accessibilityIsIgnored {
  return YES;
}
@end

@implementation AccessibilityIgnoredTextFieldCell
- (BOOL)accessibilityIsIgnored {
  return YES;
}
@end