1 // Copyright 2015 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 <Cocoa/Cocoa.h>
7 #include "base/memory/scoped_ptr.h"
8 #include "base/strings/stringprintf.h"
9 #include "base/strings/utf_string_conversions.h"
10 #include "chrome/browser/extensions/extension_action_test_util.h"
11 #include "chrome/browser/extensions/extension_browsertest.h"
12 #include "chrome/browser/extensions/extension_service.h"
13 #include "chrome/browser/ui/browser_window.h"
14 #import "chrome/browser/ui/cocoa/browser_window_controller.h"
15 #import "chrome/browser/ui/cocoa/extensions/browser_action_button.h"
16 #import "chrome/browser/ui/cocoa/extensions/browser_actions_container_view.h"
17 #import "chrome/browser/ui/cocoa/extensions/browser_actions_controller.h"
18 #import "chrome/browser/ui/cocoa/toolbar/toolbar_controller.h"
19 #import "chrome/browser/ui/cocoa/wrench_menu/wrench_menu_controller.h"
20 #include "chrome/browser/ui/global_error/global_error.h"
21 #include "chrome/browser/ui/global_error/global_error_service.h"
22 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
23 #include "chrome/browser/ui/toolbar/toolbar_actions_bar.h"
24 #include "chrome/browser/ui/toolbar/toolbar_actions_model.h"
25 #include "chrome/test/base/interactive_test_utils.h"
26 #include "extensions/common/feature_switch.h"
27 #import "ui/events/test/cocoa_test_event_utils.h"
31 const int kMenuPadding = 26;
33 // A simple error class that has a menu item.
34 class MenuError : public GlobalError {
37 ~MenuError() override {}
39 bool HasMenuItem() override { return true; }
40 int MenuItemCommandID() override {
41 // An arbitrary high id so that it's not taken.
44 base::string16 MenuItemLabel() override {
45 const char kErrorMessage[] =
46 "This is a really long error message that will cause the wrench menu "
47 "to have increased width";
48 return base::ASCIIToUTF16(kErrorMessage);
50 void ExecuteMenuItem(Browser* browser) override {}
52 bool HasBubbleView() override { return false; }
53 bool HasShownBubbleView() override { return false; }
54 void ShowBubbleView(Browser* browser) override {}
55 GlobalErrorBubbleViewBase* GetBubbleView() override { return nullptr; }
58 DISALLOW_COPY_AND_ASSIGN(MenuError);
61 // Returns the center point for a particular |view|.
62 NSPoint GetCenterPoint(NSView* view) {
63 NSWindow* window = [view window];
64 NSScreen* screen = [window screen];
67 // Converts the center position of the view into the coordinates accepted
68 // by ui_controls methods.
69 NSRect bounds = [view bounds];
70 NSPoint center = NSMakePoint(NSMidX(bounds), NSMidY(bounds));
71 center = [view convertPoint:center toView:nil];
72 center = [window convertBaseToScreen:center];
73 return NSMakePoint(center.x, [screen frame].size.height - center.y);
76 // Moves the mouse (synchronously) to the center of the given |view|.
77 void MoveMouseToCenter(NSView* view) {
78 NSPoint centerPoint = GetCenterPoint(view);
79 base::RunLoop runLoop;
80 ui_controls::SendMouseMoveNotifyWhenDone(
81 centerPoint.x, centerPoint.y, runLoop.QuitClosure());
87 // A simple helper menu delegate that will keep track of if a menu is opened,
88 // and closes them immediately (which is useful because message loops with
89 // menus open in Cocoa don't play nicely with testing).
90 @interface MenuHelper : NSObject<NSMenuDelegate> {
91 // Whether or not a menu has been opened. This can be reset so the helper can
92 // be used multiple times.
95 // A function to be called to verify state while the menu is open.
96 base::Closure verify_;
102 @property(nonatomic, assign) BOOL menuOpened;
103 @property(nonatomic, assign) base::Closure verify;
107 @implementation MenuHelper
109 - (void)menuWillOpen:(NSMenu*)menu {
111 if (!verify_.is_null())
113 [menu cancelTracking];
121 @synthesize menuOpened = menuOpened_;
122 @synthesize verify = verify_;
126 class BrowserActionButtonUiTest : public ExtensionBrowserTest {
128 BrowserActionButtonUiTest() {}
129 ~BrowserActionButtonUiTest() override {}
131 void SetUpOnMainThread() override {
132 ExtensionBrowserTest::SetUpOnMainThread();
134 [[BrowserWindowController
135 browserWindowControllerForWindow:browser()->
136 window()->GetNativeWindow()]
138 ASSERT_TRUE(toolbarController_);
139 wrenchMenuController_ = [toolbarController_ wrenchMenuController];
140 model_ = ToolbarActionsModel::Get(profile());
143 void SetUpCommandLine(base::CommandLine* command_line) override {
144 ExtensionBrowserTest::SetUpCommandLine(command_line);
145 enable_redesign_.reset(new extensions::FeatureSwitch::ScopedOverride(
146 extensions::FeatureSwitch::extension_action_redesign(), true));
147 ToolbarActionsBar::disable_animations_for_testing_ = true;
150 void TearDownOnMainThread() override {
151 enable_redesign_.reset();
152 ToolbarActionsBar::disable_animations_for_testing_ = false;
153 ExtensionBrowserTest::TearDownOnMainThread();
156 ToolbarController* toolbarController() { return toolbarController_; }
157 WrenchMenuController* wrenchMenuController() { return wrenchMenuController_; }
158 ToolbarActionsModel* model() { return model_; }
159 NSView* wrenchButton() { return [toolbarController_ wrenchButton]; }
162 scoped_ptr<extensions::FeatureSwitch::ScopedOverride> enable_redesign_;
164 ToolbarController* toolbarController_ = nil;
165 WrenchMenuController* wrenchMenuController_ = nil;
166 ToolbarActionsModel* model_ = nullptr;
168 DISALLOW_COPY_AND_ASSIGN(BrowserActionButtonUiTest);
171 // Simulates a clicks on the action button in the overflow menu, and runs
172 // |closure| upon completion.
173 void ClickOnOverflowedAction(ToolbarController* toolbarController,
174 const base::Closure& closure) {
175 WrenchMenuController* wrenchMenuController =
176 [toolbarController wrenchMenuController];
177 // The wrench menu should start as open (since that's where the overflowed
179 EXPECT_TRUE([wrenchMenuController isMenuOpen]);
180 BrowserActionsController* overflowController =
181 [wrenchMenuController browserActionsController];
183 ASSERT_TRUE(overflowController);
184 BrowserActionButton* actionButton =
185 [overflowController buttonWithIndex:0];
186 // The action should be attached to a superview.
187 EXPECT_TRUE([actionButton superview]);
189 // ui_controls:: methods don't play nice when there is an open menu (like the
190 // wrench menu). Instead, simulate a right click by feeding the event directly
192 NSPoint centerPoint = GetCenterPoint(actionButton);
193 NSEvent* mouseEvent = cocoa_test_event_utils::RightMouseDownAtPointInWindow(
194 centerPoint, [actionButton window]);
195 [actionButton rightMouseDown:mouseEvent];
197 // This should close the wrench menu.
198 EXPECT_FALSE([wrenchMenuController isMenuOpen]);
199 base::MessageLoop::current()->PostTask(FROM_HERE, closure);
202 // Verifies that the action is "popped out" of overflow; that is, it is visible
203 // on the main bar, and is set as the popped out action on the controlling
204 // ToolbarActionsBar.
205 void CheckActionIsPoppedOut(BrowserActionsController* actionsController,
206 BrowserActionButton* actionButton) {
207 EXPECT_EQ([actionsController containerView], [actionButton superview]);
208 EXPECT_EQ([actionButton viewController],
209 [actionsController toolbarActionsBar]->popped_out_action());
212 // Test that opening a context menu works for both actions on the main bar and
213 // actions in the overflow menu.
214 IN_PROC_BROWSER_TEST_F(BrowserActionButtonUiTest,
215 ContextMenusOnMainAndOverflow) {
216 // Add an extension with a browser action.
217 scoped_refptr<const extensions::Extension> extension =
218 extensions::extension_action_test_util::CreateActionExtension(
220 extensions::extension_action_test_util::BROWSER_ACTION);
221 extension_service()->AddExtension(extension.get());
222 ASSERT_EQ(1u, model()->toolbar_items().size());
224 BrowserActionsController* actionsController =
225 [toolbarController() browserActionsController];
226 BrowserActionButton* actionButton = [actionsController buttonWithIndex:0];
227 ASSERT_TRUE(actionButton);
229 // Stub out the action button's normal context menu with a fake one so we
230 // can track when it opens.
231 base::scoped_nsobject<NSMenu> testContextMenu(
232 [[NSMenu alloc] initWithTitle:@""]);
233 base::scoped_nsobject<MenuHelper> menuHelper([[MenuHelper alloc] init]);
234 [testContextMenu setDelegate:menuHelper.get()];
235 [actionButton setTestContextMenu:testContextMenu.get()];
237 // Right now, the action button should be visible (attached to a superview).
238 EXPECT_TRUE([actionButton superview]);
240 // Move the mouse to the center of the action button, preparing to click.
241 MoveMouseToCenter(actionButton);
244 // No menu should yet be open.
245 EXPECT_FALSE([menuHelper menuOpened]);
246 base::RunLoop runLoop;
247 ui_controls::SendMouseEventsNotifyWhenDone(
249 ui_controls::DOWN | ui_controls::UP,
250 runLoop.QuitClosure());
252 // The menu should have opened from the click.
253 EXPECT_TRUE([menuHelper menuOpened]);
256 // Reset the menu helper so we can use it again.
257 [menuHelper setMenuOpened:NO];
258 [menuHelper setVerify:base::Bind(
259 CheckActionIsPoppedOut, actionsController, actionButton)];
261 // Shrink the visible count to be 0. This should hide the action button.
262 model()->SetVisibleIconCount(0);
263 EXPECT_EQ(nil, [actionButton superview]);
265 // Move the mouse over the wrench button.
266 MoveMouseToCenter(wrenchButton());
269 // No menu yet (on the browser action).
270 EXPECT_FALSE([menuHelper menuOpened]);
271 base::RunLoop runLoop;
272 // Click on the wrench menu, and pass in a callback to continue the test
273 // in ClickOnOverflowedAction (Due to the blocking nature of Cocoa menus,
274 // passing in runLoop.QuitClosure() is not sufficient here.)
275 ui_controls::SendMouseEventsNotifyWhenDone(
276 ui_controls::LEFT, ui_controls::DOWN | ui_controls::UP,
277 base::Bind(&ClickOnOverflowedAction,
278 base::Unretained(toolbarController()),
279 runLoop.QuitClosure()));
281 // The menu should have opened. Note that the menu opened on the main bar's
282 // action button, not the overflow's. Since Cocoa doesn't support running
283 // a menu-within-a-menu, this is what has to happen.
284 EXPECT_TRUE([menuHelper menuOpened]);
288 // Checks the layout of the overflow bar in the wrench menu.
289 void CheckWrenchMenuLayout(ToolbarController* toolbarController,
290 int overflowStartIndex,
291 const std::string& error_message,
292 const base::Closure& closure) {
293 WrenchMenuController* wrenchMenuController =
294 [toolbarController wrenchMenuController];
295 // The wrench menu should start as open (since that's where the overflowed
297 EXPECT_TRUE([wrenchMenuController isMenuOpen]) << error_message;
298 BrowserActionsController* overflowController =
299 [wrenchMenuController browserActionsController];
300 ASSERT_TRUE(overflowController) << error_message;
302 ToolbarActionsBar* overflowBar = [overflowController toolbarActionsBar];
303 BrowserActionsContainerView* overflowContainer =
304 [overflowController containerView];
305 NSMenu* menu = [wrenchMenuController menu];
307 // The overflow container should be within the bounds of the wrench menu, as
308 // should its parents.
309 int menu_width = [menu size].width;
310 NSRect frame = [overflowContainer frame];
311 // The container itself should be indented in the menu.
312 EXPECT_GT(NSMinX(frame), 0) << error_message;
313 // Hierarchy: The overflow container is owned by two different views in the
314 // wrench menu. Each superview should start at 0 in the x-axis..
315 EXPECT_EQ(0, NSMinX([[overflowContainer superview] frame])) << error_message;
316 EXPECT_EQ(0, NSMinX([[[overflowContainer superview] superview] frame])) <<
318 // The overflow container should fully fit in the wrench menu, including the
319 // space taken away for padding, and should have its desired size.
320 EXPECT_LE(NSWidth(frame), menu_width - kMenuPadding) << error_message;
321 EXPECT_EQ(NSWidth(frame), overflowBar->GetPreferredSize().width()) <<
324 // Every button that has an index lower than the overflow start index (i.e.,
325 // every button on the main toolbar) should not be attached to a view.
326 for (int i = 0; i < overflowStartIndex; ++i) {
327 BrowserActionButton* button = [overflowController buttonWithIndex:i];
328 EXPECT_FALSE([button superview]) << error_message;
329 EXPECT_GE(0, NSMaxX([button frame])) << error_message;
332 // Every other button should be attached to a view, and should be at the
333 // proper bounds. Calculating each button's proper bounds here would just be
334 // a duplication of the logic in the method, but we can test that each button
335 // a) is within the overflow container's bounds, and
336 // b) doesn't intersect with another button.
337 // If both of those are true, then we're probably good.
338 for (NSUInteger i = overflowStartIndex;
339 i < [overflowController buttonCount]; ++i) {
340 BrowserActionButton* button = [overflowController buttonWithIndex:i];
341 EXPECT_TRUE([button superview]) << error_message;
342 EXPECT_TRUE(NSContainsRect([overflowContainer bounds], [button frame])) <<
344 for (NSUInteger j = 0; j < i; ++j) {
346 NSContainsRect([[overflowController buttonWithIndex:j] frame],
347 [button frame])) << error_message;
351 // Close the wrench menu.
352 [wrenchMenuController cancel];
353 EXPECT_FALSE([wrenchMenuController isMenuOpen]) << error_message;
354 base::MessageLoop::current()->PostTask(FROM_HERE, closure);
357 // Tests the layout of the overflow container in the wrench menu.
358 IN_PROC_BROWSER_TEST_F(BrowserActionButtonUiTest, TestOverflowContainerLayout) {
359 // Add a bunch of extensions - enough to trigger multiple rows in the overflow
361 const int kNumExtensions = 12;
362 for (int i = 0; i < kNumExtensions; ++i) {
363 scoped_refptr<const extensions::Extension> extension =
364 extensions::extension_action_test_util::CreateActionExtension(
365 base::StringPrintf("extension%d", i),
366 extensions::extension_action_test_util::BROWSER_ACTION);
367 extension_service()->AddExtension(extension.get());
369 ASSERT_EQ(kNumExtensions, static_cast<int>(model()->toolbar_items().size()));
371 // A helper function to open the wrench menu and call the check function.
372 auto resizeAndActivateWrench = [this](int visible_count,
373 const std::string& error_message) {
374 model()->SetVisibleIconCount(kNumExtensions - visible_count);
375 MoveMouseToCenter(wrenchButton());
378 base::RunLoop runLoop;
379 // Click on the wrench menu, and pass in a callback to continue the test
380 // in CheckWrenchMenuLayout (due to the blocking nature of Cocoa menus,
381 // passing in runLoop.QuitClosure() is not sufficient here.)
382 ui_controls::SendMouseEventsNotifyWhenDone(
383 ui_controls::LEFT, ui_controls::DOWN | ui_controls::UP,
384 base::Bind(&CheckWrenchMenuLayout,
385 base::Unretained(toolbarController()),
386 kNumExtensions - visible_count,
388 runLoop.QuitClosure()));
393 // Test the layout with gradually more extensions hidden.
394 for (int i = 1; i <= kNumExtensions; ++i)
395 resizeAndActivateWrench(i, base::StringPrintf("Normal: %d", i));
397 // Adding a global error adjusts the wrench menu size, and has been known
398 // to mess up the overflow container's bounds (crbug.com/511326).
399 GlobalErrorService* error_service =
400 GlobalErrorServiceFactory::GetForProfile(profile());
401 error_service->AddGlobalError(new MenuError());
403 // It's probably excessive to test every level of the overflow here. Test
404 // having all actions overflowed, some actions overflowed, and one action
406 resizeAndActivateWrench(kNumExtensions, "GlobalError Full");
407 resizeAndActivateWrench(kNumExtensions / 2, "GlobalError Half");
408 resizeAndActivateWrench(1, "GlobalError One");