File: menu_controller.mm

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (349 lines) | stat: -rw-r--r-- 11,666 bytes parent folder | download | duplicates (4)
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
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import "ui/menus/cocoa/menu_controller.h"

#include <AppKit/AppKit.h>

#include "base/apple/bridging.h"
#include "base/apple/foundation_util.h"
#include "base/apple/owned_objc.h"
#include "base/check_op.h"
#include "base/functional/bind.h"
#include "base/numerics/safe_conversions.h"
#include "base/strings/sys_string_conversions.h"
#include "ui/base/accelerators/accelerator.h"
#include "ui/base/accelerators/platform_accelerator_cocoa.h"
#include "ui/base/interaction/element_tracker_mac.h"
#include "ui/base/l10n/l10n_util_mac.h"
#include "ui/base/models/image_model.h"
#import "ui/events/event_utils.h"
#include "ui/gfx/font_list.h"
#include "ui/gfx/image/image.h"
#include "ui/menus/simple_menu_model.h"
#include "ui/strings/grit/ui_strings.h"

namespace {

// Called when an empty submenu is created. This inserts a menu item labeled
// "(empty)" into the submenu. Matches Windows behavior.
NSMenu* MakeEmptySubmenu() {
  NSMenu* submenu = [[NSMenu alloc] initWithTitle:@""];
  NSString* empty_menu_title =
      l10n_util::GetNSString(IDS_APP_MENU_EMPTY_SUBMENU);
  [submenu addItemWithTitle:empty_menu_title action:nullptr keyEquivalent:@""];
  [submenu itemAtIndex:0].enabled = NO;
  return submenu;
}

// Called when adding a submenu to the menu and checks if the submenu, via its
// |model|, has visible child items.
bool MenuHasVisibleItems(const ui::MenuModel* model) {
  size_t count = model->GetItemCount();
  for (size_t index = 0; index < count; ++index) {
    if (model->IsVisibleAt(index)) {
      return true;
    }
  }
  return false;
}

}  // namespace

// This class stores a base::WeakPtr<ui::MenuModel> as an Objective-C object,
// which allows it to be stored in the representedObject field of an NSMenuItem.
@interface WeakPtrToMenuModelAsNSObject : NSObject
+ (instancetype)weakPtrForModel:(ui::MenuModel*)model;
+ (ui::MenuModel*)menuModelForNSMenuItem:(NSMenuItem*)menuItem;
@property(readonly) ui::MenuModel* menuModel;
@end

@implementation WeakPtrToMenuModelAsNSObject {
  base::WeakPtr<ui::MenuModel> _model;
}

+ (instancetype)weakPtrForModel:(ui::MenuModel*)model {
  return [[WeakPtrToMenuModelAsNSObject alloc] initWithModel:model];
}

+ (ui::MenuModel*)menuModelForNSMenuItem:(NSMenuItem*)menuItem {
  return base::apple::ObjCCastStrict<WeakPtrToMenuModelAsNSObject>(
             menuItem.representedObject)
      .menuModel;
}

- (instancetype)initWithModel:(ui::MenuModel*)model {
  if ((self = [super init])) {
    _model = model->AsWeakPtr();
  }
  return self;
}

- (ui::MenuModel*)menuModel {
  return _model.get();
}

@end

