File: wrench_menu_controller.mm

package info (click to toggle)
chromium-browser 41.0.2272.118-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-kfreebsd
  • size: 2,189,132 kB
  • sloc: cpp: 9,691,462; ansic: 3,341,451; python: 712,689; asm: 518,779; xml: 208,926; java: 169,820; sh: 119,353; perl: 68,907; makefile: 28,311; yacc: 13,305; objc: 11,385; tcl: 3,186; cs: 2,225; sql: 2,217; lex: 2,215; lisp: 1,349; pascal: 1,256; awk: 407; ruby: 155; sed: 53; php: 14; exp: 11
file content (458 lines) | stat: -rw-r--r-- 17,061 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
// Copyright (c) 2011 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/wrench_menu/wrench_menu_controller.h"

#include "base/basictypes.h"
#include "base/mac/bundle_locations.h"
#include "base/strings/string16.h"
#include "base/strings/sys_string_conversions.h"
#include "chrome/app/chrome_command_ids.h"
#import "chrome/browser/app_controller_mac.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#import "chrome/browser/ui/cocoa/accelerators_cocoa.h"
#import "chrome/browser/ui/cocoa/bookmarks/bookmark_menu_bridge.h"
#import "chrome/browser/ui/cocoa/bookmarks/bookmark_menu_cocoa_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/encoding_menu_controller_delegate_mac.h"
#import "chrome/browser/ui/cocoa/l10n_util.h"
#import "chrome/browser/ui/cocoa/toolbar/toolbar_controller.h"
#import "chrome/browser/ui/cocoa/wrench_menu/menu_tracked_root_view.h"
#import "chrome/browser/ui/cocoa/wrench_menu/recent_tabs_menu_model_delegate.h"
#include "chrome/browser/ui/toolbar/recent_tabs_sub_menu_model.h"
#include "chrome/browser/ui/toolbar/wrench_menu_model.h"
#include "chrome/grit/generated_resources.h"
#include "components/ui/zoom/zoom_event_manager.h"
#include "content/public/browser/user_metrics.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/models/menu_model.h"
#include "ui/gfx/geometry/size.h"

namespace wrench_menu_controller {
const CGFloat kWrenchBubblePointOffsetY = 6;
}

using base::UserMetricsAction;

@interface WrenchMenuController (Private)
- (void)createModel;
- (void)adjustPositioning;
- (void)performCommandDispatch:(NSNumber*)tag;
- (NSButton*)zoomDisplay;
- (void)removeAllItems:(NSMenu*)menu;
- (NSMenu*)recentTabsSubmenu;
- (RecentTabsSubMenuModel*)recentTabsMenuModel;
- (int)maxWidthForMenuModel:(ui::MenuModel*)model
                 modelIndex:(int)modelIndex;
@end

namespace WrenchMenuControllerInternal {

// A C++ delegate that handles the accelerators in the wrench menu.
class AcceleratorDelegate : public ui::AcceleratorProvider {
 public:
  bool GetAcceleratorForCommandId(int command_id,
                                  ui::Accelerator* out_accelerator) override {
    AcceleratorsCocoa* keymap = AcceleratorsCocoa::GetInstance();
    const ui::Accelerator* accelerator =
        keymap->GetAcceleratorForCommand(command_id);
    if (!accelerator)
      return false;
    *out_accelerator = *accelerator;
    return true;
  }
};

class ZoomLevelObserver {
 public:
  ZoomLevelObserver(WrenchMenuController* controller,
                    ui_zoom::ZoomEventManager* manager)
      : controller_(controller) {
    subscription_ = manager->AddZoomLevelChangedCallback(
        base::Bind(&ZoomLevelObserver::OnZoomLevelChanged,
                   base::Unretained(this)));
  }

  ~ZoomLevelObserver() {}

 private:
  void OnZoomLevelChanged(const content::HostZoomMap::ZoomLevelChange& change) {
    WrenchMenuModel* wrenchMenuModel = [controller_ wrenchMenuModel];
    wrenchMenuModel->UpdateZoomControls();
    const base::string16 level =
        wrenchMenuModel->GetLabelForCommandId(IDC_ZOOM_PERCENT_DISPLAY);
    [[controller_ zoomDisplay] setTitle:SysUTF16ToNSString(level)];
  }

  scoped_ptr<content::HostZoomMap::Subscription> subscription_;

  WrenchMenuController* controller_;  // Weak; owns this.

  DISALLOW_COPY_AND_ASSIGN(ZoomLevelObserver);
};

}  // namespace WrenchMenuControllerInternal

@implementation WrenchMenuController

