File: extension_keybinding_registry.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; 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 (385 lines) | stat: -rw-r--r-- 13,243 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
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
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_keybinding_registry.h"

#include <memory>
#include <utility>

#include "base/values.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/extensions/permissions/active_tab_permission_granter.h"
#include "chrome/browser/extensions/tab_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/media_keys_listener_manager.h"
#include "content/public/browser/web_contents.h"
#include "extensions/browser/event_router.h"
#include "extensions/common/command.h"
#include "extensions/common/extension_id.h"
#include "extensions/common/extension_set.h"
#include "extensions/common/manifest_constants.h"
#include "extensions/common/mojom/context_type.mojom.h"

#if BUILDFLAG(IS_CHROMEOS)
#include "chrome/browser/ui/ash/media_client/media_client_impl.h"
#endif

namespace {

const char kOnCommandEventName[] = "commands.onCommand";

}  // namespace

namespace extensions {

ExtensionKeybindingRegistry::ExtensionKeybindingRegistry(
    content::BrowserContext* context,
    ExtensionFilter extension_filter,
    Delegate* delegate)
    : browser_context_(context),
      extension_filter_(extension_filter),
      delegate_(delegate),
      shortcut_handling_suspended_(false) {
  extension_registry_observation_.Observe(
      ExtensionRegistry::Get(browser_context_));
  command_service_observation_.Observe(CommandService::Get(browser_context_));
  media_keys_listener_ = ui::MediaKeysListener::Create(
      this, ui::MediaKeysListener::Scope::kFocused);
}

ExtensionKeybindingRegistry::~ExtensionKeybindingRegistry() = default;

void ExtensionKeybindingRegistry::SetShortcutHandlingSuspended(bool suspended) {
  shortcut_handling_suspended_ = suspended;
  OnShortcutHandlingSuspended(suspended);
}

void ExtensionKeybindingRegistry::AddExtensionKeybindings(
    const Extension* extension,
    const std::string& command_name) {
  // This object only handles named commands, not toolbar action execution.
  if (ShouldIgnoreCommand(command_name)) {
    return;
  }

  // Add all the active keybindings (except toolbar action executions,
  // which are handled elsewhere).
  ui::CommandMap commands;
  if (!PopulateCommands(extension, &commands)) {
    return;
  }

  for (auto& command : commands) {
    if (!command_name.empty() &&
        (command.second.command_name() != command_name)) {
      continue;
    }
    const ui::Accelerator& accelerator = command.second.accelerator();

    if (!IsAcceleratorRegistered(accelerator)) {
      if (!RegisterAccelerator(accelerator)) {
        continue;
      }
    }

    AddEventTarget(accelerator, extension->id(), command.second.command_name());
  }
}

void ExtensionKeybindingRegistry::RemoveExtensionKeybinding(
    const Extension* extension,
    const std::string& command_name) {
  bool any_media_keys_removed = false;
  auto it = event_targets_.begin();
  while (it != event_targets_.end()) {
    TargetList& target_list = it->second;
    auto target = target_list.begin();
    while (target != target_list.end()) {
      if (target->first == extension->id() &&
          (command_name.empty() || command_name == target->second))
        target = target_list.erase(target);
      else
        target++;
    }

    auto old = it++;
    if (target_list.empty()) {
      // Let each platform-specific implementation get a chance to clean up.
      UnregisterAccelerator(old->first);

      if (old->first.IsMediaKey()) {
        any_media_keys_removed = true;
        if (media_keys_listener_)
          media_keys_listener_->StopWatchingMediaKey(old->first.key_code());
      }

      event_targets_.erase(old);

      // If a specific command_name was requested, it has now been deleted so no
      // further work is required.
      if (!command_name.empty())
        break;
    }
  }

  // If we're no longer listening to any media keys, tell the browser that
  // it can start handling media keys.
  if (any_media_keys_removed && !IsListeningToAnyMediaKeys()) {
    if (content::MediaKeysListenerManager::
            IsMediaKeysListenerManagerEnabled()) {
      content::MediaKeysListenerManager* media_keys_listener_manager =
          content::MediaKeysListenerManager::GetInstance();
      DCHECK(media_keys_listener_manager);

      media_keys_listener_manager->EnableInternalMediaKeyHandling();
    } else {
#if BUILDFLAG(IS_CHROMEOS)
      MediaClientImpl::Get()->DisableCustomMediaKeyHandler(browser_context_,
                                                           this);
#endif
    }
  }
}

void ExtensionKeybindingRegistry::Init() {
  ExtensionRegistry* registry = ExtensionRegistry::Get(browser_context_);
  if (!registry)
    return;  // ExtensionRegistry can be null during testing.

  for (const scoped_refptr<const Extension>& extension :
       registry->enabled_extensions()) {
    if (ExtensionMatchesFilter(extension.get()))
      AddExtensionKeybindings(extension.get(), std::string());
  }
}

bool ExtensionKeybindingRegistry::ShouldIgnoreCommand(
    const std::string& command) const {
  return Command::IsActionRelatedCommand(command);
}

bool ExtensionKeybindingRegistry::NotifyEventTargets(
    const ui::Accelerator& accelerator) {
  return ExecuteCommands(accelerator, std::string());
}

void ExtensionKeybindingRegistry::CommandExecuted(
    const ExtensionId& extension_id,
    const std::string& command) {
  const Extension* extension = ExtensionRegistry::Get(browser_context_)
                                   ->enabled_extensions()
                                   .GetByID(extension_id);
  if (!extension)
    return;

  base::Value::List args;
  args.Append(command);

// TODO(crbug.com/406136564): Support tab parameter for commands.onCommand.
#if BUILDFLAG(ENABLE_EXTENSIONS)
  base::Value tab_value;
  if (delegate_) {
    content::WebContents* web_contents =
        delegate_->GetWebContentsForExtension();
    // Grant before sending the event so that the permission is granted before
    // the extension acts on the command. NOTE: The Global Commands handler does
    // not set the delegate as it deals only with named commands (not
    // page/browser actions that are associated with the current page directly).
    ActiveTabPermissionGranter* granter =
        web_contents ? ActiveTabPermissionGranter::FromWebContents(web_contents)
                     : nullptr;
    if (granter) {
      granter->GrantIfRequested(extension);
    }

    if (web_contents) {
      // The action APIs (browserAction, pageAction, action) are only available
      // to privileged extension contexts. As such, we deterministically know
      // that the right context type here is privileged.
      constexpr mojom::ContextType context_type =
          mojom::ContextType::kPrivilegedExtension;
      ExtensionTabUtil::ScrubTabBehavior scrub_tab_behavior =
          ExtensionTabUtil::GetScrubTabBehavior(extension, context_type,
                                                web_contents);
      tab_value = base::Value(ExtensionTabUtil::CreateTabObject(
                                  web_contents, scrub_tab_behavior, extension)
                                  .ToValue());
    }
  }

  args.Append(std::move(tab_value));
#endif  // BUILDFLAG(ENABLE_EXTENSIONS)

  auto event =
      std::make_unique<Event>(events::COMMANDS_ON_COMMAND, kOnCommandEventName,
                              std::move(args), browser_context_);
  event->user_gesture = EventRouter::UserGestureState::kEnabled;
  EventRouter::Get(browser_context_)
      ->DispatchEventToExtension(extension_id, std::move(event));
}

bool ExtensionKeybindingRegistry::IsAcceleratorRegistered(
    const ui::Accelerator& accelerator) const {
  return event_targets_.find(accelerator) != event_targets_.end();
}

void ExtensionKeybindingRegistry::AddEventTarget(
    const ui::Accelerator& accelerator,
    const ExtensionId& extension_id,
    const std::string& command_name) {
  event_targets_[accelerator].push_back(
      std::make_pair(extension_id, command_name));
  // Shortcuts except media keys have only one target in the list. See comment
  // about |event_targets_|.
  if (!accelerator.IsMediaKey()) {
    DCHECK_EQ(1u, event_targets_[accelerator].size());
  } else {
    if (media_keys_listener_)
      media_keys_listener_->StartWatchingMediaKey(accelerator.key_code());

    // Tell the browser that it should not handle media keys, since we're going
    // to handle them.
    if (content::MediaKeysListenerManager::
            IsMediaKeysListenerManagerEnabled()) {
      content::MediaKeysListenerManager* media_keys_listener_manager =
          content::MediaKeysListenerManager::GetInstance();
      DCHECK(media_keys_listener_manager);

      media_keys_listener_manager->DisableInternalMediaKeyHandling();
    } else {
#if BUILDFLAG(IS_CHROMEOS)
      MediaClientImpl::Get()->EnableCustomMediaKeyHandler(browser_context_,
                                                          this);
#endif
    }
  }
}

bool ExtensionKeybindingRegistry::GetFirstTarget(
    const ui::Accelerator& accelerator,
    ExtensionId* extension_id,
    std::string* command_name) const {
  auto targets = event_targets_.find(accelerator);
  if (targets == event_targets_.end())
    return false;

  DCHECK(!targets->second.empty());
  auto first_target = targets->second.begin();
  *extension_id = first_target->first;
  *command_name = first_target->second;
  return true;
}

bool ExtensionKeybindingRegistry::IsEventTargetsEmpty() const {
  return event_targets_.empty();
}

void ExtensionKeybindingRegistry::OnExtensionLoaded(
    content::BrowserContext* browser_context,
    const Extension* extension) {
  if (ExtensionMatchesFilter(extension))
    AddExtensionKeybindings(extension, std::string());
}

void ExtensionKeybindingRegistry::OnExtensionUnloaded(
    content::BrowserContext* browser_context,
    const Extension* extension,
    UnloadedExtensionReason reason) {
  if (ExtensionMatchesFilter(extension))
    RemoveExtensionKeybinding(extension, std::string());
}

void ExtensionKeybindingRegistry::OnExtensionCommandAdded(
    const ExtensionId& extension_id,
    const Command& command) {
  const Extension* extension = ExtensionRegistry::Get(browser_context_)
                                   ->enabled_extensions()
                                   .GetByID(extension_id);
  // During install and uninstall the extension won't be found. We'll catch
  // those events above, with the OnExtension[Unloaded|Loaded], so we ignore
  // this event.
  if (!extension || !ExtensionMatchesFilter(extension))
    return;

  // Component extensions trigger OnExtensionLoaded() for extension
  // installs as well as loads. This can cause adding of multiple key
  // targets.
  if (extension->location() == mojom::ManifestLocation::kComponent)
    return;

  AddExtensionKeybindings(extension, command.command_name());
}

void ExtensionKeybindingRegistry::OnExtensionCommandRemoved(
    const ExtensionId& extension_id,
    const Command& command) {
  const Extension* extension = ExtensionRegistry::Get(browser_context_)
                                   ->enabled_extensions()
                                   .GetByID(extension_id);
  // During install and uninstall the extension won't be found. We'll catch
  // those events above, with the OnExtension[Unloaded|Loaded], so we ignore
  // this event.
  if (!extension || !ExtensionMatchesFilter(extension))
    return;

  RemoveExtensionKeybinding(extension, command.command_name());
}

void ExtensionKeybindingRegistry::OnCommandServiceDestroying() {
  command_service_observation_.Reset();
}

void ExtensionKeybindingRegistry::OnMediaKeysAccelerator(
    const ui::Accelerator& accelerator) {
  NotifyEventTargets(accelerator);
}

bool ExtensionKeybindingRegistry::ExtensionMatchesFilter(
    const Extension* extension) {
  switch (extension_filter_) {
    case ALL_EXTENSIONS:
      return true;
    case PLATFORM_APPS_ONLY:
      return extension->is_platform_app();
    default:
      NOTREACHED();
  }
}

bool ExtensionKeybindingRegistry::ExecuteCommands(
    const ui::Accelerator& accelerator,
    const ExtensionId& extension_id) {
  auto targets = event_targets_.find(accelerator);
  if (targets == event_targets_.end() || targets->second.empty())
    return false;

  bool executed = false;
  for (TargetList::const_iterator it = targets->second.begin();
       it != targets->second.end(); it++) {
    if (!EventRouter::Get(browser_context_)
             ->ExtensionHasEventListener(it->first, kOnCommandEventName)) {
      continue;
    }

    if (extension_id.empty() || it->first == extension_id) {
      CommandExecuted(it->first, it->second);
      executed = true;
    }
  }

  return executed;
}

bool ExtensionKeybindingRegistry::IsListeningToAnyMediaKeys() const {
  for (const auto& accelerator_target : event_targets_) {
    if (accelerator_target.first.IsMediaKey()) {
      return true;
    }
  }
  return false;
}

}  // namespace extensions