// Internal methods.
@interface MenuControllerCocoa ()
// Called before the menu is to be displayed to update the state (enabled,
// radio, etc) of each item in the menu. Also will update the title if the item
// is marked as "dynamic".
- (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item;

// Adds the item at |index| in |model| as an NSMenuItem at |index| of |menu|.
// Associates a submenu if the MenuModel::ItemType is TYPE_SUBMENU.
- (void)addItemToMenu:(NSMenu*)menu
              atIndex:(size_t)index
            fromModel:(ui::MenuModel*)model;

// Creates a NSMenu from the given model. If the model has submenus, this can
// be invoked recursively.
- (NSMenu*)menuFromModel:(ui::MenuModel*)model;

// Adds a separator item at the given index. As the separator doesn't need
// anything from the model, this method doesn't need the model index as the
// other method below does.
- (void)addSeparatorToMenu:(NSMenu*)menu atIndex:(size_t)index;

// Called when the user chooses a particular menu item. AppKit sends this only
// after the menu has fully faded out. |sender| is the menu item chosen.
- (void)itemSelected:(id)sender;
@end

@implementation MenuControllerCocoa {
  base::WeakPtr<ui::MenuModel> _model;
  NSMenu* __strong _menu;
  BOOL _isMenuOpen;
  id<MenuControllerCocoaDelegate> __weak _delegate;
}

- (ui::MenuModel*)model {
  return _model.get();
}

- (void)setModel:(ui::MenuModel*)model {
  _model = model->AsWeakPtr();
}

- (instancetype)initWithModel:(ui::MenuModel*)model
                     delegate:(id<MenuControllerCocoaDelegate>)delegate {
  if ((self = [super init])) {
    _model = model->AsWeakPtr();
    _delegate = delegate;
    [self buildMenu];
  }
  return self;
}

- (void)dealloc {
  _menu.delegate = nil;

  // Close the menu if it is still open. This could happen if a tab gets closed
  // while its context menu is still open.
  [self cancel];
  _model = nullptr;
}

- (void)cancel {
  if (_isMenuOpen) {
    [_menu cancelTracking];
    if (_model) {
      _model->MenuWillClose();
    }
    _isMenuOpen = NO;
  }
}

- (NSMenu*)menuFromModel:(ui::MenuModel*)model {
  NSMenu* menu = [[NSMenu alloc] initWithTitle:@""];

  const size_t count = model->GetItemCount();
  for (size_t index = 0; index < count; ++index) {
    if (model->GetTypeAt(index) == ui::MenuModel::TYPE_SEPARATOR) {
      [self addSeparatorToMenu:menu atIndex:index];
    } else {
      [self addItemToMenu:menu atIndex:index fromModel:model];
    }
  }

  return menu;
}

- (void)addSeparatorToMenu:(NSMenu*)menu atIndex:(size_t)index {
  NSMenuItem* separator = [NSMenuItem separatorItem];
  [menu insertItem:separator atIndex:base::checked_cast<NSInteger>(index)];
}

- (void)addItemToMenu:(NSMenu*)menu
              atIndex:(size_t)index
            fromModel:(ui::MenuModel*)model {
  auto rawLabel = model->GetLabelAt(index);
  NSString* label = model->MayHaveMnemonicsAt(index)
                        ? l10n_util::FixUpWindowsStyleLabel(rawLabel)
                        : base::SysUTF16ToNSString(rawLabel);
  NSMenuItem* item = [[NSMenuItem alloc] initWithTitle:label
                                                action:@selector(itemSelected:)
                                         keyEquivalent:@""];

  // If the menu item has an icon, set it.
  ui::ImageModel icon = model->GetIconAt(index);
  if (icon.IsImage()) {
    item.image = icon.GetImage().ToNSImage();
  }

  ui::MenuModel::ItemType type = model->GetTypeAt(index);
  const NSInteger modelIndex = base::checked_cast<NSInteger>(index);
  if (type == ui::MenuModel::TYPE_SUBMENU && model->IsVisibleAt(index)) {
    ui::MenuModel* submenuModel = model->GetSubmenuModelAt(index);

    // If there are visible items, recursively build the submenu.
    NSMenu* submenu = MenuHasVisibleItems(submenuModel)
                          ? [self menuFromModel:submenuModel]
                          : MakeEmptySubmenu();

    item.target = nil;
    item.action = nil;
    item.submenu = submenu;
    // [item setSubmenu:] updates target and action which means clicking on a
    // submenu entry will not call [self validateUserInterfaceItem:].
    DCHECK_EQ(item.action, @selector(submenuAction:));
    DCHECK_EQ(item.target, submenu);
    // Set the enabled state here as submenu entries do not call into
    // validateUserInterfaceItem. See https://crbug.com/40634897 and
    // https://crbug.com/41474827.
    [item setEnabled:model->IsEnabledAt(index)];
  } else {
    // The MenuModel works on indexes so we can't just set the command id as the
    // tag like we do in other menus. Also set the represented object to be
    // the model so hierarchical menus check the correct index in the correct
    // model. Setting the target to |self| allows this class to participate
    // in validation of the menu items.
    item.tag = modelIndex;
    item.target = self;
    item.representedObject =
        [WeakPtrToMenuModelAsNSObject weakPtrForModel:model];
    // On the Mac, context menus do not have accelerators except when
    // |force_show_accelerator_for_item| is set to true. Consult with the Mac
    // team before using the flag!
    if (model->GetForceShowAcceleratorForItemAt(index)) {
      ui::Accelerator accelerator;
      if (model->GetAcceleratorAt(index, &accelerator)) {
        KeyEquivalentAndModifierMask* equivalent =
            GetKeyEquivalentAndModifierMaskFromAccelerator(accelerator);
        item.keyEquivalent = equivalent.keyEquivalent;
        item.keyEquivalentModifierMask = equivalent.modifierMask;
      }
    }
  }

  if (_delegate) {
    [_delegate controllerWillAddItem:item fromModel:model atIndex:index];
  }

  [menu insertItem:item atIndex:modelIndex];
}

- (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
  NSMenuItem* menuItem = base::apple::ObjCCastStrict<NSMenuItem>(item);

  SEL action = menuItem.action;
  if (action != @selector(itemSelected:)) {
    return NO;
  }

  ui::MenuModel* model =
      [WeakPtrToMenuModelAsNSObject menuModelForNSMenuItem:menuItem];
  if (!model) {
    return NO;
  }

  const size_t modelIndex = base::checked_cast<size_t>(menuItem.tag);
  BOOL checked = model->IsItemCheckedAt(modelIndex);
  menuItem.state = checked ? NSControlStateValueOn : NSControlStateValueOff;
  menuItem.hidden = !model->IsVisibleAt(modelIndex);
  if (model->IsItemDynamicAt(modelIndex)) {
    // Update the label and the icon.
    NSString* label =
        l10n_util::FixUpWindowsStyleLabel(model->GetLabelAt(modelIndex));
    menuItem.title = label;

    ui::ImageModel icon = model->GetIconAt(modelIndex);
    menuItem.image = icon.IsImage() ? icon.GetImage().ToNSImage() : nil;
  }
  const gfx::FontList* font_list = model->GetLabelFontListAt(modelIndex);
  if (font_list) {
    CTFontRef font = font_list->GetPrimaryFont().GetCTFont();
    NSDictionary* attributes =
        @{NSFontAttributeName : base::apple::CFToNSPtrCast(font)};
    NSAttributedString* title =
        [[NSAttributedString alloc] initWithString:menuItem.title
                                        attributes:attributes];
    menuItem.attributedTitle = title;
  }
  return model->IsEnabledAt(modelIndex);
}

- (void)itemSelected:(id)sender {
  NSMenuItem* menuItem = base::apple::ObjCCastStrict<NSMenuItem>(sender);

  ui::MenuModel* model =
      [WeakPtrToMenuModelAsNSObject menuModelForNSMenuItem:menuItem];
  DCHECK(model);
  const size_t modelIndex = base::checked_cast<size_t>(menuItem.tag);
  const ui::ElementIdentifier identifier =
      model->GetElementIdentifierAt(modelIndex);
  if (identifier) {
    ui::ElementTrackerMac::GetInstance()->NotifyMenuItemActivated(menuItem.menu,
                                                                  identifier);
  }
  model->ActivatedAt(
      modelIndex,
      ui::EventFlagsFromNative(base::apple::OwnedNSEvent(NSApp.currentEvent)));
  // Note: |self| may be destroyed by the call to ActivatedAt().
}

- (void)buildMenu {
  // The menu is eagerly built in the initializer, so the model cannot be null
  // at this point.
  CHECK(_model);

  _menu = [self menuFromModel:_model.get()];
  _menu.delegate = self;

  // TODO(dfried): Ideally we'd do this after each submenu is created.
  // However, the way we currently hook menu events only supports the root
  // menu. Therefore we call this method here and submenus are not supported
  // for auto-highlighting or ElementTracker events.
  if (_delegate) {
    [_delegate controllerWillAddMenu:_menu fromModel:_model.get()];
  }
}

- (NSMenu*)menu {
  return _menu;
}

- (BOOL)isMenuOpen {
  return _isMenuOpen;
}

- (void)menuWillOpen:(NSMenu*)menu {
  _isMenuOpen = YES;
  if (_model) {
    _model->MenuWillShow();  // Note: |model_| may trigger -[self dealloc].
  }
}

- (void)menuDidClose:(NSMenu*)menu {
  if (_isMenuOpen) {
    _isMenuOpen = NO;
    if (_model) {
      _model->MenuWillClose();  // Note: |model_| may trigger -[self dealloc].
    }
  }
}

@end