- (id)initWithBrowser:(Browser*)browser {
  if ((self = [super init])) {
    browser_ = browser;
    observer_.reset(new WrenchMenuControllerInternal::ZoomLevelObserver(
        self,
        ui_zoom::ZoomEventManager::GetForBrowserContext(browser->profile())));
    acceleratorDelegate_.reset(
        new WrenchMenuControllerInternal::AcceleratorDelegate());
    [self createModel];
  }
  return self;
}

- (void)addItemToMenu:(NSMenu*)menu
              atIndex:(NSInteger)index
            fromModel:(ui::MenuModel*)model {
  // Non-button item types should be built as normal items, with the exception
  // of the extensions overflow menu.
  int command_id = model->GetCommandIdAt(index);
  if (model->GetTypeAt(index) != ui::MenuModel::TYPE_BUTTON_ITEM &&
      command_id != IDC_EXTENSIONS_OVERFLOW_MENU) {
    [super addItemToMenu:menu
                 atIndex:index
               fromModel:model];
    return;
  }

  // Handle the special-cased menu items.
  base::scoped_nsobject<NSMenuItem> customItem(
      [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""]);
  MenuTrackedRootView* view = nil;
  switch (command_id) {
    case IDC_EXTENSIONS_OVERFLOW_MENU: {
      view = [buttonViewController_ toolbarActionsOverflowItem];
      BrowserActionsContainerView* containerView =
          [buttonViewController_ overflowActionsContainerView];

      // The overflow browser actions container can't function properly without
      // a main counterpart, so if the browser window hasn't initialized, abort.
      // (This is fine because we re-populate the wrench menu each time before
      // we show it.)
      if (!browser_->window())
        break;

      BrowserActionsController* mainController =
          [[[BrowserWindowController browserWindowControllerForWindow:browser_->
              window()->GetNativeWindow()] toolbarController]
                  browserActionsController];
      browserActionsController_.reset(
          [[BrowserActionsController alloc]
              initWithBrowser:browser_
                containerView:containerView
               mainController:mainController]);

      // Set the origins and preferred size for the container.
      gfx::Size preferredSize = [browserActionsController_ preferredSize];
      NSSize preferredNSSize = NSMakeSize(preferredSize.width(),
                                          preferredSize.height());
      // View hierarchy is as follows (from parent > child):
      // |view| > |anonymous view| > containerView. We have to set the origin
      // and size of each for it display properly.
      [view setFrameSize:preferredNSSize];
      [view setFrameOrigin:NSMakePoint(0, 0)];
      [[containerView superview] setFrameSize:preferredNSSize];
      [[containerView superview] setFrameOrigin:NSMakePoint(0, 0)];
      [containerView setFrameSize:preferredNSSize];
      [containerView setFrameOrigin:NSMakePoint(0, 0)];
      [browserActionsController_ update];
      break;
    }
    case IDC_EDIT_MENU:
      view = [buttonViewController_ editItem];
      break;
    case IDC_ZOOM_MENU:
      view = [buttonViewController_ zoomItem];
      break;
    default:
      NOTREACHED();
      break;
  }
  DCHECK(view);
  [customItem setView:view];
  [view setMenuItem:customItem];
  [self adjustPositioning];
  [menu insertItem:customItem.get() atIndex:index];
}

- (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
  const BOOL enabled = [super validateUserInterfaceItem:item];

  NSMenuItem* menuItem = (id)item;
  ui::MenuModel* model =
      static_cast<ui::MenuModel*>(
          [[menuItem representedObject] pointerValue]);

  // The section headers in the recent tabs submenu should be bold and black if
  // a font list is specified for the items (bold is already applied in the
  // |MenuController| as the font list returned by |GetLabelFontListAt| is
  // bold).
  if (model && model == [self recentTabsMenuModel]) {
    if (model->GetLabelFontListAt([item tag])) {
      DCHECK([menuItem attributedTitle]);
      base::scoped_nsobject<NSMutableAttributedString> title(
          [[NSMutableAttributedString alloc]
              initWithAttributedString:[menuItem attributedTitle]]);
      [title addAttribute:NSForegroundColorAttributeName
                    value:[NSColor blackColor]
                    range:NSMakeRange(0, [title length])];
      [menuItem setAttributedTitle:title.get()];
    } else {
      // Not a section header. Add a tooltip with the title and the URL.
      std::string url;
      base::string16 title;
      if ([self recentTabsMenuModel]->GetURLAndTitleForItemAtIndex(
              [item tag], &url, &title)) {
        [menuItem setToolTip:
            cocoa_l10n_util::TooltipForURLAndTitle(
                base::SysUTF8ToNSString(url), base::SysUTF16ToNSString(title))];
       }
    }
  }

  return enabled;
}

