File: browser_action_button_interactive_uitest.mm

package info (click to toggle)
chromium-browser 57.0.2987.98-1~deb8u1
  • links: PTS, VCS
  • area: main
  • in suites: jessie
  • size: 2,637,852 kB
  • ctags: 2,544,394
  • sloc: cpp: 12,815,961; ansic: 3,676,222; python: 1,147,112; asm: 526,608; java: 523,212; xml: 286,794; perl: 92,654; sh: 86,408; objc: 73,271; makefile: 27,698; cs: 18,487; yacc: 13,031; tcl: 12,957; pascal: 4,875; ml: 4,716; lex: 3,904; sql: 3,862; ruby: 1,982; lisp: 1,508; php: 1,368; exp: 404; awk: 325; csh: 117; jsp: 39; sed: 37
file content (686 lines) | stat: -rw-r--r-- 27,236 bytes parent folder | download
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
// Copyright 2015 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/extensions/browser_action_button.h"

#import <Cocoa/Cocoa.h>

#include <memory>

#include "base/bind.h"
#include "base/callback.h"
#include "base/callback_helpers.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/extensions/extension_action_test_util.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/ui/browser_window.h"
#import "chrome/browser/ui/cocoa/app_menu/app_menu_controller.h"
#import "chrome/browser/ui/cocoa/browser_window_controller.h"
#import "chrome/browser/ui/cocoa/extensions/browser_actions_container_view.h"
#import "chrome/browser/ui/cocoa/extensions/browser_actions_controller.h"
#import "chrome/browser/ui/cocoa/test/run_loop_testing.h"
#import "chrome/browser/ui/cocoa/toolbar/toolbar_controller.h"
#include "chrome/browser/ui/global_error/global_error.h"
#include "chrome/browser/ui/global_error/global_error_service.h"
#include "chrome/browser/ui/global_error/global_error_service_factory.h"
#include "chrome/browser/ui/toolbar/component_toolbar_actions_factory.h"
#include "chrome/browser/ui/toolbar/media_router_action.h"
#include "chrome/browser/ui/toolbar/toolbar_actions_bar.h"
#include "chrome/browser/ui/toolbar/toolbar_actions_model.h"
#include "chrome/test/base/interactive_test_utils.h"
#include "extensions/common/feature_switch.h"
#include "ui/base/cocoa/cocoa_base_utils.h"
#import "ui/events/test/cocoa_test_event_utils.h"

namespace {

const int kMenuPadding = 26;

// A simple error class that has a menu item.
class MenuError : public GlobalError {
 public:
  MenuError() {}
  ~MenuError() override {}

  bool HasMenuItem() override { return true; }
  int MenuItemCommandID() override {
    // An arbitrary high id so that it's not taken.
    return 65536;
  }
  base::string16 MenuItemLabel() override {
    const char kErrorMessage[] =
        "This is a really long error message that will cause the app menu "
        "to have increased width";
    return base::ASCIIToUTF16(kErrorMessage);
  }
  void ExecuteMenuItem(Browser* browser) override {}

  bool HasBubbleView() override { return false; }
  bool HasShownBubbleView() override { return false; }
  void ShowBubbleView(Browser* browser) override {}
  GlobalErrorBubbleViewBase* GetBubbleView() override { return nullptr; }

