File: context_menu_helpers.h

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (348 lines) | stat: -rw-r--r-- 12,104 bytes parent folder | download | duplicates (3)
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
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Definition of helper functions for the ContextMenus API.

#ifndef CHROME_BROWSER_EXTENSIONS_CONTEXT_MENU_HELPERS_H_
#define CHROME_BROWSER_EXTENSIONS_CONTEXT_MENU_HELPERS_H_

#include "base/notreached.h"
#include "base/strings/string_number_conversions.h"
#include "base/types/optional_util.h"
#include "chrome/browser/extensions/menu_manager.h"
#include "chrome/common/extensions/api/context_menus.h"
#include "content/public/browser/browser_context.h"
#include "extensions/common/error_utils.h"
#include "extensions/common/extension_id.h"
#include "extensions/common/manifest_handlers/background_info.h"
#include "extensions/common/utils/extension_utils.h"

namespace content {
struct ContextMenuParams;
}  // namespace content

namespace extensions {
class ContextMenuMatcher;
}  // namespace extensions

namespace extensions::context_menu_helpers {

namespace {

template <typename PropertyWithEnumT>
std::unique_ptr<MenuItem::Id> GetParentId(const PropertyWithEnumT& property,
                                          bool is_off_the_record,
                                          const MenuItem::ExtensionKey& key) {
  if (!property.parent_id)
    return nullptr;

  std::unique_ptr<MenuItem::Id> parent_id(
      new MenuItem::Id(is_off_the_record, key));
  if (property.parent_id->as_integer) {
    parent_id->uid = *property.parent_id->as_integer;
  } else if (property.parent_id->as_string) {
    parent_id->string_uid = *property.parent_id->as_string;
  } else {
    NOTREACHED();
  }
  return parent_id;
}

}  // namespace

extern const char kActionNotAllowedError[];
extern const char kCannotFindItemError[];
extern const char kCheckedError[];
extern const char kDuplicateIDError[];
extern const char kGeneratedIdKey[];
extern const char kLauncherNotAllowedError[];
extern const char kOnclickDisallowedError[];
extern const char kParentsMustBeNormalError[];
extern const char kTitleNeededError[];
extern const char kTooManyMenuItems[];

std::string GetIDString(const MenuItem::Id& id);

MenuItem* GetParent(MenuItem::Id parent_id,
                    const MenuManager* menu_manager,
                    std::string* error);

MenuItem::ContextList GetContexts(
    const std::vector<api::context_menus::ContextType>& in_contexts);

MenuItem::Type GetType(api::context_menus::ItemType type,
                       MenuItem::Type default_type);

// Determines if a context menu item should be shown for a given click context.
// This checks if the properties of a right-click (the `params`) match the
// requirements of an extension's context menu item, which are defined by its
// allowed `contexts` and `target_url_patterns`.
//
// params The properties of the context menu click, such as the link
//     URL, selected text, and media type.
// contexts The set of contexts the menu item is registered for (e.g.,
//     `MenuItem::IMAGE`, `MenuItem::LINK`).
// target_url_patterns The set of URL patterns to match against for
//     applicable contexts like links and media.
// Returns whether the menu item is a match for the given context and should be
// shown.
bool ExtensionContextAndPatternMatch(const content::ContextMenuParams& params,
                                     const MenuItem::ContextList& contexts,
                                     const URLPatternSet& target_url_patterns);

// Determines if a given MenuItem should be shown for a context menu click,
// based on the context (e.g., link, image, or selection) and URL.
//
// params The properties of the context menu click.
// item The extension menu item to be evaluated.
// Returns whether the menu item should be displayed in the context menu.
bool MenuItemMatchesParams(const content::ContextMenuParams& params,
                           const MenuItem* item);

// Prepares user-selected text for display in a context menu item, by truncating
// the string to a maximum length (`kMaxSelectionTextLength`) and escaping
// ampersands to prevent them from being interpreted as UI mnemonic character
// shortcuts.
//
// selection_text The raw text selected by the user.
// Returns a truncated and escaped version of the input string suitable for
// display.
std::u16string PrintableSelectionText(const std::u16string& selection_text);

// Populates a ContextMenuMatcher with all relevant context menu items from
// enabled extensions, sorted and grouped appropriately.
//
// params The parameters of the context menu click. This is used to get
//     the selected text for menu items that include it (e.g., "Search for %s").
// matcher The `ContextMenuMatcher` that will be cleared and then
//     populated with the extension menu items.
void PopulateExtensionItems(content::BrowserContext* browser_context,
                            const content::ContextMenuParams& params,
                            ContextMenuMatcher& matcher);

// Creates and adds a menu item from `create_properties`.
template <typename PropertyWithEnumT>
bool CreateMenuItem(const PropertyWithEnumT& create_properties,
                    content::BrowserContext* browser_context,
                    const Extension* extension,
                    const MenuItem::Id& item_id,
                    std::string* error) {
  bool is_webview = item_id.extension_key.webview_instance_id != 0;
  MenuManager* menu_manager = MenuManager::Get(browser_context);

  if (menu_manager->MenuItemsSize(item_id.extension_key) >=
      MenuManager::kMaxItemsPerExtension) {
    *error = ErrorUtils::FormatErrorMessage(
        kTooManyMenuItems,
        base::NumberToString(MenuManager::kMaxItemsPerExtension));
    return false;
  }

  if (menu_manager->GetItemById(item_id)) {
    *error =
        ErrorUtils::FormatErrorMessage(kDuplicateIDError, GetIDString(item_id));
    return false;
  }

  if (!is_webview && BackgroundInfo::HasLazyContext(extension) &&
      create_properties.onclick) {
    *error = kOnclickDisallowedError;
    return false;
  }

  // Contexts.
  MenuItem::ContextList contexts;
  if (create_properties.contexts)
    contexts = GetContexts(*create_properties.contexts);
  else
    contexts.Add(MenuItem::PAGE);

  if (contexts.Contains(MenuItem::LAUNCHER)) {
    // Launcher item is not allowed for <webview>.
    if (is_webview || !extension->is_platform_app()) {
      *error = kLauncherNotAllowedError;
      return false;
    }
  }

  if (contexts.Contains(MenuItem::BROWSER_ACTION) ||
      contexts.Contains(MenuItem::PAGE_ACTION) ||
      contexts.Contains(MenuItem::ACTION)) {
    // Action items are not allowed for <webview>.
    if (is_webview || !extension->is_extension()) {
      *error = kActionNotAllowedError;
      return false;
    }
  }

  // Title.
  std::string title;
  if (create_properties.title)
    title = *create_properties.title;

  MenuItem::Type type = GetType(create_properties.type, MenuItem::NORMAL);
  if (title.empty() && type != MenuItem::SEPARATOR) {
    *error = kTitleNeededError;
    return false;
  }

  // Visibility state.
  bool visible = create_properties.visible.value_or(true);

  // Checked state.
  bool checked = create_properties.checked.value_or(false);

  // Enabled.
  bool enabled = create_properties.enabled.value_or(true);

  std::unique_ptr<MenuItem> item(
      new MenuItem(item_id, title, checked, visible, enabled, type, contexts));

  // URL Patterns.
  if (!item->PopulateURLPatterns(
          base::OptionalToPtr(create_properties.document_url_patterns),
          base::OptionalToPtr(create_properties.target_url_patterns), error)) {
    return false;
  }

  // Parent id.
  bool success = true;
  std::unique_ptr<MenuItem::Id> parent_id(
      GetParentId(create_properties, browser_context->IsOffTheRecord(),
                  item_id.extension_key));
  if (parent_id.get()) {
    MenuItem* parent = GetParent(*parent_id, menu_manager, error);
    if (!parent)
      return false;
    success = menu_manager->AddChildItem(parent->id(), std::move(item));
  } else {
    success = menu_manager->AddContextItem(extension, std::move(item));
  }

  if (!success)
    return false;

  menu_manager->WriteToStorage(extension, item_id.extension_key);
  return true;
}

// Updates a menu item from `update_properties`.
template <typename PropertyWithEnumT>
bool UpdateMenuItem(const PropertyWithEnumT& update_properties,
                    content::BrowserContext* browser_context,
                    const Extension* extension,
                    const MenuItem::Id& item_id,
                    std::string* error) {
  bool radio_item_updated = false;
  bool is_webview = item_id.extension_key.webview_instance_id != 0;
  MenuManager* menu_manager = MenuManager::Get(browser_context);

  MenuItem* item = menu_manager->GetItemById(item_id);
  const ExtensionId& extension_id = MaybeGetExtensionId(extension);
  if (!item || item->extension_id() != extension_id) {
    *error = ErrorUtils::FormatErrorMessage(kCannotFindItemError,
                                            GetIDString(item_id));
    return false;
  }

  // Type.
  MenuItem::Type type = GetType(update_properties.type, item->type());

  if (type != item->type()) {
    if (type == MenuItem::RADIO || item->type() == MenuItem::RADIO) {
      radio_item_updated = true;
    }
    item->set_type(type);
  }

  // Title.
  if (update_properties.title) {
    std::string title(*update_properties.title);
    if (title.empty() && item->type() != MenuItem::SEPARATOR) {
      *error = kTitleNeededError;
      return false;
    }
    item->set_title(title);
  }

  // Checked state.
  if (update_properties.checked) {
    bool checked = *update_properties.checked;
    if (checked && item->type() != MenuItem::CHECKBOX &&
        item->type() != MenuItem::RADIO) {
      *error = kCheckedError;
      return false;
    }

    const bool should_toggle_checked =
        // If radio item was unchecked nothing should happen. The radio item
        // should remain checked because there should always be one item checked
        // in the radio list.
        (item->type() == MenuItem::RADIO && checked) ||
        // Checkboxes are always updated.
        item->type() == MenuItem::CHECKBOX;

    if (should_toggle_checked) {
      if (!item->SetChecked(checked)) {
        *error = kCheckedError;
        return false;
      }
      radio_item_updated = true;
    }
  }

  // Visibility state.
  if (update_properties.visible)
    item->set_visible(*update_properties.visible);

  // Enabled.
  if (update_properties.enabled)
    item->set_enabled(*update_properties.enabled);

  // Contexts.
  MenuItem::ContextList contexts;
  if (update_properties.contexts) {
    contexts = GetContexts(*update_properties.contexts);

    if (contexts.Contains(MenuItem::LAUNCHER)) {
      // Launcher item is not allowed for <webview>.
      if (is_webview || !extension->is_platform_app()) {
        *error = kLauncherNotAllowedError;
        return false;
      }
    }

    if (contexts != item->contexts())
      item->set_contexts(contexts);
  }

  // Parent id.
  std::unique_ptr<MenuItem::Id> parent_id(
      GetParentId(update_properties, browser_context->IsOffTheRecord(),
                  item_id.extension_key));
  if (parent_id.get()) {
    MenuItem* parent = GetParent(*parent_id, menu_manager, error);
    if (!parent || !menu_manager->ChangeParent(item->id(), &parent->id()))
      return false;
  }

  // URL Patterns.
  if (!item->PopulateURLPatterns(
          base::OptionalToPtr(update_properties.document_url_patterns),
          base::OptionalToPtr(update_properties.target_url_patterns), error)) {
    return false;
  }

  // There is no need to call ItemUpdated if ChangeParent is called because
  // all sanitation is taken care of in ChangeParent.
  if (radio_item_updated && !menu_manager->ItemUpdated(item->id()))
    return false;

  menu_manager->WriteToStorage(extension, item_id.extension_key);
  return true;
}

}  // namespace extensions::context_menu_helpers

#endif  // CHROME_BROWSER_EXTENSIONS_CONTEXT_MENU_HELPERS_H_