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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
|
// Copyright (c) 2012 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_actions_controller.h"
#include <stddef.h>
#include <string>
#include <utility>
#include "base/macros.h"
#include "base/strings/sys_string_conversions.h"
#include "chrome/browser/extensions/extension_message_bubble_controller.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#import "chrome/browser/ui/cocoa/browser_window_controller.h"
#import "chrome/browser/ui/cocoa/extensions/browser_action_button.h"
#import "chrome/browser/ui/cocoa/extensions/browser_actions_container_view.h"
#import "chrome/browser/ui/cocoa/extensions/extension_message_bubble_bridge.h"
#import "chrome/browser/ui/cocoa/extensions/extension_popup_controller.h"
#import "chrome/browser/ui/cocoa/extensions/toolbar_actions_bar_bubble_mac.h"
#import "chrome/browser/ui/cocoa/image_button_cell.h"
#import "chrome/browser/ui/cocoa/menu_button.h"
#import "chrome/browser/ui/cocoa/toolbar/toolbar_controller.h"
#include "chrome/browser/ui/extensions/extension_toolbar_icon_surfacing_bubble_delegate.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/toolbar/toolbar_action_view_controller.h"
#include "chrome/browser/ui/toolbar/toolbar_actions_bar.h"
#include "chrome/browser/ui/toolbar/toolbar_actions_bar_delegate.h"
#include "grit/theme_resources.h"
#import "third_party/google_toolbox_for_mac/src/AppKit/GTMNSAnimation+Duration.h"
#include "ui/base/cocoa/appkit_utils.h"
#include "ui/base/cocoa/cocoa_base_utils.h"
#include "ui/base/material_design/material_design_controller.h"
NSString* const kBrowserActionVisibilityChangedNotification =
@"BrowserActionVisibilityChangedNotification";
namespace {
const CGFloat kAnimationDuration = 0.2;
const CGFloat kChevronWidth = 18;
// How far to inset from the bottom of the view to get the top border
// of the popup 2px below the bottom of the Omnibox.
const CGFloat kBrowserActionBubbleYOffset = 3.0;
} // namespace
@interface BrowserActionsController(Private)
// Creates and adds a view for the given |action| at |index|.
- (void)addViewForAction:(ToolbarActionViewController*)action
withIndex:(NSUInteger)index;
// Removes the view for the given |action| from the ccontainer.
- (void)removeViewForAction:(ToolbarActionViewController*)action;
// Removes views for all actions.
- (void)removeAllViews;
// Redraws the BrowserActionsContainerView and updates the button order to match
// the order in the ToolbarActionsBar.
- (void)redraw;
// Resizes the container to the specified |width|, and animates according to
// the ToolbarActionsBar.
- (void)resizeContainerToWidth:(CGFloat)width;
// Sets the container to be either hidden or visible based on whether there are
// any actions to show.
// Returns whether the container is visible.
- (BOOL)updateContainerVisibility;
// During container resizing, buttons become more transparent as they are pushed
// off the screen. This method updates each button's opacity determined by the
// position of the button.
- (void)updateButtonOpacity;
// When the container is resizing, there's a chance that the buttons' frames
// need to be adjusted (for instance, if an action is added to the left, the
// frames of the actions to the right should gradually move right in the
// container). Adjust the frames accordingly.
- (void)updateButtonPositions;
// Returns the existing button associated with the given id; nil if it cannot be
// found.
- (BrowserActionButton*)buttonForId:(const std::string&)id;
// Returns the button at the given index. This is just a wrapper around
// [NSArray objectAtIndex:], since that technically defaults to returning ids
// (and can cause compile errors).
- (BrowserActionButton*)buttonAtIndex:(NSUInteger)index;
// Notification handlers for events registered by the class.
// Updates each button's opacity, the cursor rects and chevron position.
- (void)containerFrameChanged:(NSNotification*)notification;
// Hides the chevron and unhides every hidden button so that dragging the
// container out smoothly shows the Browser Action buttons.
- (void)containerDragStart:(NSNotification*)notification;
// Determines which buttons need to be hidden based on the new size, hides them
// and updates the chevron overflow menu. Also fires a notification to let the
// toolbar know that the drag has finished.
- (void)containerDragFinished:(NSNotification*)notification;
// Shows the toolbar info bubble, if it should be displayed.
- (void)containerMouseEntered:(NSNotification*)notification;
// Notifies the controlling ToolbarActionsBar that any running animation has
// ended.
- (void)containerAnimationEnded:(NSNotification*)notification;
// Processes a key event from the container.
- (void)containerKeyEvent:(NSNotification*)notification;
// Adjusts the position of the surrounding action buttons depending on where the
// button is within the container.
- (void)actionButtonDragging:(NSNotification*)notification;
// Updates the position of the Browser Actions within the container. This fires
// when _any_ Browser Action button is done dragging to keep all open windows in
// sync visually.
- (void)actionButtonDragFinished:(NSNotification*)notification;
// Returns the frame that the button with the given |index| should have.
- (NSRect)frameForIndex:(NSUInteger)index;
// Returns the popup point for the given |view| with |bounds|.
- (NSPoint)popupPointForView:(NSView*)view
withBounds:(NSRect)bounds;
// Moves the given button both visually and within the toolbar model to the
// specified index.
- (void)moveButton:(BrowserActionButton*)button
toIndex:(NSUInteger)index;
// Handles clicks for BrowserActionButtons.
- (BOOL)browserActionClicked:(BrowserActionButton*)button;
// The reason |frame| is specified in these chevron functions is because the
// container may be animating and the end frame of the animation should be
// passed instead of the current frame (which may be off and cause the chevron
// to jump at the end of its animation).
// Shows the overflow chevron button depending on whether there are any hidden
// extensions within the frame given.
- (void)showChevronIfNecessaryInFrame:(NSRect)frame;
// Moves the chevron to its correct position within |frame|.
- (void)updateChevronPositionInFrame:(NSRect)frame;
// Shows or hides the chevron in the given |frame|.
- (void)setChevronHidden:(BOOL)hidden
inFrame:(NSRect)frame;
// Handles when a menu item within the chevron overflow menu is selected.
- (void)chevronItemSelected:(id)menuItem;
// Updates the container's grippy cursor based on the number of hidden buttons.
- (void)updateGrippyCursors;
// Returns the associated ToolbarController.
- (ToolbarController*)toolbarController;
// Creates a message bubble with the given |delegate| that is anchored to the
// given |anchorView|.
- (ToolbarActionsBarBubbleMac*)createMessageBubble:
(scoped_ptr<ToolbarActionsBarBubbleDelegate>)delegate
anchorView:(NSView*)anchorView;
// Called when the window for the active bubble is closing, and sets the active
// bubble to nil.
- (void)bubbleWindowClosing:(NSNotification*)notification;
// Sets the current focused view. Should only be used for the overflow
// container.
- (void)setFocusedViewIndex:(NSInteger)index;
@end
// A subclass of MenuButton that draws the chevron button in MD style.
@interface ChevronMenuButton : MenuButton
@end
@implementation ChevronMenuButton
- (gfx::VectorIconId)vectorIconId {
return gfx::VectorIconId::OVERFLOW_CHEVRON;
}
@end
namespace {
// A bridge between the ToolbarActionsBar and the BrowserActionsController.
class ToolbarActionsBarBridge : public ToolbarActionsBarDelegate {
public:
explicit ToolbarActionsBarBridge(BrowserActionsController* controller);
~ToolbarActionsBarBridge() override;
BrowserActionsController* controller_for_test() { return controller_; }
private:
// ToolbarActionsBarDelegate:
void AddViewForAction(ToolbarActionViewController* action,
size_t index) override;
void RemoveViewForAction(ToolbarActionViewController* action) override;
void RemoveAllViews() override;
void Redraw(bool order_changed) override;
void ResizeAndAnimate(gfx::Tween::Type tween_type,
int target_width,
bool suppress_chevron) override;
void SetChevronVisibility(bool chevron_visible) override;
int GetWidth(GetWidthTime get_width_time) const override;
bool IsAnimating() const override;
void StopAnimating() override;
int GetChevronWidth() const override;
void ShowExtensionMessageBubble(
scoped_ptr<extensions::ExtensionMessageBubbleController> controller,
ToolbarActionViewController* anchor_action) override;
void ShowToolbarActionBubble(
scoped_ptr<ToolbarActionsBarBubbleDelegate> bubble) override;
// The owning BrowserActionsController; weak.
BrowserActionsController* controller_;
DISALLOW_COPY_AND_ASSIGN(ToolbarActionsBarBridge);
};
ToolbarActionsBarBridge::ToolbarActionsBarBridge(
BrowserActionsController* controller)
: controller_(controller) {
}
ToolbarActionsBarBridge::~ToolbarActionsBarBridge() {
}
void ToolbarActionsBarBridge::AddViewForAction(
ToolbarActionViewController* action,
size_t index) {
[controller_ addViewForAction:action
withIndex:index];
}
void ToolbarActionsBarBridge::RemoveViewForAction(
ToolbarActionViewController* action) {
[controller_ removeViewForAction:action];
}
void ToolbarActionsBarBridge::RemoveAllViews() {
[controller_ removeAllViews];
}
void ToolbarActionsBarBridge::Redraw(bool order_changed) {
[controller_ redraw];
}
void ToolbarActionsBarBridge::ResizeAndAnimate(gfx::Tween::Type tween_type,
int target_width,
bool suppress_chevron) {
[controller_ resizeContainerToWidth:target_width];
}
void ToolbarActionsBarBridge::SetChevronVisibility(bool chevron_visible) {
[controller_ setChevronHidden:!chevron_visible
inFrame:[[controller_ containerView] frame]];
}
int ToolbarActionsBarBridge::GetWidth(GetWidthTime get_width_time) const {
NSRect frame =
get_width_time == ToolbarActionsBarDelegate::GET_WIDTH_AFTER_ANIMATION
? [[controller_ containerView] animationEndFrame]
: [[controller_ containerView] frame];
return NSWidth(frame);
}
bool ToolbarActionsBarBridge::IsAnimating() const {
return [[controller_ containerView] isAnimating];
}
void ToolbarActionsBarBridge::StopAnimating() {
// Unfortunately, animating the browser actions container affects neighboring
// views (like the omnibox), which could also be animating. Because of this,
// instead of just ending the animation, the cleanest way to terminate is to
// "animate" to the current frame.
[controller_ resizeContainerToWidth:
NSWidth([[controller_ containerView] frame])];
}
int ToolbarActionsBarBridge::GetChevronWidth() const {
return kChevronWidth;
}
void ToolbarActionsBarBridge::ShowExtensionMessageBubble(
scoped_ptr<extensions::ExtensionMessageBubbleController> bubble_controller,
ToolbarActionViewController* anchor_action) {
NSView* anchorView = nil;
BOOL anchoredToAction = NO;
if (anchor_action) {
BrowserActionButton* actionButton =
[controller_ buttonForId:anchor_action->GetId()];
if (actionButton && [actionButton superview]) {
anchorView = actionButton;
anchoredToAction = YES;
}
}
if (!anchorView)
anchorView = [[controller_ toolbarController] appMenuButton];
// This goop is a by-product of needing to wire together abstract classes,
// C++/Cocoa bridges, and ExtensionMessageBubbleController's somewhat strange
// Show() interface. It's ugly, but it's pretty confined, so it's probably
// okay (but if we ever need to expand, it might need to be reconsidered).
extensions::ExtensionMessageBubbleController* weak_controller =
bubble_controller.get();
scoped_ptr<ExtensionMessageBubbleBridge> bridge(
new ExtensionMessageBubbleBridge(std::move(bubble_controller),
anchoredToAction));
ToolbarActionsBarBubbleMac* bubble =
[controller_ createMessageBubble:std::move(bridge)
anchorView:anchorView];
weak_controller->OnShown();
[bubble showWindow:nil];
}
void ToolbarActionsBarBridge::ShowToolbarActionBubble(
scoped_ptr<ToolbarActionsBarBubbleDelegate> bubble) {
NSView* anchorView = nil;
if (!bubble->GetAnchorActionId().empty()) {
BrowserActionButton* button =
[controller_ buttonForId:bubble->GetAnchorActionId()];
anchorView = button && [button superview] ? button :
[[controller_ toolbarController] appMenuButton];
} else {
anchorView = [controller_ containerView];
}
ToolbarActionsBarBubbleMac* bubbleView =
[controller_ createMessageBubble:std::move(bubble)
anchorView:anchorView];
[bubbleView showWindow:nil];
}
} // namespace
@implementation BrowserActionsController
@synthesize containerView = containerView_;
@synthesize browser = browser_;
@synthesize isOverflow = isOverflow_;
@synthesize activeBubble = activeBubble_;
#pragma mark -
#pragma mark Public Methods
- (id)initWithBrowser:(Browser*)browser
containerView:(BrowserActionsContainerView*)container
mainController:(BrowserActionsController*)mainController {
DCHECK(browser && container);
if ((self = [super init])) {
browser_ = browser;
isOverflow_ = mainController != nil;
toolbarActionsBarBridge_.reset(new ToolbarActionsBarBridge(self));
ToolbarActionsBar* mainBar =
mainController ? [mainController toolbarActionsBar] : nullptr;
toolbarActionsBar_.reset(
new ToolbarActionsBar(toolbarActionsBarBridge_.get(),
browser_,
mainBar));
containerView_ = container;
[containerView_ setPostsFrameChangedNotifications:YES];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(containerFrameChanged:)
name:NSViewFrameDidChangeNotification
object:containerView_];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(containerDragStart:)
name:kBrowserActionGrippyDragStartedNotification
object:containerView_];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(containerDragFinished:)
name:kBrowserActionGrippyDragFinishedNotification
object:containerView_];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(containerAnimationEnded:)
name:kBrowserActionsContainerAnimationEnded
object:containerView_];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(containerKeyEvent:)
name:kBrowserActionsContainerReceivedKeyEvent
object:containerView_];
// Listen for a finished drag from any button to make sure each open window
// stays in sync.
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(actionButtonDragFinished:)
name:kBrowserActionButtonDragEndNotification
object:nil];
suppressChevron_ = NO;
if (toolbarActionsBar_->platform_settings().chevron_enabled) {
chevronAnimation_.reset([[NSViewAnimation alloc] init]);
[chevronAnimation_ gtm_setDuration:kAnimationDuration
eventMask:NSLeftMouseUpMask];
[chevronAnimation_ setAnimationBlockingMode:NSAnimationNonblocking];
}
if (isOverflow_)
toolbarActionsBar_->SetOverflowRowWidth(NSWidth([containerView_ frame]));
buttons_.reset([[NSMutableArray alloc] init]);
toolbarActionsBar_->CreateActions();
[self showChevronIfNecessaryInFrame:[containerView_ frame]];
[self updateGrippyCursors];
[container setIsOverflow:isOverflow_];
focusedViewIndex_ = -1;
}
return self;
}
- (void)dealloc {
[self browserWillBeDestroyed];
[super dealloc];
}
- (void)browserWillBeDestroyed {
[overflowMenu_ setDelegate:nil];
// Explicitly destroy the ToolbarActionsBar so all buttons get removed with a
// valid BrowserActionsController, and so we can verify state before
// destruction.
if (toolbarActionsBar_.get()) {
toolbarActionsBar_->DeleteActions();
toolbarActionsBar_.reset();
}
DCHECK_EQ(0u, [buttons_ count]);
[[NSNotificationCenter defaultCenter] removeObserver:self];
browser_ = nullptr;
}
- (void)update {
toolbarActionsBar_->Update();
}
- (NSUInteger)buttonCount {
return [buttons_ count];
}
- (NSUInteger)visibleButtonCount {
NSUInteger visibleCount = 0;
for (BrowserActionButton* button in buttons_.get())
visibleCount += [button superview] == containerView_;
return visibleCount;
}
- (gfx::Size)preferredSize {
return toolbarActionsBar_->GetPreferredSize();
}
- (NSPoint)popupPointForId:(const std::string&)id {
BrowserActionButton* button = [self buttonForId:id];
if (!button)
return NSZeroPoint;
NSRect bounds;
NSView* referenceButton = button;
if ([button superview] != containerView_ || isOverflow_) {
referenceButton = toolbarActionsBar_->platform_settings().chevron_enabled ?
chevronMenuButton_.get() : [[self toolbarController] appMenuButton];
bounds = [referenceButton bounds];
} else {
bounds = [button convertRect:[button frameAfterAnimation]
fromView:[button superview]];
}
return [self popupPointForView:referenceButton withBounds:bounds];
}
- (BOOL)chevronIsHidden {
if (!chevronMenuButton_.get())
return YES;
if (![chevronAnimation_ isAnimating])
return [chevronMenuButton_ isHidden];
DCHECK([[chevronAnimation_ viewAnimations] count] > 0);
// The chevron is animating in or out. Determine which one and have the return
// value reflect where the animation is headed.
NSString* effect = [[[chevronAnimation_ viewAnimations] objectAtIndex:0]
valueForKey:NSViewAnimationEffectKey];
if (effect == NSViewAnimationFadeInEffect) {
return NO;
} else if (effect == NSViewAnimationFadeOutEffect) {
return YES;
}
NOTREACHED();
return YES;
}
- (content::WebContents*)currentWebContents {
return browser_->tab_strip_model()->GetActiveWebContents();
}
- (BrowserActionButton*)mainButtonForId:(const std::string&)id {
BrowserActionsController* mainController = isOverflow_ ?
[[self toolbarController] browserActionsController] : self;
return [mainController buttonForId:id];
}
- (ToolbarActionsBar*)toolbarActionsBar {
return toolbarActionsBar_.get();
}
- (void)setFocusedInOverflow:(BOOL)focused {
BOOL isFocused = focusedViewIndex_ != -1;
if (isFocused != focused) {
int index = focused ?
[buttons_ count] - toolbarActionsBar_->GetIconCount() : -1;
[self setFocusedViewIndex:index];
}
}
- (gfx::Size)sizeForOverflowWidth:(int)maxWidth {
toolbarActionsBar_->SetOverflowRowWidth(maxWidth);
return [self preferredSize];
}
#pragma mark -
#pragma mark NSMenuDelegate
- (void)menuNeedsUpdate:(NSMenu*)menu {
[menu removeAllItems];
// See menu_button.h for documentation on why this is needed.
[menu addItemWithTitle:@"" action:nil keyEquivalent:@""];
NSUInteger iconCount = toolbarActionsBar_->GetIconCount();
NSRange hiddenButtonRange =
NSMakeRange(iconCount, [buttons_ count] - iconCount);
for (BrowserActionButton* button in
[buttons_ subarrayWithRange:hiddenButtonRange]) {
NSString* name =
base::SysUTF16ToNSString([button viewController]->GetActionName());
NSMenuItem* item =
[menu addItemWithTitle:name
action:@selector(chevronItemSelected:)
keyEquivalent:@""];
[item setRepresentedObject:button];
[item setImage:[button compositedImage]];
[item setTarget:self];
[item setEnabled:[button isEnabled]];
}
}
#pragma mark -
#pragma mark Private Methods
- (void)addViewForAction:(ToolbarActionViewController*)action
withIndex:(NSUInteger)index {
NSRect buttonFrame = NSMakeRect(NSMaxX([containerView_ bounds]),
0,
ToolbarActionsBar::IconWidth(false),
ToolbarActionsBar::IconHeight());
BrowserActionButton* newButton =
[[[BrowserActionButton alloc]
initWithFrame:buttonFrame
viewController:action
controller:self] autorelease];
[newButton setTarget:self];
[newButton setAction:@selector(browserActionClicked:)];
[buttons_ insertObject:newButton atIndex:index];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(actionButtonDragging:)
name:kBrowserActionButtonDraggingNotification
object:newButton];
[containerView_ setMaxDesiredWidth:toolbarActionsBar_->GetMaximumWidth()];
}
- (void)redraw {
if (![self updateContainerVisibility])
return; // Container is hidden; no need to update.
scoped_ptr<ui::NinePartImageIds> highlight;
if (toolbarActionsBar_->is_highlighting()) {
if (toolbarActionsBar_->highlight_type() ==
ToolbarActionsModel::HIGHLIGHT_INFO)
highlight.reset(
new ui::NinePartImageIds(IMAGE_GRID(IDR_TOOLBAR_ACTION_HIGHLIGHT)));
else
highlight.reset(
new ui::NinePartImageIds(IMAGE_GRID(IDR_DEVELOPER_MODE_HIGHLIGHT)));
}
[containerView_ setHighlight:std::move(highlight)];
if (toolbarActionsBar_->show_icon_surfacing_bubble() &&
![containerView_ trackingEnabled]) {
[containerView_ setTrackingEnabled:YES];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(containerMouseEntered:)
name:kBrowserActionsContainerMouseEntered
object:containerView_];
}
std::vector<ToolbarActionViewController*> toolbar_actions =
toolbarActionsBar_->GetActions();
for (NSUInteger i = 0; i < [buttons_ count]; ++i) {
ToolbarActionViewController* controller =
[[self buttonAtIndex:i] viewController];
if (controller != toolbar_actions[i]) {
size_t j = i + 1;
while (true) {
ToolbarActionViewController* other_controller =
[[self buttonAtIndex:j] viewController];
if (other_controller == toolbar_actions[i])
break;
++j;
}
[buttons_ exchangeObjectAtIndex:i withObjectAtIndex:j];
}
}
[self showChevronIfNecessaryInFrame:[containerView_ frame]];
NSUInteger startIndex = toolbarActionsBar_->GetStartIndexInBounds();
NSUInteger endIndex = toolbarActionsBar_->GetEndIndexInBounds();
for (NSUInteger i = 0; i < [buttons_ count]; ++i) {
BrowserActionButton* button = [buttons_ objectAtIndex:i];
if ([button isBeingDragged])
continue;
[self moveButton:[buttons_ objectAtIndex:i] toIndex:i];
if (i >= startIndex && i < endIndex) {
// Make sure the button is within the visible container.
if ([button superview] != containerView_) {
// We add the subview under the sibling views so that when it
// "slides in", it does so under its neighbors.
[containerView_ addSubview:button
positioned:NSWindowBelow
relativeTo:nil];
}
// We need to set the alpha value in case the container has resized.
[button setAlphaValue:1.0];
} else if ([button superview] == containerView_ &&
![containerView_ userIsResizing]) {
// If the user is resizing, all buttons are (and should be) on the
// container view.
[button removeFromSuperview];
[button setAlphaValue:0.0];
}
}
}
- (void)removeViewForAction:(ToolbarActionViewController*)action {
BrowserActionButton* button = [self buttonForId:action->GetId()];
[button removeFromSuperview];
[button onRemoved];
[buttons_ removeObject:button];
[containerView_ setMaxDesiredWidth:toolbarActionsBar_->GetMaximumWidth()];
}
- (void)removeAllViews {
for (BrowserActionButton* button in buttons_.get()) {
[button removeFromSuperview];
[button onRemoved];
}
[buttons_ removeAllObjects];
}
- (void)resizeContainerToWidth:(CGFloat)width {
// Cocoa goes a little crazy if we try and change animations while adjusting
// child frames (i.e., the buttons). If the toolbar is already animating,
// just jump to the new frame. (This typically only happens if someone is
// "spamming" a button to add/remove an action.)
BOOL animate = !toolbarActionsBar_->suppress_animation() &&
![containerView_ isAnimating];
[self updateContainerVisibility];
[containerView_ resizeToWidth:width
animate:animate];
NSRect frame = animate ? [containerView_ animationEndFrame] :
[containerView_ frame];
[self showChevronIfNecessaryInFrame:frame];
[containerView_ setNeedsDisplay:YES];
if (!animate) {
[[NSNotificationCenter defaultCenter]
postNotificationName:kBrowserActionVisibilityChangedNotification
object:self];
}
[self redraw];
[self updateGrippyCursors];
}
- (BOOL)updateContainerVisibility {
BOOL hidden = [buttons_ count] == 0;
if ([containerView_ isHidden] != hidden)
[containerView_ setHidden:hidden];
return !hidden;
}
- (void)updateButtonOpacity {
for (BrowserActionButton* button in buttons_.get()) {
NSRect buttonFrame = [button frameAfterAnimation];
// The button is fully in the container view, and should get full opacity.
if (NSContainsRect([containerView_ bounds], buttonFrame)) {
if ([button alphaValue] != 1.0)
[button setAlphaValue:1.0];
continue;
}
// The button is only partially in the container view. If the user is
// resizing the container, we have partial alpha so the icon fades in as
// space is made. Otherwise, hide the icon fully.
CGFloat alpha = 0.0;
if ([containerView_ userIsResizing]) {
CGFloat intersectionWidth =
NSWidth(NSIntersectionRect([containerView_ bounds], buttonFrame));
alpha = std::max(static_cast<CGFloat>(0.0),
intersectionWidth / NSWidth(buttonFrame));
}
[button setAlphaValue:alpha];
[button setNeedsDisplay:YES];
}
}
- (void)updateButtonPositions {
for (NSUInteger index = 0; index < [buttons_ count]; ++index) {
BrowserActionButton* button = [buttons_ objectAtIndex:index];
NSRect buttonFrame = [self frameForIndex:index];
// If the button is at the proper position (or animating to it), then we
// don't need to update its position.
if (NSMinX([button frameAfterAnimation]) == NSMinX(buttonFrame))
continue;
// We set the x-origin by calculating the proper distance from the right
// edge in the container so that, if the container is animating, the
// button appears stationary.
buttonFrame.origin.x = NSWidth([containerView_ frame]) -
(toolbarActionsBar_->GetPreferredSize().width() - NSMinX(buttonFrame));
[button setFrame:buttonFrame animate:NO];
}
}
- (BrowserActionButton*)buttonForId:(const std::string&)id {
for (BrowserActionButton* button in buttons_.get()) {
if ([button viewController]->GetId() == id)
return button;
}
return nil;
}
- (BrowserActionButton*)buttonAtIndex:(NSUInteger)index {
return static_cast<BrowserActionButton*>([buttons_ objectAtIndex:index]);
}
- (void)containerFrameChanged:(NSNotification*)notification {
[self updateButtonPositions];
[self updateButtonOpacity];
[[containerView_ window] invalidateCursorRectsForView:containerView_];
[self updateChevronPositionInFrame:[containerView_ frame]];
}
- (void)containerDragStart:(NSNotification*)notification {
[self setChevronHidden:YES inFrame:[containerView_ frame]];
for (BrowserActionButton* button in buttons_.get()) {
if ([button superview] != containerView_) {
[button setAlphaValue:1.0];
[containerView_ addSubview:button];
}
}
}
- (void)containerDragFinished:(NSNotification*)notification {
for (BrowserActionButton* button in buttons_.get()) {
NSRect buttonFrame = [button frame];
if (NSContainsRect([containerView_ bounds], buttonFrame))
continue;
CGFloat intersectionWidth =
NSWidth(NSIntersectionRect([containerView_ bounds], buttonFrame));
// Hide the button if it's not "mostly" visible. "Mostly" here equates to
// having three or fewer pixels hidden.
if (([containerView_ grippyPinned] && intersectionWidth > 0) ||
(intersectionWidth <= NSWidth(buttonFrame) - 3.0)) {
[button setAlphaValue:0.0];
[button removeFromSuperview];
}
}
toolbarActionsBar_->OnResizeComplete(
toolbarActionsBar_->IconCountToWidth([self visibleButtonCount]));
[self updateGrippyCursors];
[self resizeContainerToWidth:toolbarActionsBar_->GetPreferredSize().width()];
}
- (void)containerAnimationEnded:(NSNotification*)notification {
if (![containerView_ isAnimating])
toolbarActionsBar_->OnAnimationEnded();
}
- (void)containerKeyEvent:(NSNotification*)notification {
DCHECK(isOverflow_); // We only manually process key events in overflow.
NSDictionary* dict = [notification userInfo];
BrowserActionsContainerKeyAction action =
static_cast<BrowserActionsContainerKeyAction>(
[[dict objectForKey:kBrowserActionsContainerKeyEventKey] intValue]);
switch (action) {
case BROWSER_ACTIONS_DECREMENT_FOCUS:
case BROWSER_ACTIONS_INCREMENT_FOCUS: {
NSInteger newIndex = focusedViewIndex_ +
(action == BROWSER_ACTIONS_INCREMENT_FOCUS ? 1 : -1);
NSInteger minIndex =
[buttons_ count] - toolbarActionsBar_->GetIconCount();
if (newIndex >= minIndex && newIndex < static_cast<int>([buttons_ count]))
[self setFocusedViewIndex:newIndex];
break;
}
case BROWSER_ACTIONS_EXECUTE_CURRENT: {
if (focusedViewIndex_ != -1) {
BrowserActionButton* focusedButton =
[self buttonAtIndex:focusedViewIndex_];
[focusedButton performClick:focusedButton];
}
break;
}
case BROWSER_ACTIONS_INVALID_KEY_ACTION:
NOTREACHED();
}
}
- (void)containerMouseEntered:(NSNotification*)notification {
if (!activeBubble_ && // only show one bubble at a time
toolbarActionsBar_->show_icon_surfacing_bubble()) {
scoped_ptr<ToolbarActionsBarBubbleDelegate> delegate(
new ExtensionToolbarIconSurfacingBubbleDelegate(browser_->profile()));
ToolbarActionsBarBubbleMac* bubble =
[self createMessageBubble:std::move(delegate)
anchorView:containerView_];
[bubble showWindow:nil];
}
[containerView_ setTrackingEnabled:NO];
[[NSNotificationCenter defaultCenter]
removeObserver:self
name:kBrowserActionsContainerMouseEntered
object:containerView_];
}
- (void)actionButtonDragging:(NSNotification*)notification {
suppressChevron_ = YES;
if (![self chevronIsHidden])
[self setChevronHidden:YES inFrame:[containerView_ frame]];
// Determine what index the dragged button should lie in, alter the model and
// reposition the buttons.
BrowserActionButton* draggedButton = [notification object];
NSRect draggedButtonFrame = [draggedButton frame];
// Find the mid-point. We flip the y-coordinates so that y = 0 is at the
// top of the container to make row calculation more logical.
NSPoint midPoint =
NSMakePoint(NSMidX(draggedButtonFrame),
NSMaxY([containerView_ bounds]) - NSMidY(draggedButtonFrame));
// Calculate the row index and the index in the row. We bound the latter
// because the view can go farther right than the right-most icon in the last
// row of the overflow menu.
NSInteger rowIndex = midPoint.y / ToolbarActionsBar::IconHeight();
int icons_per_row = isOverflow_ ?
toolbarActionsBar_->platform_settings().icons_per_overflow_menu_row :
toolbarActionsBar_->GetIconCount();
NSInteger indexInRow = std::min(icons_per_row - 1,
static_cast<int>(midPoint.x / ToolbarActionsBar::IconWidth(true)));
// Find the desired index for the button.
NSInteger maxIndex = [buttons_ count] - 1;
NSInteger offset = isOverflow_ ?
[buttons_ count] - toolbarActionsBar_->GetIconCount() : 0;
NSInteger index =
std::min(maxIndex, offset + rowIndex * icons_per_row + indexInRow);
toolbarActionsBar_->OnDragDrop([buttons_ indexOfObject:draggedButton],
index,
ToolbarActionsBar::DRAG_TO_SAME);
}
- (void)actionButtonDragFinished:(NSNotification*)notification {
suppressChevron_ = NO;
[self redraw];
}
- (NSRect)frameForIndex:(NSUInteger)index {
gfx::Rect frameRect = toolbarActionsBar_->GetFrameForIndex(index);
int iconWidth = ToolbarActionsBar::IconWidth(false);
// The toolbar actions bar will return an empty rect if the index is for an
// action that is before range we show (i.e., is for a button that's on the
// main bar, and this is the overflow). Set the frame to be outside the bounds
// of the view.
NSRect frame = frameRect.IsEmpty() ?
NSMakeRect(-iconWidth - 1, 0, iconWidth,
ToolbarActionsBar::IconHeight()) :
NSRectFromCGRect(frameRect.ToCGRect());
// We need to flip the y coordinate for Cocoa's view system.
frame.origin.y = NSHeight([containerView_ frame]) - NSMaxY(frame);
return frame;
}
- (NSPoint)popupPointForView:(NSView*)view
withBounds:(NSRect)bounds {
// Anchor point just above the center of the bottom.
int y = [view isFlipped] ? NSMaxY(bounds) - kBrowserActionBubbleYOffset :
kBrowserActionBubbleYOffset;
NSPoint anchor = NSMakePoint(NSMidX(bounds), y);
// Convert the point to the container view's frame, and adjust for animation.
NSPoint anchorInContainer =
[containerView_ convertPoint:anchor fromView:view];
anchorInContainer.x -= NSMinX([containerView_ frame]) -
NSMinX([containerView_ animationEndFrame]);
return [containerView_ convertPoint:anchorInContainer toView:nil];
}
- (void)moveButton:(BrowserActionButton*)button
toIndex:(NSUInteger)index {
NSRect buttonFrame = [self frameForIndex:index];
CGFloat currentX = NSMinX([button frame]);
CGFloat xLeft = toolbarActionsBar_->GetPreferredSize().width() -
NSMinX(buttonFrame);
// We check if the button is already in the correct place for the toolbar's
// current size. This could mean that the button could be the correct distance
// from the left or from the right edge. If it has the correct distance, we
// don't move it, and it will be updated when the container frame changes.
// This way, if the user has extensions A and C installed, and installs
// extension B between them, extension C appears to stay stationary on the
// screen while the toolbar expands to the left (even though C's bounds within
// the container change).
if ((currentX == NSMinX(buttonFrame) ||
currentX == NSWidth([containerView_ frame]) - xLeft) &&
NSMinY([button frame]) == NSMinY(buttonFrame)) {
// If the button is in the right place, but animating, we need to stop the
// animation.
if ([button isAnimating])
[button stopAnimation];
return;
}
// It's possible the button is already animating to the right place. Don't
// call move again, because it will stop the current animation.
if (!NSEqualRects(buttonFrame, [button frameAfterAnimation])) {
[button setFrame:buttonFrame
animate:!toolbarActionsBar_->suppress_animation() && !isOverflow_];
}
}
- (BOOL)browserActionClicked:(BrowserActionButton*)button {
return [button viewController]->ExecuteAction(true);
}
- (void)showChevronIfNecessaryInFrame:(NSRect)frame {
if (!toolbarActionsBar_->platform_settings().chevron_enabled)
return;
bool hidden = suppressChevron_ ||
toolbarActionsBar_->GetIconCount() == [self buttonCount];
[self setChevronHidden:hidden inFrame:frame];
}
- (void)updateChevronPositionInFrame:(NSRect)frame {
CGFloat xPos = NSWidth(frame) - kChevronWidth -
toolbarActionsBar_->platform_settings().item_spacing;
NSRect buttonFrame = NSMakeRect(xPos,
0,
kChevronWidth,
ToolbarActionsBar::IconHeight());
[chevronAnimation_ stopAnimation];
[chevronMenuButton_ setFrame:buttonFrame];
}
- (void)setChevronHidden:(BOOL)hidden
inFrame:(NSRect)frame {
if (!toolbarActionsBar_->platform_settings().chevron_enabled ||
hidden == [self chevronIsHidden])
return;
if (!chevronMenuButton_.get()) {
bool isModeMaterial = ui::MaterialDesignController::IsModeMaterial();
if (isModeMaterial) {
chevronMenuButton_.reset([[ChevronMenuButton alloc] init]);
} else {
chevronMenuButton_.reset([[MenuButton alloc] init]);
}
[chevronMenuButton_ setOpenMenuOnClick:YES];
[chevronMenuButton_ setBordered:NO];
[chevronMenuButton_ setShowsBorderOnlyWhileMouseInside:YES];
if (!isModeMaterial) {
[[chevronMenuButton_ cell] setImageID:IDR_BROWSER_ACTIONS_OVERFLOW
forButtonState:image_button_cell::kDefaultState];
[[chevronMenuButton_ cell] setImageID:IDR_BROWSER_ACTIONS_OVERFLOW_H
forButtonState:image_button_cell::kHoverState];
[[chevronMenuButton_ cell] setImageID:IDR_BROWSER_ACTIONS_OVERFLOW_P
forButtonState:image_button_cell::kPressedState];
}
overflowMenu_.reset([[NSMenu alloc] initWithTitle:@""]);
[overflowMenu_ setAutoenablesItems:NO];
[overflowMenu_ setDelegate:self];
[chevronMenuButton_ setAttachedMenu:overflowMenu_];
[containerView_ addSubview:chevronMenuButton_];
}
[self updateChevronPositionInFrame:frame];
// Stop any running animation.
[chevronAnimation_ stopAnimation];
if (toolbarActionsBar_->suppress_animation()) {
[chevronMenuButton_ setHidden:hidden];
return;
}
NSString* animationEffect;
if (hidden) {
animationEffect = NSViewAnimationFadeOutEffect;
} else {
[chevronMenuButton_ setHidden:NO];
animationEffect = NSViewAnimationFadeInEffect;
}
NSDictionary* animationDictionary = @{
NSViewAnimationTargetKey : chevronMenuButton_.get(),
NSViewAnimationEffectKey : animationEffect
};
[chevronAnimation_ setViewAnimations:
[NSArray arrayWithObject:animationDictionary]];
[chevronAnimation_ startAnimation];
}
- (void)chevronItemSelected:(id)menuItem {
[self browserActionClicked:[menuItem representedObject]];
}
- (void)updateGrippyCursors {
[containerView_
setCanDragLeft:toolbarActionsBar_->GetIconCount() != [buttons_ count]];
[containerView_ setCanDragRight:[self visibleButtonCount] > 0];
[[containerView_ window] invalidateCursorRectsForView:containerView_];
}
- (ToolbarController*)toolbarController {
return [[BrowserWindowController browserWindowControllerForWindow:
browser_->window()->GetNativeWindow()] toolbarController];
}
- (ToolbarActionsBarBubbleMac*)createMessageBubble:
(scoped_ptr<ToolbarActionsBarBubbleDelegate>)delegate
anchorView:(NSView*)anchorView {
DCHECK(anchorView);
DCHECK_GE([buttons_ count], 0u);
NSPoint anchor = [self popupPointForView:anchorView
withBounds:[anchorView bounds]];
anchor = ui::ConvertPointFromWindowToScreen([containerView_ window], anchor);
activeBubble_ = [[ToolbarActionsBarBubbleMac alloc]
initWithParentWindow:[containerView_ window]
anchorPoint:anchor
delegate:std::move(delegate)];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(bubbleWindowClosing:)
name:NSWindowWillCloseNotification
object:[activeBubble_ window]];
return activeBubble_;
}
- (void)bubbleWindowClosing:(NSNotification*)notification {
activeBubble_ = nil;
}
- (void)setFocusedViewIndex:(NSInteger)index {
DCHECK(isOverflow_);
focusedViewIndex_ = index;
}
#pragma mark -
#pragma mark Testing Methods
- (BrowserActionButton*)buttonWithIndex:(NSUInteger)index {
return index < [buttons_ count] ? [buttons_ objectAtIndex:index] : nil;
}
@end
|