 private:
  DISALLOW_COPY_AND_ASSIGN(MenuError);
};

// Returns the center point for a particular |view|.
NSPoint GetCenterPoint(NSView* view) {
  NSWindow* window = [view window];
  NSScreen* screen = [window screen];
  DCHECK(screen);

  // Converts the center position of the view into the coordinates accepted
  // by ui_controls methods.
  NSRect bounds = [view bounds];
  NSPoint center = NSMakePoint(NSMidX(bounds), NSMidY(bounds));
  center = [view convertPoint:center toView:nil];
  center = ui::ConvertPointFromWindowToScreen(window, center);
  return NSMakePoint(center.x, [screen frame].size.height - center.y);
}

// Moves the mouse (synchronously) to the center of the given |view|.
void MoveMouseToCenter(NSView* view) {
  NSPoint centerPoint = GetCenterPoint(view);
  base::RunLoop runLoop;
  ui_controls::SendMouseMoveNotifyWhenDone(
      centerPoint.x, centerPoint.y, runLoop.QuitClosure());
  runLoop.Run();
}

// Simulates a click on the action button in the overflow menu, and runs
// |closure| upon completion.
void ClickOnOverflowedAction(ToolbarController* toolbarController,
                             const base::Closure& closure) {
  AppMenuController* appMenuController = [toolbarController appMenuController];
  // The app menu should start as open (since that's where the overflowed
  // actions are).
  EXPECT_TRUE([appMenuController isMenuOpen]);
  BrowserActionsController* overflowController =
      [appMenuController browserActionsController];

  ASSERT_TRUE(overflowController);
  BrowserActionButton* actionButton = [overflowController buttonWithIndex:0];
  // The action should be attached to a superview.
  EXPECT_TRUE([actionButton superview]);

  // ui_controls:: methods don't play nice when there is an open menu (like the
  // app menu). Instead, simulate a right click by feeding the event directly to
  // the button.
  NSPoint centerPoint = GetCenterPoint(actionButton);
  NSEvent* mouseEvent = cocoa_test_event_utils::RightMouseDownAtPointInWindow(
      centerPoint, [actionButton window]);
  [actionButton rightMouseDown:mouseEvent];

  // This should close the app menu.
  EXPECT_FALSE([appMenuController isMenuOpen]);
  base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, closure);
}

}  // namespace

// A simple helper menu delegate that will keep track of if a menu is opened,
// and closes them immediately (which is useful because message loops with
// menus open in Cocoa don't play nicely with testing).
@interface MenuHelper : NSObject<NSMenuDelegate> {
  // Whether or not a menu has been opened. This can be reset so the helper can
  // be used multiple times.
  BOOL menuOpened_;

  // A function to be called to verify state while the menu is open.
  base::Closure verify_;
}

// Bare-bones init.
- (id)init;

@property(nonatomic, assign) BOOL menuOpened;
@property(nonatomic, assign) base::Closure verify;

@end

@implementation MenuHelper

- (void)menuWillOpen:(NSMenu*)menu {
  menuOpened_ = YES;
  if (!verify_.is_null())
    verify_.Run();
  [menu cancelTracking];
}

- (id)init {
  self = [super init];
  return self;
}

@synthesize menuOpened = menuOpened_;
@synthesize verify = verify_;

@end

// A helper class to wait for a menu to open and close.
@interface MenuWatcher : NSObject {
  // The MenuController for the menu this object is watching.
  MenuController* menuController_;

  // The closure to run when the menu opens, if any.
  base::Closure openClosure_;

  // The closure to run when the menu closes, if any.
  base::Closure closeClosure_;
}

- (id)initWithController:(MenuController*)controller;

// Notifications from the MenuController.
- (void)menuDidClose:(NSNotification*)notification;
- (void)menuDidOpen:(NSNotification*)notification;

@property(nonatomic, assign) base::Closure openClosure;
@property(nonatomic, assign) base::Closure closeClosure;

@end

@implementation MenuWatcher

@synthesize openClosure = openClosure_;
@synthesize closeClosure = closeClosure_;

- (id)initWithController:(MenuController*)controller {
  if (self = [super init]) {
    menuController_ = controller;
    [[NSNotificationCenter defaultCenter]
        addObserver:self
         selector:@selector(menuDidOpen:)
       name:kMenuControllerMenuWillOpenNotification
        object:menuController_];
    [[NSNotificationCenter defaultCenter]
        addObserver:self
         selector:@selector(menuDidClose:)
       name:kMenuControllerMenuDidCloseNotification
        object:menuController_];
  }
  return self;
}

- (void)dealloc {
  [[NSNotificationCenter defaultCenter] removeObserver:self];
  [super dealloc];
}

- (void)menuDidClose:(NSNotification*)notification {
  if (!closeClosure_.is_null()) {
    base::ThreadTaskRunnerHandle::Get()->PostTask(
        FROM_HERE, base::ResetAndReturn(&closeClosure_));
  }
}