- (NSMenu*)bookmarkSubMenu {
  NSString* title = l10n_util::GetNSStringWithFixup(IDS_BOOKMARKS_MENU);
  return [[[self menu] itemWithTitle:title] submenu];
}

- (void)updateBookmarkSubMenu {
  NSMenu* bookmarkMenu = [self bookmarkSubMenu];
  DCHECK(bookmarkMenu);

  bookmarkMenuBridge_.reset(
      new BookmarkMenuBridge([self wrenchMenuModel]->browser()->profile(),
                             bookmarkMenu));
}

- (void)menuWillOpen:(NSMenu*)menu {
  [super menuWillOpen:menu];

  NSString* title = base::SysUTF16ToNSString(
      [self wrenchMenuModel]->GetLabelForCommandId(IDC_ZOOM_PERCENT_DISPLAY));
  [[[buttonViewController_ zoomItem] viewWithTag:IDC_ZOOM_PERCENT_DISPLAY]
      setTitle:title];
  content::RecordAction(UserMetricsAction("ShowAppMenu"));

  NSImage* icon = [self wrenchMenuModel]->browser()->window()->IsFullscreen() ?
      [NSImage imageNamed:NSImageNameExitFullScreenTemplate] :
          [NSImage imageNamed:NSImageNameEnterFullScreenTemplate];
  [[buttonViewController_ zoomFullScreen] setImage:icon];
}

- (void)menuNeedsUpdate:(NSMenu*)menu {
  // First empty out the menu and create a new model.
  [self removeAllItems:menu];
  [self createModel];

  // Create a new menu, which cannot be swapped because the tracking is about to
  // start, so simply copy the items.
  NSMenu* newMenu = [self menuFromModel:model_];
  NSArray* itemArray = [newMenu itemArray];
  [self removeAllItems:newMenu];
  for (NSMenuItem* item in itemArray) {
    [menu addItem:item];
  }

  [self updateRecentTabsSubmenu];
  [self updateBookmarkSubMenu];
}

// Used to dispatch commands from the Wrench menu. The custom items within the
// menu cannot be hooked up directly to First Responder because the window in
// which the controls reside is not the BrowserWindowController, but a
// NSCarbonMenuWindow; this screws up the typical |-commandDispatch:| system.
- (IBAction)dispatchWrenchMenuCommand:(id)sender {
  NSInteger tag = [sender tag];
  if (sender == [buttonViewController_ zoomPlus] ||
      sender == [buttonViewController_ zoomMinus]) {
    // Do a direct dispatch rather than scheduling on the outermost run loop,
    // which would not get hit until after the menu had closed.
    [self performCommandDispatch:[NSNumber numberWithInt:tag]];

    // The zoom buttons should not close the menu if opened sticky.
    if ([sender respondsToSelector:@selector(isTracking)] &&
        [sender performSelector:@selector(isTracking)]) {
      [menu_ cancelTracking];
    }
  } else {
    // The custom views within the Wrench menu are abnormal and keep the menu
    // open after a target-action.  Close the menu manually.
    [menu_ cancelTracking];

    // Executing certain commands from the nested run loop of the menu can lead
    // to wonky behavior (e.g. http://crbug.com/49716). To avoid this, schedule
    // the dispatch on the outermost run loop.
    [self performSelector:@selector(performCommandDispatch:)
               withObject:[NSNumber numberWithInt:tag]
               afterDelay:0.0];
  }
}

// Used to perform the actual dispatch on the outermost runloop.
- (void)performCommandDispatch:(NSNumber*)tag {
  [self wrenchMenuModel]->ExecuteCommand([tag intValue], 0);
}

- (WrenchMenuModel*)wrenchMenuModel {
  // Don't use |wrenchMenuModel_| so that a test can override the generic one.
  return static_cast<WrenchMenuModel*>(model_);
}

- (void)updateRecentTabsSubmenu {
  ui::MenuModel* model = [self recentTabsMenuModel];
  if (model) {
    recentTabsMenuModelDelegate_.reset(
        new RecentTabsMenuModelDelegate(model, [self recentTabsSubmenu]));
  }
}

- (void)createModel {
  recentTabsMenuModelDelegate_.reset();
  wrenchMenuModel_.reset(
      new WrenchMenuModel(acceleratorDelegate_.get(), browser_));
  [self setModel:wrenchMenuModel_.get()];

  buttonViewController_.reset(
      [[WrenchMenuButtonViewController alloc] initWithController:self]);
  [buttonViewController_ view];
}

