File: peripheral_customization_event_rewriter.cc

package info (click to toggle)
chromium 120.0.6099.224-1~deb11u1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 6,112,112 kB
  • sloc: cpp: 32,907,025; ansic: 8,148,123; javascript: 3,679,536; python: 2,031,248; asm: 959,718; java: 804,675; xml: 617,256; sh: 111,417; objc: 100,835; perl: 88,443; cs: 53,032; makefile: 29,579; fortran: 24,137; php: 21,162; tcl: 21,147; sql: 20,809; ruby: 17,735; pascal: 12,864; yacc: 8,045; lisp: 3,388; lex: 1,323; ada: 727; awk: 329; jsp: 267; csh: 117; exp: 43; sed: 37
file content (740 lines) | stat: -rw-r--r-- 27,205 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
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
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/events/peripheral_customization_event_rewriter.h"

#include <linux/input.h>

#include <memory>

#include "ash/accelerators/accelerator_controller_impl.h"
#include "ash/constants/ash_features.h"
#include "ash/public/mojom/input_device_settings.mojom-forward.h"
#include "ash/public/mojom/input_device_settings.mojom-shared.h"
#include "ash/public/mojom/input_device_settings.mojom.h"
#include "ash/shell.h"
#include "ash/system/input_device_settings/input_device_settings_controller_impl.h"
#include "base/check.h"
#include "base/containers/fixed_flat_map.h"
#include "base/notreached.h"
#include "base/ranges/algorithm.h"
#include "ui/display/screen.h"
#include "ui/events/event.h"
#include "ui/events/event_constants.h"
#include "ui/events/event_dispatcher.h"
#include "ui/events/event_utils.h"
#include "ui/events/keycodes/dom/dom_code.h"
#include "ui/events/keycodes/dom/dom_key.h"
#include "ui/events/keycodes/keyboard_codes_posix.h"
#include "ui/events/ozone/evdev/mouse_button_property.h"
#include "ui/events/types/event_type.h"
#include "ui/gfx/geometry/point_f.h"