- (void)menuDidOpen:(NSNotification*)notification {
  if (!openClosure_.is_null()) {
    base::ThreadTaskRunnerHandle::Get()->PostTask(
        FROM_HERE, base::ResetAndReturn(&openClosure_));
  }
}

@end

class BrowserActionButtonUiTest : public ExtensionBrowserTest {
 protected:
  BrowserActionButtonUiTest() {}
  ~BrowserActionButtonUiTest() override {}

  void SetUpOnMainThread() override {
    ExtensionBrowserTest::SetUpOnMainThread();
    toolbarController_ =
        [[BrowserWindowController
            browserWindowControllerForWindow:browser()->
                window()->GetNativeWindow()]
            toolbarController];
    ASSERT_TRUE(toolbarController_);
    appMenuController_ = [toolbarController_ appMenuController];
    model_ = ToolbarActionsModel::Get(profile());
  }

  void SetUpCommandLine(base::CommandLine* command_line) override {
    ExtensionBrowserTest::SetUpCommandLine(command_line);
    enable_redesign_.reset(new extensions::FeatureSwitch::ScopedOverride(
        extensions::FeatureSwitch::extension_action_redesign(), true));
    ToolbarActionsBar::disable_animations_for_testing_ = true;
  }

  void TearDownOnMainThread() override {
    enable_redesign_.reset();
    ToolbarActionsBar::disable_animations_for_testing_ = false;
    ExtensionBrowserTest::TearDownOnMainThread();
  }

  // Opens the app menu and the context menu of the overflowed action, and
  // checks that the menus get opened/closed properly. |menuHelper| must be set
  // as the delegate for the context menu.
  void OpenAppMenuAndActionContextMenu(MenuHelper* menuHelper) {
    // Move the mouse over the app menu button.
    MoveMouseToCenter(appMenuButton());

    // No menu yet (on the browser action).
    EXPECT_FALSE([menuHelper menuOpened]);
    base::RunLoop runLoop;
    // Click on the app menu, and pass in a callback to continue the test in
    // ClickOnOverflowedAction. Due to the blocking nature of Cocoa menus, we
    // can't test the menu synchronously here by quitting the run loop when it
    // opens, and instead need to test through a callback.
    base::scoped_nsobject<MenuWatcher> menuWatcher(
        [[MenuWatcher alloc] initWithController:appMenuController()]);
    [menuWatcher
        setOpenClosure:base::Bind(&ClickOnOverflowedAction,
                                  base::Unretained(toolbarController()),
                                  runLoop.QuitClosure())];
    ui_controls::SendMouseEvents(ui_controls::LEFT,
                                 ui_controls::DOWN | ui_controls::UP);
    runLoop.Run();

    // The menu opened on the main bar's action button rather than the
    // overflow's since Cocoa does not support running a menu within a menu.
    EXPECT_TRUE([menuHelper menuOpened]);
  }

  ToolbarController* toolbarController() { return toolbarController_; }
  AppMenuController* appMenuController() { return appMenuController_; }
  ToolbarActionsModel* model() { return model_; }
  NSView* appMenuButton() { return [toolbarController_ appMenuButton]; }

 private:
  std::unique_ptr<extensions::FeatureSwitch::ScopedOverride> enable_redesign_;

  ToolbarController* toolbarController_ = nil;
  AppMenuController* appMenuController_ = nil;
  ToolbarActionsModel* model_ = nullptr;

  DISALLOW_COPY_AND_ASSIGN(BrowserActionButtonUiTest);
};

// Verifies that the action is "popped out" of overflow; that is, it is visible
// on the main bar, and is set as the popped out action on the controlling
// ToolbarActionsBar.
void CheckActionIsPoppedOut(BrowserActionsController* actionsController,
                            BrowserActionButton* actionButton) {
  EXPECT_EQ([actionsController containerView], [actionButton superview]);
  EXPECT_EQ([actionButton viewController],
            [actionsController toolbarActionsBar]->popped_out_action());
  // Since the button is popped out for a popup or context menu, it should be
  // highlighted.
  EXPECT_TRUE([actionButton isHighlighted]);
}

