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
|
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/40285824): Remove this and convert code to safer constructs.
#pragma allow_unsafe_buffers
#endif
#include "components/exo/keyboard.h"
#include <algorithm>
#include "ash/accelerators/accelerator_controller_impl.h"
#include "ash/accelerators/accelerator_table.h"
#include "ash/constants/ash_features.h"
#include "ash/keyboard/ui/keyboard_ui_controller.h"
#include "ash/keyboard/ui/keyboard_util.h"
#include "ash/public/cpp/accelerators.h"
#include "ash/public/cpp/keyboard/keyboard_controller.h"
#include "ash/shell.h"
#include "ash/wm/window_state.h"
#include "base/containers/contains.h"
#include "base/containers/flat_set.h"
#include "base/containers/flat_tree.h"
#include "base/containers/span.h"
#include "base/functional/bind.h"
#include "base/no_destructor.h"
#include "base/task/single_thread_task_runner.h"
#include "base/trace_event/trace_event.h"
#include "chromeos/ui/base/app_types.h"
#include "chromeos/ui/base/window_properties.h"
#include "components/exo/input_trace.h"
#include "components/exo/keyboard_delegate.h"
#include "components/exo/keyboard_device_configuration_delegate.h"
#include "components/exo/keyboard_modifiers.h"
#include "components/exo/seat.h"
#include "components/exo/shell_surface.h"
#include "components/exo/shell_surface_util.h"
#include "components/exo/surface.h"
#include "components/exo/xkb_tracker.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/client/focus_client.h"
#include "ui/aura/window.h"
#include "ui/base/ime/constants.h"
#include "ui/base/ime/events.h"
#include "ui/base/ime/input_method.h"
#include "ui/events/base_event_utils.h"
#include "ui/events/event.h"
#include "ui/events/event_constants.h"
#include "ui/events/keycodes/dom/dom_code.h"
#include "ui/events/keycodes/dom/keycode_converter.h"
#include "ui/views/widget/widget.h"
#include "ui/wm/core/window_util.h"
namespace exo {
namespace {
// This value must be bigger than the priority for DataDevice.
constexpr int kKeyboardSeatObserverPriority = 1;
static_assert(Seat::IsValidObserverPriority(kKeyboardSeatObserverPriority),
"kKeyboardSeatObserverPriority is not in the valid range.");
// Delay until a key state change expected to be acknowledged is expired.
constexpr int kExpirationDelayForPendingKeyAcksMs = 1000;
// The accelerator keys reserved to be processed by chrome.
constexpr struct {
ui::KeyboardCode keycode;
int modifiers;
} kReservedAccelerators[] = {
{ui::VKEY_F13, ui::EF_NONE},
{ui::VKEY_I, ui::EF_SHIFT_DOWN | ui::EF_ALT_DOWN},
{ui::VKEY_Z, ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN}};
bool ProcessAccelerator(Surface* surface, const ui::KeyEvent* event) {
views::Widget* widget =
views::Widget::GetTopLevelWidgetForNativeView(surface->window());
if (widget) {
views::FocusManager* focus_manager = widget->GetFocusManager();
return focus_manager->ProcessAccelerator(ui::Accelerator(*event));
}
return false;
}
bool IsVirtualKeyboardEnabled() {
return keyboard::GetAccessibilityKeyboardEnabled() ||
keyboard::GetTouchKeyboardEnabled() ||
(keyboard::KeyboardUIController::HasInstance() &&
keyboard::KeyboardUIController::Get()->IsEnableFlagSet(
keyboard::KeyboardEnableFlag::kCommandLineEnabled));
}
bool IsReservedAccelerator(const ui::KeyEvent* event) {
for (const auto& accelerator : kReservedAccelerators) {
if (event->flags() == accelerator.modifiers &&
event->key_code() == accelerator.keycode) {
return true;
}
}
return false;
}
// Returns false if an accelerator is not reserved or it's not enabled.
bool ProcessAcceleratorIfReserved(Surface* surface, ui::KeyEvent* event) {
return IsReservedAccelerator(event) && ProcessAccelerator(surface, event);
}
// Returns true if the surface needs to support IME.
// TODO(yhanada, https://crbug.com/847500): Remove this when we find a way
// to fix https://crbug.com/847500 without breaking ARC apps/Lacros browser.
bool IsImeSupportedSurface(Surface* surface) {
aura::Window* window = surface->window();
while (window) {
const auto app_type = window->GetProperty(chromeos::kAppTypeKey);
switch (app_type) {
case chromeos::AppType::ARC_APP:
case chromeos::AppType::CROSTINI_APP:
return true;
default:
// Do nothing.
break;
}
// For notifications, billing surfaces, etc. AppType::ARC_APP is not set
// despite them being from ARC. Ideally AppType should be added to them, but
// there is a risk that breaks other features e.g. full restore.
// TODO(tetsui): find a way to remove this.
if (window->GetProperty(aura::client::kSkipImeProcessing))
return true;
if (aura::Window* transient_parent = wm::GetTransientParent(window)) {
window = transient_parent;
} else {
window = window->parent();
}
}
return false;
}
bool IsAutoRepeatEnabled(const ui::KeyEvent& event) {
const auto* properties = event.properties();
if (!properties) {
return true;
}
return !ui::HasKeyEventSuppressAutoRepeat(*properties);
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
// Keyboard, public:
Keyboard::Keyboard(std::unique_ptr<KeyboardDelegate> delegate, Seat* seat)
: delegate_(std::move(delegate)),
seat_(seat),
expiration_delay_for_pending_key_acks_(
base::Milliseconds(kExpirationDelayForPendingKeyAcksMs)) {
seat_->AddObserver(this, kKeyboardSeatObserverPriority);
auto* keyboard_controller = ash::KeyboardController::Get();
keyboard_controller->AddObserver(this);
ash::ImeControllerImpl* ime_controller = ash::Shell::Get()->ime_controller();
ime_controller->AddObserver(this);
delegate_->OnKeyboardLayoutUpdated(seat_->xkb_tracker()->GetKeymap().get());
OnSurfaceFocused(seat_->GetFocusedSurface(), nullptr,
!!seat_->GetFocusedSurface());
// Send the initial key repeat settings, iff it is already initialized.
// If not, that means Profile is not yet initialized, thus skipping,
// because when it is initialized, OnKeyRepeatSettingsChanged is called
// by KeyboardController.
auto key_repeat_settings = keyboard_controller->GetKeyRepeatSettings();
if (key_repeat_settings.has_value())
OnKeyRepeatSettingsChanged(key_repeat_settings.value());
}
Keyboard::~Keyboard() {
RemoveEventHandler();
for (KeyboardObserver& observer : observer_list_)
observer.OnKeyboardDestroying(this);
if (focus_)
focus_->RemoveSurfaceObserver(this);
ash::Shell::Get()->ime_controller()->RemoveObserver(this);
ash::KeyboardController::Get()->RemoveObserver(this);
seat_->RemoveObserver(this);
}
bool Keyboard::HasDeviceConfigurationDelegate() const {
return !!device_configuration_delegate_;
}
void Keyboard::SetDeviceConfigurationDelegate(
KeyboardDeviceConfigurationDelegate* delegate) {
device_configuration_delegate_ = delegate;
UpdateKeyboardType();
}
void Keyboard::AddObserver(KeyboardObserver* observer) {
observer_list_.AddObserver(observer);
}
bool Keyboard::HasObserver(KeyboardObserver* observer) const {
return observer_list_.HasObserver(observer);
}
void Keyboard::RemoveObserver(KeyboardObserver* observer) {
observer_list_.RemoveObserver(observer);
}
void Keyboard::SetNeedKeyboardKeyAcks(bool need_acks) {
RemoveEventHandler();
are_keyboard_key_acks_needed_ = need_acks;
AddEventHandler();
}
bool Keyboard::AreKeyboardKeyAcksNeeded() const {
// Keyboard class doesn't need key acks while the spoken feedback is enabled.
// While the spoken feedback is enabled, a key event is sent to both of a
// wayland client and Chrome to give a chance to work to Chrome OS's
// shortcuts.
return are_keyboard_key_acks_needed_;
}
void Keyboard::AckKeyboardKey(uint32_t serial, bool handled) {
auto it = pending_key_acks_.find(serial);
if (it == pending_key_acks_.end())
return;
auto* key_event = &it->second.first;
if (!handled && !key_event->handled() && focus_)
ProcessAccelerator(focus_, key_event);
pending_key_acks_.erase(serial);
}
////////////////////////////////////////////////////////////////////////////////
// ui::EventHandler overrides:
void Keyboard::OnKeyEvent(ui::KeyEvent* event) {
if (!focus_ || seat_->was_shutdown())
return;
DCHECK(GetShellRootSurface(static_cast<aura::Window*>(event->target())) ||
Surface::AsSurface(static_cast<aura::Window*>(event->target())));
// Ignore synthetic key repeat events.
if (event->is_repeat()) {
// Clients should not see key repeat events and instead handle them on the
// client side.
// Mark the key repeat events as handled to avoid them from invoking
// accelerators.
event->SetHandled();
return;
}
TRACE_EXO_INPUT_EVENT(event);
// Process reserved accelerators or ash accelerators which need to be handled
// before sending it to client.
if (ProcessAcceleratorIfReserved(focus_, event)) {
// Discard a key press event if the corresponding accelerator is handled.
event->SetHandled();
// The current focus might have been reset while processing accelerators.
if (!focus_)
return;
}
// When IME ate a key event, we use the event only for tracking key states and
// ignore for further processing. Otherwise it is handled in two places (IME
// and client) and causes undesired behavior.
// If the window should receive a key event before IME, Exo should send any
// key events to a client. The client will send back the events to IME if
// needed.
const bool consumed_by_ime =
!focus_->window()->GetProperty(aura::client::kSkipImeProcessing) &&
ConsumedByIme(*event);
// Currently, physical keycode is tracked in Seat, assuming that the
// Keyboard::OnKeyEvent is called between Seat::WillProcessEvent and
// Seat::DidProcessEvent. However, if IME is enabled, it is no longer true,
// because IME work in async approach, and on its dispatching, call stack
// is split so actually Keyboard::OnKeyEvent is called after
// Seat::DidProcessEvent.
// TODO(yhanada): This is a quick fix for https://crbug.com/859071. Remove
// ARC-/Lacros-specific code path once we can find a way to manage
// press/release events pair for synthetic events.
PhysicalCode physical_code =
seat_->physical_code_for_currently_processing_event();
const auto* physical_dom_code = std::get_if<ui::DomCode>(&physical_code);
if (physical_dom_code && *physical_dom_code == ui::DomCode::NONE &&
focused_on_ime_supported_surface_) {
// This key event is a synthetic event.
// Consider DomCode field of the event as a physical code
// for synthetic events when focus surface belongs to an ARC application.
physical_code = event->code();
}
switch (event->type()) {
case ui::EventType::kKeyPressed: {
auto it = pressed_keys_.find(physical_code);
const bool should_handle =
(it == pressed_keys_.end()) ||
(event->flags() & ui::EF_IS_CUSTOMIZED_FROM_BUTTON);
const bool is_physical_code_none =
physical_dom_code && *physical_dom_code == ui::DomCode::NONE;
if (should_handle && !event->handled() && !is_physical_code_none) {
if (bool auto_repeat_enabled = IsAutoRepeatEnabled(*event);
auto_repeat_enabled != auto_repeat_enabled_) {
auto_repeat_enabled_ = auto_repeat_enabled;
if (auto settings =
ash::KeyboardController::Get()->GetKeyRepeatSettings();
settings.has_value()) {
OnKeyRepeatSettingsChanged(*settings);
}
}
for (auto& observer : observer_list_) {
observer.OnKeyboardKey(event->time_stamp(), event->code(), true);
}
if (!consumed_by_ime) {
// Process key press event if not already handled and not already
// pressed.
uint32_t serial = delegate_->OnKeyboardKey(event->time_stamp(),
event->code(), true);
if (AreKeyboardKeyAcksNeeded()) {
pending_key_acks_.insert(
{serial,
{*event, base::TimeTicks::Now() +
expiration_delay_for_pending_key_acks_}});
event->SetHandled();
}
}
// Keep track of both the physical code and potentially re-written
// code that this event generated.
pressed_keys_[physical_code].emplace(event->code(), consumed_by_ime);
} else if (!should_handle && !event->handled()) {
// Non-repeate key events for already pressed key can be sent in some
// cases (e.g. Holding 'A' key then holding 'B' key then releasing 'A'
// key sends a non-repeat 'B' key press event).
// When it happens, we don't want to send the press event to a client
// and also want to avoid it from invoking any accelerator.
if (AreKeyboardKeyAcksNeeded())
event->SetHandled();
}
} break;
case ui::EventType::kKeyReleased: {
// Process key release event if currently pressed.
auto key_state_set_iter = pressed_keys_.find(physical_code);
if (key_state_set_iter == pressed_keys_.end()) {
break;
}
auto& key_state_set = key_state_set_iter->second;
auto key_state_iter = std::ranges::find(
key_state_set, event->code(),
[](const KeyState& key_state) { return key_state.code; });
// If we can't find the specific key event to release, all previously
// pressed events tied to this physical key should be released.
auto [begin, end] =
key_state_iter == key_state_set.end()
? std::pair(key_state_set.begin(), key_state_set.end())
: std::pair(key_state_iter, key_state_iter + 1);
for (auto iter = begin; iter != end; ++iter) {
for (auto& observer : observer_list_) {
observer.OnKeyboardKey(event->time_stamp(), iter->code, false);
}
if (!iter->consumed_by_ime) {
// We use the code that was generated when the physical key was
// pressed rather than the current event code. This allows events
// to be re-written before dispatch, while still allowing the
// client to track the state of the physical keyboard.
uint32_t serial =
delegate_->OnKeyboardKey(event->time_stamp(), iter->code, false);
if (AreKeyboardKeyAcksNeeded()) {
auto ack_it =
pending_key_acks_
.insert(
{serial,
{*event, base::TimeTicks::Now() +
expiration_delay_for_pending_key_acks_}})
.first;
// Handled is not copied with Event's copy ctor, so explicitly copy
// here.
if (event->handled()) {
ack_it->second.first.SetHandled();
}
event->SetHandled();
}
}
}
key_state_set.erase(begin, end);
if (key_state_set.empty()) {
pressed_keys_.erase(key_state_set_iter);
}
} break;
default:
NOTREACHED();
}
if (pending_key_acks_.empty())
return;
if (process_expired_pending_key_acks_pending_)
return;
ScheduleProcessExpiredPendingKeyAcks(expiration_delay_for_pending_key_acks_);
}
////////////////////////////////////////////////////////////////////////////////
// SurfaceObserver overrides:
void Keyboard::OnSurfaceDestroying(Surface* surface) {
DCHECK(surface == focus_);
SetFocus(nullptr);
}
////////////////////////////////////////////////////////////////////////////////
// SeatObserver overrides:
void Keyboard::OnSurfaceFocused(Surface* gained_focus,
Surface* lost_focused,
bool has_focused_surface) {
Surface* gained_focus_surface =
gained_focus && delegate_->CanAcceptKeyboardEventsForSurface(gained_focus)
? gained_focus
: nullptr;
if (gained_focus_surface != focus_)
SetFocus(gained_focus_surface);
}
void Keyboard::OnKeyboardModifierUpdated() {
// XkbTracker must be updated in the Seat, before calling this method.
if (focus_)
delegate_->OnKeyboardModifiers(seat_->xkb_tracker()->GetModifiers());
}
////////////////////////////////////////////////////////////////////////////////
// ash::KeyboardControllerObserver overrides:
void Keyboard::OnKeyboardEnableFlagsChanged(
const std::set<keyboard::KeyboardEnableFlag>& flags) {
UpdateKeyboardType();
}
void Keyboard::OnKeyRepeatSettingsChanged(
const ash::KeyRepeatSettings& settings) {
delegate_->OnKeyRepeatSettingsChanged(
settings.enabled && auto_repeat_enabled_, settings.delay,
settings.interval);
}
////////////////////////////////////////////////////////////////////////////////
// ash::ImeController::Observer overrides:
void Keyboard::OnCapsLockChanged(bool enabled) {}
void Keyboard::OnKeyboardLayoutNameChanged(const std::string& layout_name) {
// XkbTracker must be updated in the Seat, before calling this method.
// Ensured by the observer registration order.
delegate_->OnKeyboardLayoutUpdated(seat_->xkb_tracker()->GetKeymap().get());
}
////////////////////////////////////////////////////////////////////////////////
// Keyboard, private:
base::flat_map<PhysicalCode, base::flat_set<KeyState>>
Keyboard::GetPressedKeysForSurface(Surface* surface) {
// Remove system keys from being sent as pressed keys unless the window
// can consume them.
base::flat_map<PhysicalCode, base::flat_set<KeyState>> filtered_keys =
pressed_keys_;
aura::Window* top_level = surface->window()->GetToplevelWindow();
if (top_level && !ash::WindowState::Get(top_level)->CanConsumeSystemKeys()) {
base::EraseIf(filtered_keys, [](auto& key_state_set_pair) {
base::EraseIf(key_state_set_pair.second, [](auto& key_state) {
return ash::AcceleratorController::IsSystemKey(key_state.key_code);
});
return key_state_set_pair.second.empty();
});
}
return filtered_keys;
}
void Keyboard::SetFocus(Surface* surface) {
if (focus_) {
RemoveEventHandler();
delegate_->OnKeyboardLeave(focus_);
focus_->RemoveSurfaceObserver(this);
focus_ = nullptr;
pending_key_acks_.clear();
}
if (surface) {
pressed_keys_ = seat_->pressed_keys();
auto enter_keys = GetPressedKeysForSurface(surface);
delegate_->OnKeyboardModifiers(seat_->xkb_tracker()->GetModifiers());
delegate_->OnKeyboardEnter(surface, enter_keys);
focus_ = surface;
focus_->AddSurfaceObserver(this);
focused_on_ime_supported_surface_ = IsImeSupportedSurface(surface);
AddEventHandler();
}
}
void Keyboard::ProcessExpiredPendingKeyAcks() {
DCHECK(process_expired_pending_key_acks_pending_);
process_expired_pending_key_acks_pending_ = false;
// Check pending acks and process them as if it is handled if
// expiration time passed.
base::TimeTicks current_time = base::TimeTicks::Now();
while (!pending_key_acks_.empty()) {
auto it = pending_key_acks_.begin();
const ui::KeyEvent event = it->second.first;
if (it->second.second > current_time)
break;
// Expiration time has passed, assume the event was handled.
pending_key_acks_.erase(it);
}
if (pending_key_acks_.empty())
return;
base::TimeDelta delay_until_next_process_expired_pending_key_acks =
pending_key_acks_.begin()->second.second - current_time;
ScheduleProcessExpiredPendingKeyAcks(
delay_until_next_process_expired_pending_key_acks);
}
void Keyboard::ScheduleProcessExpiredPendingKeyAcks(base::TimeDelta delay) {
DCHECK(!process_expired_pending_key_acks_pending_);
process_expired_pending_key_acks_pending_ = true;
base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&Keyboard::ProcessExpiredPendingKeyAcks,
weak_ptr_factory_.GetWeakPtr()),
delay);
}
void Keyboard::AddEventHandler() {
if (!focus_)
return;
// Toplevel window can be not ShellSurface, for example for a notification
// surface.
aura::Window* toplevel_window = focus_->window();
if (toplevel_window->GetToplevelWindow())
toplevel_window = toplevel_window->GetToplevelWindow();
if (are_keyboard_key_acks_needed_)
toplevel_window->AddPreTargetHandler(this);
else
toplevel_window->AddPostTargetHandler(this);
}
void Keyboard::RemoveEventHandler() {
if (!focus_)
return;
// Toplevel window can be not ShellSurface, for example for a notification
// surface.
aura::Window* toplevel_window = focus_->window();
if (toplevel_window->GetToplevelWindow())
toplevel_window = toplevel_window->GetToplevelWindow();
if (are_keyboard_key_acks_needed_)
toplevel_window->RemovePreTargetHandler(this);
else
toplevel_window->RemovePostTargetHandler(this);
}
void Keyboard::UpdateKeyboardType() {
if (!device_configuration_delegate_)
return;
// Ignore kAndroidDisabled which affects |enabled| and just test for a11y
// and touch enabled keyboards. TODO(yhanada): Fix this using an Android
// specific KeyboardUI implementation. https://crbug.com/897655.
const bool is_physical = !IsVirtualKeyboardEnabled();
device_configuration_delegate_->OnKeyboardTypeChanged(is_physical);
}
} // namespace exo
|