namespace ash {

namespace {

constexpr int kMouseRemappableFlags = ui::EF_BACK_MOUSE_BUTTON |
                                      ui::EF_FORWARD_MOUSE_BUTTON |
                                      ui::EF_MIDDLE_MOUSE_BUTTON;

constexpr int kGraphicsTabletRemappableFlags =
    ui::EF_RIGHT_MOUSE_BUTTON | ui::EF_BACK_MOUSE_BUTTON |
    ui::EF_FORWARD_MOUSE_BUTTON | ui::EF_MIDDLE_MOUSE_BUTTON;

constexpr auto kStaticActionToMouseButtonFlag =
    base::MakeFixedFlatMap<mojom::StaticShortcutAction, ui::EventFlags>({
        {mojom::StaticShortcutAction::kLeftClick, ui::EF_LEFT_MOUSE_BUTTON},
        {mojom::StaticShortcutAction::kRightClick, ui::EF_RIGHT_MOUSE_BUTTON},
        {mojom::StaticShortcutAction::kMiddleClick, ui::EF_MIDDLE_MOUSE_BUTTON},
    });

mojom::KeyEvent GetStaticShortcutAction(mojom::StaticShortcutAction action) {
  mojom::KeyEvent key_event;
  switch (action) {
    case mojom::StaticShortcutAction::kDisable:
    case mojom::StaticShortcutAction::kLeftClick:
    case mojom::StaticShortcutAction::kRightClick:
    case mojom::StaticShortcutAction::kMiddleClick:
      NOTREACHED_NORETURN();
    case mojom::StaticShortcutAction::kCopy:
      key_event = mojom::KeyEvent(
          ui::VKEY_C, static_cast<int>(ui::DomCode::US_C),
          static_cast<int>(ui::DomKey::Constant<'c'>::Character),
          ui::EF_CONTROL_DOWN, /*key_display=*/"");
      break;
    case mojom::StaticShortcutAction::kPaste:
      key_event = mojom::KeyEvent(
          ui::VKEY_V, static_cast<int>(ui::DomCode::US_V),
          static_cast<int>(ui::DomKey::Constant<'v'>::Character),
          ui::EF_CONTROL_DOWN, /*key_display=*/"");
      break;
    case mojom::StaticShortcutAction::kUndo:
      key_event = mojom::KeyEvent(
          ui::VKEY_Z, static_cast<int>(ui::DomCode::US_Z),
          static_cast<int>(ui::DomKey::Constant<'z'>::Character),
          ui::EF_CONTROL_DOWN, /*key_display=*/"");
      break;
    case mojom::StaticShortcutAction::kRedo:
      key_event = mojom::KeyEvent(
          ui::VKEY_Z, static_cast<int>(ui::DomCode::US_Z),
          static_cast<int>(ui::DomKey::Constant<'z'>::Character),
          ui::EF_CONTROL_DOWN | ui::EF_SHIFT_DOWN, /*key_display=*/"");
      break;
    case mojom::StaticShortcutAction::kZoomIn:
      key_event = mojom::KeyEvent(
          ui::VKEY_OEM_PLUS, static_cast<int>(ui::DomCode::EQUAL),
          static_cast<int>(ui::DomKey::Constant<'='>::Character),
          ui::EF_CONTROL_DOWN, /*key_display=*/"");
      break;
    case mojom::StaticShortcutAction::kZoomOut:
      key_event = mojom::KeyEvent(
          ui::VKEY_OEM_MINUS, static_cast<int>(ui::DomCode::MINUS),
          static_cast<int>(ui::DomKey::Constant<'-'>::Character),
          ui::EF_CONTROL_DOWN, /*key_display=*/"");
      break;
    case mojom::StaticShortcutAction::kPreviousPage:
      key_event = mojom::KeyEvent(ui::VKEY_BROWSER_BACK,
                                  static_cast<int>(ui::DomCode::BROWSER_BACK),
                                  static_cast<int>(ui::DomKey::BROWSER_BACK),
                                  ui::EF_NONE, /*key_display=*/"");
      break;
    case mojom::StaticShortcutAction::kNextPage:
      key_event =
          mojom::KeyEvent(ui::VKEY_BROWSER_FORWARD,
                          static_cast<int>(ui::DomCode::BROWSER_FORWARD),
                          static_cast<int>(ui::DomKey::BROWSER_FORWARD),
                          ui::EF_NONE, /*key_display=*/"");
      break;
  }
  return key_event;
}

int ConvertKeyCodeToFlags(ui::KeyboardCode key_code) {
  switch (key_code) {
    case ui::VKEY_LWIN:
    case ui::VKEY_RWIN:
      return ui::EF_COMMAND_DOWN;
    case ui::VKEY_CONTROL:
      return ui::EF_CONTROL_DOWN;
    case ui::VKEY_SHIFT:
    case ui::VKEY_LSHIFT:
    case ui::VKEY_RSHIFT:
      return ui::EF_SHIFT_DOWN;
    case ui::VKEY_MENU:
    case ui::VKEY_RMENU:
      return ui::EF_ALT_DOWN;
    default:
      return ui::EF_NONE;
  }
}

std::unique_ptr<ui::Event> RewriteEventToKeyEvent(
    const ui::Event& event,
    const mojom::KeyEvent& key_event) {
  const ui::EventType event_type = (event.type() == ui::ET_MOUSE_PRESSED ||
                                    event.type() == ui::ET_KEY_PRESSED)
                                       ? ui::ET_KEY_PRESSED
                                       : ui::ET_KEY_RELEASED;
  int flags_to_apply = key_event.modifiers;
  // Do not apply modifier flags when the key is a modifier and it is a release
  // event. Modifier keys do not apply their flag on release.
  if (event_type == ui::ET_KEY_RELEASED &&
      key_event.modifiers ==
          static_cast<uint32_t>(ConvertKeyCodeToFlags(key_event.vkey))) {
    flags_to_apply = ui::EF_NONE;
  }
  auto rewritten_event = std::make_unique<ui::KeyEvent>(
      event_type, key_event.vkey, static_cast<ui::DomCode>(key_event.dom_code),
      flags_to_apply | event.flags(),
      static_cast<ui::DomKey>(key_event.dom_key), event.time_stamp());
  rewritten_event->set_source_device_id(event.source_device_id());
  return rewritten_event;
}

std::unique_ptr<ui::Event> RewriteEventToMouseButtonEvent(
    const ui::Event& event,
    mojom::StaticShortcutAction action) {
  auto* flag_iter = kStaticActionToMouseButtonFlag.find(action);
  CHECK(flag_iter != kStaticActionToMouseButtonFlag.end());
  const int characteristic_flag = flag_iter->second;

  auto* screen = display::Screen::GetScreen();
  CHECK(screen);
  auto display = screen->GetDisplayNearestPoint(screen->GetCursorScreenPoint());
  const gfx::PointF location =
      gfx::ScalePoint(gfx::PointF(screen->GetCursorScreenPoint() -
                                  display.bounds().origin().OffsetFromOrigin()),
                      display.device_scale_factor());

  const ui::EventType type = (event.type() == ui::ET_MOUSE_PRESSED ||
                              event.type() == ui::ET_KEY_PRESSED)
                                 ? ui::ET_MOUSE_PRESSED
                                 : ui::ET_MOUSE_RELEASED;
  auto rewritten_event = std::make_unique<ui::MouseEvent>(
      type, location, location, event.time_stamp(),
      event.flags() | characteristic_flag, characteristic_flag);
  rewritten_event->set_source_device_id(event.source_device_id());
  return rewritten_event;
}

bool IsMouseButtonEvent(const ui::MouseEvent& mouse_event) {
  return mouse_event.type() == ui::ET_MOUSE_PRESSED ||
         mouse_event.type() == ui::ET_MOUSE_RELEASED;
}

bool IsMouseRemappableButton(int flags) {
  return (flags & kMouseRemappableFlags) != 0;
}

bool IsGraphicsTabletRemappableButton(int flags) {
  return (flags & kGraphicsTabletRemappableFlags) != 0;
}

int GetRemappableMouseEventFlags(
    PeripheralCustomizationEventRewriter::DeviceType device_type) {
  switch (device_type) {
    case PeripheralCustomizationEventRewriter::DeviceType::kMouse:
      return kMouseRemappableFlags;
    case PeripheralCustomizationEventRewriter::DeviceType::kGraphicsTablet:
      return kGraphicsTabletRemappableFlags;
  }
}

mojom::ButtonPtr GetButtonFromMouseEvent(const ui::MouseEvent& mouse_event) {
  switch (mouse_event.changed_button_flags()) {
    case ui::EF_LEFT_MOUSE_BUTTON:
      return mojom::Button::NewCustomizableButton(
          mojom::CustomizableButton::kLeft);
    case ui::EF_RIGHT_MOUSE_BUTTON:
      return mojom::Button::NewCustomizableButton(
          mojom::CustomizableButton::kRight);
    case ui::EF_MIDDLE_MOUSE_BUTTON:
      return mojom::Button::NewCustomizableButton(
          mojom::CustomizableButton::kMiddle);
    case ui::EF_FORWARD_MOUSE_BUTTON:
    case ui::EF_BACK_MOUSE_BUTTON:
      break;
  }

  CHECK(mouse_event.changed_button_flags() == ui::EF_FORWARD_MOUSE_BUTTON ||
        mouse_event.changed_button_flags() == ui::EF_BACK_MOUSE_BUTTON);
  auto linux_key_code = ui::GetForwardBackMouseButtonProperty(mouse_event);
  if (!linux_key_code) {
    return (mouse_event.changed_button_flags() == ui::EF_FORWARD_MOUSE_BUTTON)
               ? mojom::Button::NewCustomizableButton(
                     mojom::CustomizableButton::kForward)
               : mojom::Button::NewCustomizableButton(
                     mojom::CustomizableButton::kBack);
  }

  switch (*linux_key_code) {
    case BTN_FORWARD:
      return mojom::Button::NewCustomizableButton(
          mojom::CustomizableButton::kForward);
    case BTN_BACK:
      return mojom::Button::NewCustomizableButton(
          mojom::CustomizableButton::kBack);
    case BTN_SIDE:
      return mojom::Button::NewCustomizableButton(
          mojom::CustomizableButton::kSide);
    case BTN_EXTRA:
      return mojom::Button::NewCustomizableButton(
          mojom::CustomizableButton::kExtra);
  }

  NOTREACHED_NORETURN();
}

int ConvertButtonToFlags(const mojom::Button& button) {
  if (button.is_customizable_button()) {
    switch (button.get_customizable_button()) {
      case mojom::CustomizableButton::kLeft:
        return ui::EF_LEFT_MOUSE_BUTTON;
      case mojom::CustomizableButton::kRight:
        return ui::EF_RIGHT_MOUSE_BUTTON;
      case mojom::CustomizableButton::kMiddle:
        return ui::EF_MIDDLE_MOUSE_BUTTON;
      case mojom::CustomizableButton::kForward:
      case mojom::CustomizableButton::kExtra:
        return ui::EF_FORWARD_MOUSE_BUTTON;
      case mojom::CustomizableButton::kBack:
      case mojom::CustomizableButton::kSide:
        return ui::EF_BACK_MOUSE_BUTTON;
    }
  }

  if (button.is_vkey()) {
    return ConvertKeyCodeToFlags(button.get_vkey());
  }

  return ui::EF_NONE;
}

const mojom::RemappingAction* GetRemappingActionFromMouseSettings(
    const mojom::Button& button,
    const mojom::MouseSettings& settings) {
  const auto button_remapping_iter = base::ranges::find(
      settings.button_remappings, button,
      [](const mojom::ButtonRemappingPtr& entry) { return *entry->button; });
  if (button_remapping_iter != settings.button_remappings.end()) {
    return (*button_remapping_iter)->remapping_action.get();
  }

  return nullptr;
}

const mojom::RemappingAction* GetRemappingActionFromGraphicsTabletSettings(
    const mojom::Button& button,
    const mojom::GraphicsTabletSettings& settings) {
  const auto pen_button_remapping_iter = base::ranges::find(
      settings.pen_button_remappings, button,
      [](const mojom::ButtonRemappingPtr& entry) { return *entry->button; });
  if (pen_button_remapping_iter != settings.pen_button_remappings.end()) {
    return (*pen_button_remapping_iter)->remapping_action.get();
  }

  const auto tablet_button_remapping_iter = base::ranges::find(
      settings.tablet_button_remappings, button,
      [](const mojom::ButtonRemappingPtr& entry) { return *entry->button; });
  if (tablet_button_remapping_iter != settings.tablet_button_remappings.end()) {
    return (*tablet_button_remapping_iter)->remapping_action.get();
  }

  return nullptr;
}

int GetRemappedModifiersFromMouseSettings(
    const mojom::MouseSettings& settings) {
  int modifiers = 0;
  for (const auto& button_remapping : settings.button_remappings) {
    if (button_remapping->remapping_action) {
      modifiers |= ConvertButtonToFlags(*button_remapping->button);
    }
  }
  return modifiers;
}

int GetRemappedModifiersFromGraphicsTabletSettings(
    const mojom::GraphicsTabletSettings& settings) {
  int modifiers = 0;
  for (const auto& button_remapping : settings.pen_button_remappings) {
    modifiers |= ConvertButtonToFlags(*button_remapping->button);
  }
  for (const auto& button_remapping : settings.tablet_button_remappings) {
    modifiers |= ConvertButtonToFlags(*button_remapping->button);
  }
  return modifiers;
}

}  // namespace

// Compares the `DeviceIdButton` struct based on first the device id, and then
// the button stored within the `DeviceIdButton` struct.
bool operator<(
    const PeripheralCustomizationEventRewriter::DeviceIdButton& left,
    const PeripheralCustomizationEventRewriter::DeviceIdButton& right) {
  if (right.device_id != left.device_id) {
    return left.device_id < right.device_id;
  }

  // If both are VKeys, compare them.
  if (left.button->is_vkey() && right.button->is_vkey()) {
    return left.button->get_vkey() < right.button->get_vkey();
  }

  // If both are customizable buttons, compare them.
  if (left.button->is_customizable_button() &&
      right.button->is_customizable_button()) {
    return left.button->get_customizable_button() <
           right.button->get_customizable_button();
  }

  // Otherwise, return true if the lhs is a VKey as they mismatch and VKeys
  // should be considered less than customizable buttons.
  return left.button->is_vkey();
}

PeripheralCustomizationEventRewriter::DeviceIdButton::DeviceIdButton(
    int device_id,
    mojom::ButtonPtr button)
    : device_id(device_id), button(std::move(button)) {}

PeripheralCustomizationEventRewriter::DeviceIdButton::DeviceIdButton(
    DeviceIdButton&& device_id_button)
    : device_id(device_id_button.device_id),
      button(std::move(device_id_button.button)) {}

PeripheralCustomizationEventRewriter::DeviceIdButton::~DeviceIdButton() =
    default;

PeripheralCustomizationEventRewriter::DeviceIdButton&
PeripheralCustomizationEventRewriter::DeviceIdButton::operator=(
    PeripheralCustomizationEventRewriter::DeviceIdButton&& device_id_button) =
    default;

PeripheralCustomizationEventRewriter::PeripheralCustomizationEventRewriter(
    InputDeviceSettingsController* input_device_settings_controller)
    : input_device_settings_controller_(input_device_settings_controller) {}
PeripheralCustomizationEventRewriter::~PeripheralCustomizationEventRewriter() =
    default;

absl::optional<PeripheralCustomizationEventRewriter::DeviceType>
PeripheralCustomizationEventRewriter::GetDeviceTypeToObserve(int device_id) {
  if (mice_to_observe_.contains(device_id)) {
    return DeviceType::kMouse;
  }
  if (graphics_tablets_to_observe_.contains(device_id)) {
    return DeviceType::kGraphicsTablet;
  }
  return absl::nullopt;
}

void PeripheralCustomizationEventRewriter::StartObservingMouse(
    int device_id,
    bool can_rewrite_key_event) {
  if (can_rewrite_key_event) {
    mice_to_observe_key_events_.insert(device_id);
  }
  mice_to_observe_.insert(device_id);
}

void PeripheralCustomizationEventRewriter::StartObservingGraphicsTablet(
    int device_id) {
  graphics_tablets_to_observe_.insert(device_id);
}

void PeripheralCustomizationEventRewriter::StopObserving() {
  graphics_tablets_to_observe_.clear();
  mice_to_observe_.clear();
  mice_to_observe_key_events_.clear();
}

bool PeripheralCustomizationEventRewriter::NotifyMouseEventObserving(
    const ui::MouseEvent& mouse_event,
    DeviceType device_type) {
  if (!IsMouseButtonEvent(mouse_event)) {
    return false;
  }

  // Make sure the button is remappable for the current `device_type`.
  switch (device_type) {
    case DeviceType::kMouse:
      if (!IsMouseRemappableButton(mouse_event.changed_button_flags())) {
        return false;
      }
      break;
    case DeviceType::kGraphicsTablet:
      if (!IsGraphicsTabletRemappableButton(
              mouse_event.changed_button_flags())) {
        return false;
      }
      break;
  }

  if (mouse_event.type() != ui::ET_MOUSE_PRESSED) {
    return true;
  }

  const auto button = GetButtonFromMouseEvent(mouse_event);
  switch (device_type) {
    case DeviceType::kMouse:
      input_device_settings_controller_->OnMouseButtonPressed(
          mouse_event.source_device_id(), *button);
      break;
    case DeviceType::kGraphicsTablet:
      input_device_settings_controller_->OnGraphicsTabletButtonPressed(
          mouse_event.source_device_id(), *button);
      break;
  }

  return true;
}

bool PeripheralCustomizationEventRewriter::NotifyKeyEventObserving(
    const ui::KeyEvent& key_event,
    DeviceType device_type) {
  // Only mice that are in the mice_to_observe_key_events_ set should be allowed
  // to observe key events.
  if (device_type == DeviceType::kMouse &&
      !mice_to_observe_key_events_.contains(key_event.source_device_id())) {
    return false;
  }

  // Observers should only be notified on key presses.
  if (key_event.type() != ui::ET_KEY_PRESSED) {
    return true;
  }

  const auto button = mojom::Button::NewVkey(key_event.key_code());
  switch (device_type) {
    case DeviceType::kMouse:
      input_device_settings_controller_->OnMouseButtonPressed(
          key_event.source_device_id(), *button);
      break;
    case DeviceType::kGraphicsTablet:
      input_device_settings_controller_->OnGraphicsTabletButtonPressed(
          key_event.source_device_id(), *button);
      break;
  }

  return true;
}

bool PeripheralCustomizationEventRewriter::RewriteEventFromButton(
    const ui::Event& event,
    const mojom::Button& button,
    std::unique_ptr<ui::Event>& rewritten_event) {
  auto* remapping_action = GetRemappingAction(event.source_device_id(), button);
  if (!remapping_action) {
    return false;
  }

  if (remapping_action->is_accelerator_action()) {
    if (event.type() == ui::ET_KEY_PRESSED ||
        event.type() == ui::ET_MOUSE_PRESSED) {
      // Every accelerator supported by peripheral customization is not impacted
      // by the accelerator passed. Therefore, passing an empty accelerator will
      // cause no issues.
      Shell::Get()->accelerator_controller()->PerformActionIfEnabled(
          remapping_action->get_accelerator_action(), /*accelerator=*/{});
    }

    return true;
  }

  if (remapping_action->is_key_event()) {
    const auto& key_event = remapping_action->get_key_event();
    rewritten_event = RewriteEventToKeyEvent(event, *key_event);
  }

  if (remapping_action->is_static_shortcut_action()) {
    const auto static_action = remapping_action->get_static_shortcut_action();
    if (static_action == mojom::StaticShortcutAction::kDisable) {
      // Return true to discard the event.
      return true;
    }

    if (kStaticActionToMouseButtonFlag.contains(static_action)) {
      rewritten_event = RewriteEventToMouseButtonEvent(event, static_action);
    } else {
      rewritten_event = RewriteEventToKeyEvent(
          event, GetStaticShortcutAction(
                     remapping_action->get_static_shortcut_action()));
    }
  }

  return false;
}

ui::EventDispatchDetails PeripheralCustomizationEventRewriter::RewriteKeyEvent(
    const ui::KeyEvent& key_event,
    const Continuation continuation) {
  auto device_type_to_observe =
      GetDeviceTypeToObserve(key_event.source_device_id());
  if (device_type_to_observe) {
    if (NotifyKeyEventObserving(key_event, *device_type_to_observe)) {
      return DiscardEvent(continuation);
    }
  }

  std::unique_ptr<ui::Event> rewritten_event;
  mojom::ButtonPtr button = mojom::Button::NewVkey(key_event.key_code());
  bool updated_button_map = false;
  if (RewriteEventFromButton(key_event, *button, rewritten_event)) {
    return DiscardEvent(continuation);
  }

  // Update pressed button map now if either there was no rewrite or if its not
  // a mouse release event.
  if (!rewritten_event || rewritten_event->type() != ui::ET_MOUSE_RELEASED) {
    updated_button_map = true;
    UpdatePressedButtonMap(std::move(button), key_event, rewritten_event);
  }

  if (!rewritten_event) {
    rewritten_event = std::make_unique<ui::KeyEvent>(key_event);
  }

  RemoveRemappedModifiers(*rewritten_event);
  ApplyRemappedModifiers(*rewritten_event);

  if (!updated_button_map) {
    UpdatePressedButtonMap(std::move(button), key_event, rewritten_event);
  }

  return SendEvent(continuation, rewritten_event.get());
}

void PeripheralCustomizationEventRewriter::UpdatePressedButtonMap(
    mojom::ButtonPtr button,
    const ui::Event& original_event,
    const std::unique_ptr<ui::Event>& rewritten_event) {
  DeviceIdButton device_id_button_key =
      DeviceIdButton{original_event.source_device_id(), std::move(button)};

  // If the button is released, the entry must be removed from the map.
  if (original_event.type() == ui::ET_MOUSE_RELEASED ||
      original_event.type() == ui::ET_KEY_RELEASED) {
    device_button_to_flags_.erase(std::move(device_id_button_key));
    return;
  }

  const int key_event_flags =
      (rewritten_event && rewritten_event->IsKeyEvent())
          ? ConvertKeyCodeToFlags(rewritten_event->AsKeyEvent()->key_code())
          : 0;
  const int mouse_event_flags =
      (rewritten_event && rewritten_event->IsMouseEvent())
          ? rewritten_event->AsMouseEvent()->changed_button_flags()
          : 0;

  const int combined_flags = key_event_flags | mouse_event_flags;
  if (!combined_flags) {
    return;
  }

  // Add the entry to the map with the flags that must be applied to other
  // events.
  device_button_to_flags_.insert_or_assign(std::move(device_id_button_key),
                                           combined_flags);
}

ui::EventDispatchDetails
PeripheralCustomizationEventRewriter::RewriteMouseEvent(
    const ui::MouseEvent& mouse_event,
    const Continuation continuation) {
  auto device_type_to_observe =
      GetDeviceTypeToObserve(mouse_event.source_device_id());
  if (device_type_to_observe) {
    if (NotifyMouseEventObserving(mouse_event, *device_type_to_observe)) {
      return DiscardEvent(continuation);
    }

    // Otherwise, the flags must be cleared for the remappable buttons so they
    // do not affect the application while the mouse is meant to be observed.
    std::unique_ptr<ui::Event> rewritten_event = CloneEvent(mouse_event);
    const int remappable_flags =
        GetRemappableMouseEventFlags(*device_type_to_observe);
    rewritten_event->set_flags(rewritten_event->flags() & ~remappable_flags);
    if (rewritten_event->IsMouseEvent()) {
      auto& rewritten_mouse_event = *rewritten_event->AsMouseEvent();
      rewritten_mouse_event.set_changed_button_flags(
          rewritten_mouse_event.changed_button_flags() & ~remappable_flags);
    }
    return SendEvent(continuation, rewritten_event.get());
  }

  std::unique_ptr<ui::Event> rewritten_event;
  mojom::ButtonPtr button;
  bool updated_button_map = false;
  if (IsMouseButtonEvent(mouse_event) && mouse_event.changed_button_flags()) {
    button = GetButtonFromMouseEvent(mouse_event);
    if (RewriteEventFromButton(mouse_event, *button, rewritten_event)) {
      return DiscardEvent(continuation);
    }
    // Update pressed button map now if either there was no rewrite or if its
    // not a mouse release event.
    if (!rewritten_event || rewritten_event->type() != ui::ET_MOUSE_RELEASED) {
      updated_button_map = true;
      UpdatePressedButtonMap(std::move(button), mouse_event, rewritten_event);
    }
  }

  if (!rewritten_event) {
    rewritten_event = CloneEvent(mouse_event);
  }

  RemoveRemappedModifiers(*rewritten_event);
  ApplyRemappedModifiers(*rewritten_event);

  if (!updated_button_map) {
    UpdatePressedButtonMap(std::move(button), mouse_event, rewritten_event);
  }

  return SendEvent(continuation, rewritten_event.get());
}

ui::EventDispatchDetails PeripheralCustomizationEventRewriter::RewriteEvent(
    const ui::Event& event,
    const Continuation continuation) {
  DCHECK(features::IsPeripheralCustomizationEnabled());

  if (event.IsMouseEvent()) {
    return RewriteMouseEvent(*event.AsMouseEvent(), continuation);
  }

  if (event.IsKeyEvent()) {
    return RewriteKeyEvent(*event.AsKeyEvent(), continuation);
  }

  return SendEvent(continuation, &event);
}

const mojom::RemappingAction*
PeripheralCustomizationEventRewriter::GetRemappingAction(
    int device_id,
    const mojom::Button& button) {
  const auto* mouse_settings =
      input_device_settings_controller_->GetMouseSettings(device_id);
  if (mouse_settings) {
    return GetRemappingActionFromMouseSettings(button, *mouse_settings);
  }

  const auto* graphics_tablet_settings =
      input_device_settings_controller_->GetGraphicsTabletSettings(device_id);
  if (graphics_tablet_settings) {
    return GetRemappingActionFromGraphicsTabletSettings(
        button, *graphics_tablet_settings);
  }

  return nullptr;
}

void PeripheralCustomizationEventRewriter::RemoveRemappedModifiers(
    ui::Event& event) {
  int modifier_flags = 0;
  if (const auto* mouse_settings =
          input_device_settings_controller_->GetMouseSettings(
              event.source_device_id());
      mouse_settings) {
    modifier_flags = GetRemappedModifiersFromMouseSettings(*mouse_settings);
  } else if (const auto* graphics_tablet_settings =
                 input_device_settings_controller_->GetGraphicsTabletSettings(
                     event.source_device_id());
             graphics_tablet_settings) {
    modifier_flags = GetRemappedModifiersFromGraphicsTabletSettings(
        *graphics_tablet_settings);
  }

  // TODO(dpad): This logic isn't quite correct. If a second devices is holding
  // "Ctrl" and the original device has a button that is "Ctrl" that is
  // remapped, this will behave incorrectly as it will remove "Ctrl". Instead,
  // this needs to track what keys are being pressed by the device that have
  // modifiers attached to them. For now, this is close enough to being correct.
  event.set_flags(event.flags() & ~modifier_flags);
}

void PeripheralCustomizationEventRewriter::ApplyRemappedModifiers(
    ui::Event& event) {
  int flags = 0;
  for (const auto& [_, flag] : device_button_to_flags_) {
    flags |= flag;
  }
  event.set_flags(event.flags() | flags);
}

std::unique_ptr<ui::Event> PeripheralCustomizationEventRewriter::CloneEvent(
    const ui::Event& event) {
  std::unique_ptr<ui::Event> cloned_event = event.Clone();
  // SetNativeEvent must be called explicitly as native events are not copied
  // on ChromeOS by default. This is because `PlatformEvent` is a pointer by
  // default, so its lifetime can not be guaranteed in general. In this case,
  // the lifetime of  `rewritten_event` is guaranteed to be less than the
  // original `mouse_event`.
  SetNativeEvent(*cloned_event, event.native_event());
  return cloned_event;
}

}  // namespace ash