// Test that opening a context menu works for both actions on the main bar and
// actions in the overflow menu.
IN_PROC_BROWSER_TEST_F(BrowserActionButtonUiTest,
                       ContextMenusOnMainAndOverflow) {
  // Add an extension with a browser action.
  scoped_refptr<const extensions::Extension> extension =
      extensions::extension_action_test_util::CreateActionExtension(
          "browser_action",
          extensions::extension_action_test_util::BROWSER_ACTION);
  extension_service()->AddExtension(extension.get());
  ASSERT_EQ(1u, model()->toolbar_items().size());

  BrowserActionsController* actionsController =
      [toolbarController() browserActionsController];
  BrowserActionButton* actionButton = [actionsController buttonWithIndex:0];
  ASSERT_TRUE(actionButton);

  // Stub out the action button's normal context menu with a fake one so we
  // can track when it opens.
  base::scoped_nsobject<NSMenu> testContextMenu(
        [[NSMenu alloc] initWithTitle:@""]);
  base::scoped_nsobject<MenuHelper> menuHelper([[MenuHelper alloc] init]);
  [testContextMenu setDelegate:menuHelper.get()];
  [actionButton setTestContextMenu:testContextMenu.get()];

  // Right now, the action button should be visible (attached to a superview).
  EXPECT_TRUE([actionButton superview]);

  // Move the mouse to the center of the action button, preparing to click.
  MoveMouseToCenter(actionButton);

  {
    // No menu should yet be open.
    EXPECT_FALSE([menuHelper menuOpened]);
    base::RunLoop runLoop;
    ui_controls::SendMouseEventsNotifyWhenDone(
        ui_controls::RIGHT,
        ui_controls::DOWN | ui_controls::UP,
        runLoop.QuitClosure());
    runLoop.Run();
    // The menu should have opened from the click.
    EXPECT_TRUE([menuHelper menuOpened]);
    EXPECT_FALSE([actionButton isHighlighted]);
  }

  // Reset the menu helper so we can use it again.
  [menuHelper setMenuOpened:NO];
  [menuHelper setVerify:base::Bind(
      CheckActionIsPoppedOut, actionsController, actionButton)];

  // Shrink the visible count to be 0. This should hide the action button.
  model()->SetVisibleIconCount(0);
  EXPECT_EQ(nil, [actionButton superview]);

  OpenAppMenuAndActionContextMenu(menuHelper.get());
}

IN_PROC_BROWSER_TEST_F(BrowserActionButtonUiTest,
                       MediaRouterActionContextMenuInOverflow) {
  model()->AddComponentAction(
      ComponentToolbarActionsFactory::kMediaRouterActionId);
  ASSERT_EQ(1u, model()->toolbar_items().size());

  BrowserActionButton* actionButton =
      [[toolbarController() browserActionsController] buttonWithIndex:0];
  ASSERT_TRUE(actionButton);

  // Stub out the action button's normal context menu with a fake one so we
  // can track when it opens.
  base::scoped_nsobject<NSMenu> testContextMenu(
      [[NSMenu alloc] initWithTitle:@""]);
  base::scoped_nsobject<MenuHelper> menuHelper([[MenuHelper alloc] init]);
  [testContextMenu setDelegate:menuHelper.get()];
  [actionButton setTestContextMenu:testContextMenu.get()];

  model()->SetActionVisibility(
      ComponentToolbarActionsFactory::kMediaRouterActionId, false);

  OpenAppMenuAndActionContextMenu(menuHelper.get());

  ToolbarActionsBar* actionsBar =
      [[toolbarController() browserActionsController] toolbarActionsBar];
  // The action should be back in the overflow.
  EXPECT_FALSE(
      actionsBar->IsActionVisibleOnMainBar(actionsBar->GetActions()[0]));
}