// Fit the localized strings into the Cut/Copy/Paste control, then resize the
// whole menu item accordingly.
- (void)adjustPositioning {
  const CGFloat kButtonPadding = 12;
  CGFloat delta = 0;

  // Go through the three buttons from right-to-left, adjusting the size to fit
  // the localized strings while keeping them all aligned on their horizontal
  // edges.
  NSButton* views[] = {
      [buttonViewController_ editPaste],
      [buttonViewController_ editCopy],
      [buttonViewController_ editCut]
  };
  for (size_t i = 0; i < arraysize(views); ++i) {
    NSButton* button = views[i];
    CGFloat originalWidth = NSWidth([button frame]);

    // Do not let |-sizeToFit| change the height of the button.
    NSSize size = [button frame].size;
    [button sizeToFit];
    size.width = [button frame].size.width + kButtonPadding;
    [button setFrameSize:size];

    CGFloat newWidth = size.width;
    delta += newWidth - originalWidth;

    NSRect frame = [button frame];
    frame.origin.x -= delta;
    [button setFrame:frame];
  }

  // Resize the menu item by the total amound the buttons changed so that the
  // spacing between the buttons and the title remains the same.
  NSRect itemFrame = [[buttonViewController_ editItem] frame];
  itemFrame.size.width += delta;
  [[buttonViewController_ editItem] setFrame:itemFrame];

  // Also resize the superview of the buttons, which is an NSView used to slide
  // when the item title is too big and GTM resizes it.
  NSRect parentFrame = [[[buttonViewController_ editCut] superview] frame];
  parentFrame.size.width += delta;
  parentFrame.origin.x -= delta;
  [[[buttonViewController_ editCut] superview] setFrame:parentFrame];
}

- (NSButton*)zoomDisplay {
  return [buttonViewController_ zoomDisplay];
}

// -[NSMenu removeAllItems] is only available on 10.6+.
- (void)removeAllItems:(NSMenu*)menu {
  while ([menu numberOfItems]) {
    [menu removeItemAtIndex:0];
  }
}

- (NSMenu*)recentTabsSubmenu {
  NSString* title = l10n_util::GetNSStringWithFixup(IDS_RECENT_TABS_MENU);
  return [[[self menu] itemWithTitle:title] submenu];
}

// The recent tabs menu model is recognized by the existence of either the
// kRecentlyClosedHeaderCommandId or the kDisabledRecentlyClosedHeaderCommandId.
- (RecentTabsSubMenuModel*)recentTabsMenuModel {
  int index = 0;
  // Start searching at the wrench menu model level, |model| will be updated
  // only if the command we're looking for is found in one of the [sub]menus.
  ui::MenuModel* model = [self wrenchMenuModel];
  if (ui::MenuModel::GetModelAndIndexForCommandId(
          RecentTabsSubMenuModel::kRecentlyClosedHeaderCommandId, &model,
          &index)) {
    return static_cast<RecentTabsSubMenuModel*>(model);
  }
  if (ui::MenuModel::GetModelAndIndexForCommandId(
          RecentTabsSubMenuModel::kDisabledRecentlyClosedHeaderCommandId,
          &model, &index)) {
    return static_cast<RecentTabsSubMenuModel*>(model);
  }
  return NULL;
}

// This overrdies the parent class to return a custom width for recent tabs
// menu.
- (int)maxWidthForMenuModel:(ui::MenuModel*)model
                 modelIndex:(int)modelIndex {
  RecentTabsSubMenuModel* recentTabsMenuModel = [self recentTabsMenuModel];
  if (recentTabsMenuModel && recentTabsMenuModel == model) {
    return recentTabsMenuModel->GetMaxWidthForItemAtIndex(modelIndex);
  }
  return -1;
}

@end  // @implementation WrenchMenuController

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

@implementation WrenchMenuButtonViewController

@synthesize editItem = editItem_;
@synthesize editCut = editCut_;
@synthesize editCopy = editCopy_;
@synthesize editPaste = editPaste_;
@synthesize zoomItem = zoomItem_;
@synthesize zoomPlus = zoomPlus_;
@synthesize zoomDisplay = zoomDisplay_;
@synthesize zoomMinus = zoomMinus_;
@synthesize zoomFullScreen = zoomFullScreen_;
@synthesize toolbarActionsOverflowItem = toolbarActionsOverflowItem_;
@synthesize overflowActionsContainerView = overflowActionsContainerView_;

- (id)initWithController:(WrenchMenuController*)controller {
  if ((self = [super initWithNibName:@"WrenchMenu"
                              bundle:base::mac::FrameworkBundle()])) {
    controller_ = controller;
  }
  return self;
}

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

@end  // @implementation WrenchMenuButtonViewController