// Checks the layout of the overflow bar in the app menu.
void CheckAppMenuLayout(ToolbarController* toolbarController,
                        int overflowStartIndex,
                        const std::string& error_message,
                        const base::Closure& closure) {
  AppMenuController* appMenuController =
      [toolbarController appMenuController];
  // The app menu should start as open (since that's where the overflowed
  // actions are).
  EXPECT_TRUE([appMenuController isMenuOpen]) << error_message;
  BrowserActionsController* overflowController =
      [appMenuController browserActionsController];
  ASSERT_TRUE(overflowController) << error_message;

  ToolbarActionsBar* overflowBar = [overflowController toolbarActionsBar];
  BrowserActionsContainerView* overflowContainer =
      [overflowController containerView];
  NSMenu* menu = [appMenuController menu];

  // The overflow container should be within the bounds of the app menu, as
  // should its parents.
  int menu_width = [menu size].width;
  NSRect frame = [overflowContainer frame];
  // The container itself should be indented in the menu.
  EXPECT_GT(NSMinX(frame), 0) << error_message;
  // Hierarchy: The overflow container is owned by two different views in the
  // app menu. Each superview should start at 0 in the x-axis.
  EXPECT_EQ(0, NSMinX([[overflowContainer superview] frame])) << error_message;
  EXPECT_EQ(0, NSMinX([[[overflowContainer superview] superview] frame])) <<
      error_message;
  // The overflow container should fully fit in the app menu, including the
  // space taken away for padding, and should have its desired size.
  EXPECT_LE(NSWidth(frame), menu_width - kMenuPadding) << error_message;
  EXPECT_EQ(NSWidth(frame), overflowBar->GetPreferredSize().width()) <<
      error_message;

  // Every button that has an index lower than the overflow start index (i.e.,
  // every button on the main toolbar) should not be attached to a view.
  for (int i = 0; i < overflowStartIndex; ++i) {
    BrowserActionButton* button = [overflowController buttonWithIndex:i];
    EXPECT_FALSE([button superview]) << error_message;
    EXPECT_GE(0, NSMaxX([button frame])) << error_message;
  }

  // Every other button should be attached to a view, and should be at the
  // proper bounds. Calculating each button's proper bounds here would just be
  // a duplication of the logic in the method, but we can test that each button
  // a) is within the overflow container's bounds, and
  // b) doesn't intersect with another button.
  // If both of those are true, then we're probably good.
  for (NSUInteger i = overflowStartIndex;
       i < [overflowController buttonCount]; ++i) {
    BrowserActionButton* button = [overflowController buttonWithIndex:i];
    EXPECT_TRUE([button superview]) << error_message;
    EXPECT_TRUE(NSContainsRect([overflowContainer bounds], [button frame])) <<
        error_message;
    for (NSUInteger j = 0; j < i; ++j) {
      EXPECT_FALSE(
          NSContainsRect([[overflowController buttonWithIndex:j] frame],
                         [button frame])) << error_message;
    }
  }

  // Close the app menu.
  [appMenuController cancel];
  EXPECT_FALSE([appMenuController isMenuOpen]) << error_message;
  base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, closure);
}

// Tests the layout of the overflow container in the app menu.
// Disabled due to crashing flakily, see crbug.com/602203.
IN_PROC_BROWSER_TEST_F(BrowserActionButtonUiTest,
                       DISABLED_TestOverflowContainerLayout) {
  // Add a bunch of extensions - enough to trigger multiple rows in the overflow
  // menu.
  const int kNumExtensions = 12;
  for (int i = 0; i < kNumExtensions; ++i) {
    scoped_refptr<const extensions::Extension> extension =
        extensions::extension_action_test_util::CreateActionExtension(
            base::StringPrintf("extension%d", i),
            extensions::extension_action_test_util::BROWSER_ACTION);
    extension_service()->AddExtension(extension.get());
  }
  ASSERT_EQ(kNumExtensions, static_cast<int>(model()->toolbar_items().size()));

  // A helper function to open the app menu and call the check function.
  auto resizeAndActivateAppMenu = [this](int visible_count,
                                         const std::string& error_message) {
    model()->SetVisibleIconCount(kNumExtensions - visible_count);
    MoveMouseToCenter(appMenuButton());

    {
      base::RunLoop runLoop;
      // Click on the app menu, and pass in a callback to continue the test in
      // CheckAppMenuLayout (due to the blocking nature of Cocoa menus,
      // passing in runLoop.QuitClosure() is not sufficient here.)
      ui_controls::SendMouseEventsNotifyWhenDone(
          ui_controls::LEFT, ui_controls::DOWN | ui_controls::UP,
          base::Bind(&CheckAppMenuLayout,
                     base::Unretained(toolbarController()),
                     kNumExtensions - visible_count,
                     error_message,
                     runLoop.QuitClosure()));
      runLoop.Run();
    }
  };

  // Test the layout with gradually more extensions hidden.
  for (int i = 1; i <= kNumExtensions; ++i)
    resizeAndActivateAppMenu(i, base::StringPrintf("Normal: %d", i));

  // Adding a global error adjusts the app menu size, and has been known to mess
  // up the overflow container's bounds (crbug.com/511326).
  GlobalErrorService* error_service =
      GlobalErrorServiceFactory::GetForProfile(profile());
  error_service->AddGlobalError(base::MakeUnique<MenuError>());

  // It's probably excessive to test every level of the overflow here. Test
  // having all actions overflowed, some actions overflowed, and one action
  // overflowed.
  resizeAndActivateAppMenu(kNumExtensions, "GlobalError Full");
  resizeAndActivateAppMenu(kNumExtensions / 2, "GlobalError Half");
  resizeAndActivateAppMenu(1, "GlobalError One");
}

void AddExtensionWithMenuOpen(ToolbarController* toolbarController,
                              ExtensionService* extensionService,
                              const base::Closure& closure) {
  AppMenuController* appMenuController =
      [toolbarController appMenuController];
  EXPECT_TRUE([appMenuController isMenuOpen]);

  scoped_refptr<const extensions::Extension> extension =
      extensions::extension_action_test_util::CreateActionExtension(
          "extension",
          extensions::extension_action_test_util::BROWSER_ACTION);
  extensionService->AddExtension(extension.get());

  base::RunLoop().RunUntilIdle();

  // Close the app menu.
  [appMenuController cancel];
  EXPECT_FALSE([appMenuController isMenuOpen]);

  closure.Run();
}

// Test adding an extension while the app menu is open. Regression test for
// crbug.com/561237.
IN_PROC_BROWSER_TEST_F(BrowserActionButtonUiTest,
                       AddExtensionWithMenuOpen) {
  // Add an extension to ensure the overflow menu is present.
  scoped_refptr<const extensions::Extension> extension =
      extensions::extension_action_test_util::CreateActionExtension(
          "original extension",
          extensions::extension_action_test_util::BROWSER_ACTION);
  extension_service()->AddExtension(extension.get());
  ASSERT_EQ(1, static_cast<int>(model()->toolbar_items().size()));
  model()->SetVisibleIconCount(0);

  MoveMouseToCenter(appMenuButton());

  base::RunLoop runLoop;
  // Click on the app menu, and pass in a callback to continue the test in
  // AddExtensionWithMenuOpen (due to the blocking nature of Cocoa menus,
  // passing in runLoop.QuitClosure() is not sufficient here.)
  base::scoped_nsobject<MenuWatcher> menuWatcher(
      [[MenuWatcher alloc] initWithController:appMenuController()]);
  [menuWatcher setOpenClosure:
      base::Bind(&AddExtensionWithMenuOpen,
                 base::Unretained(toolbarController()), extension_service(),
                 runLoop.QuitClosure())];
  ui_controls::SendMouseEvents(ui_controls::LEFT,
                               ui_controls::DOWN | ui_controls::UP);
  runLoop.Run();
}

// Test that activating an action that doesn't want to run on the page via the
// mouse and the keyboard works.
IN_PROC_BROWSER_TEST_F(BrowserActionButtonUiTest,
                       OpenMenuOnDisabledActionWithMouseOrKeyboard) {
  // Add an extension with a page action.
  scoped_refptr<const extensions::Extension> extension =
      extensions::extension_action_test_util::CreateActionExtension(
          "page action", extensions::extension_action_test_util::PAGE_ACTION);
  extension_service()->AddExtension(extension.get());
  ASSERT_EQ(1u, model()->toolbar_items().size());

  BrowserActionsController* actionsController =
      [toolbarController() browserActionsController];
  BrowserActionButton* actionButton = [actionsController buttonWithIndex:0];
  ASSERT_TRUE(actionButton);

  // Stub out the action button's normal context menu with a fake one so we
  // can track when it opens.
  base::scoped_nsobject<NSMenu> testContextMenu(
      [[NSMenu alloc] initWithTitle:@""]);
  base::scoped_nsobject<MenuHelper> menuHelper([[MenuHelper alloc] init]);
  [testContextMenu setDelegate:menuHelper.get()];
  [actionButton setTestContextMenu:testContextMenu.get()];

  // The button should be attached.
  EXPECT_TRUE([actionButton superview]);

  // Move the mouse and click on the button. The menu should open.
  MoveMouseToCenter(actionButton);
  {
    EXPECT_FALSE([menuHelper menuOpened]);
    base::RunLoop runLoop;
    ui_controls::SendMouseEventsNotifyWhenDone(
        ui_controls::LEFT, ui_controls::DOWN | ui_controls::UP,
        runLoop.QuitClosure());
    runLoop.Run();
    EXPECT_TRUE([menuHelper menuOpened]);
  }

  // Reset the menu helper so we can use it again.
  [menuHelper setMenuOpened:NO];

  // Send the 'space' key to the button with it as the first responder. The menu
  // should open.
  [[actionButton window] makeFirstResponder:actionButton];
  EXPECT_TRUE([[actionButton window] firstResponder] == actionButton);
  {
    EXPECT_FALSE([menuHelper menuOpened]);
    base::RunLoop runLoop;
    ui_controls::SendKeyPressNotifyWhenDone([actionButton window],
                                            ui::VKEY_SPACE, false, false, false,
                                            false, runLoop.QuitClosure());
    runLoop.Run();
    EXPECT_TRUE([menuHelper menuOpened]);
  }
}

void CloseAppMenu(AppMenuController* appMenuController,
                  const base::Closure& quitClosure) {
  EXPECT_TRUE([appMenuController isMenuOpen]);
  [appMenuController cancel];
  quitClosure.Run();
}

// Tests opening the app menu with an overflow section needed, then closing it,
// removing the need for the overflow section, and re-opening it.
// Regression test for crbug.com/603241.
IN_PROC_BROWSER_TEST_F(BrowserActionButtonUiTest,
                       TestReopeningAppMenuWithOverflowNotNeeded) {
  // Add an extension with a browser action and overflow it in the menu.
  scoped_refptr<const extensions::Extension> extension =
      extensions::extension_action_test_util::CreateActionExtension(
          "browser_action",
          extensions::extension_action_test_util::BROWSER_ACTION);
  extension_service()->AddExtension(extension.get());
  ASSERT_EQ(1u, model()->toolbar_items().size());
  model()->SetVisibleIconCount(0);

  // Move the mouse over the app menu button.
  MoveMouseToCenter(appMenuButton());

  auto openAndCloseAppMenu = [](AppMenuController* controller) {
    base::RunLoop runLoop;
    base::scoped_nsobject<MenuWatcher> menuWatcher(
        [[MenuWatcher alloc] initWithController:controller]);
    [menuWatcher setOpenClosure:
        base::Bind(&CloseAppMenu,
                   base::Unretained(controller),
                   runLoop.QuitClosure())];
    ui_controls::SendMouseEvents(ui_controls::LEFT,
                                 ui_controls::DOWN | ui_controls::UP);
    runLoop.Run();
  };
  openAndCloseAppMenu(appMenuController());

  // Move the extension back to the main bar, so an overflow bar is no longer
  // needed. Then open and close the app menu a couple times.
  // This tests that the menu properly cleans up after itself when an overflow
  // was present, and is no longer (fix for crbug.com/603241).
  model()->SetVisibleIconCount(1);
  openAndCloseAppMenu(appMenuController());
  openAndCloseAppMenu(appMenuController());
}