shortcuts.dart 56.5 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
import 'dart:collection';

7
import 'package:flutter/foundation.dart';
8
import 'package:flutter/scheduler.dart';
9 10 11 12 13 14
import 'package:flutter/services.dart';

import 'actions.dart';
import 'focus_manager.dart';
import 'focus_scope.dart';
import 'framework.dart';
15
import 'platform_menu_bar.dart';
16 17 18 19 20 21 22 23 24 25 26 27

/// A set of [KeyboardKey]s that can be used as the keys in a [Map].
///
/// A key set contains the keys that are down simultaneously to represent a
/// shortcut.
///
/// This is a thin wrapper around a [Set], but changes the equality comparison
/// from an identity comparison to a contents comparison so that non-identical
/// sets with the same keys in them will compare as equal.
///
/// See also:
///
28
///  * [ShortcutManager], which uses [LogicalKeySet] (a [KeySet] subclass) to
29
///    define its key map.
Tong Mu's avatar
Tong Mu committed
30
@immutable
31
class KeySet<T extends KeyboardKey> {
32 33 34 35
  /// A constructor for making a [KeySet] of up to four keys.
  ///
  /// If you need a set of more than four keys, use [KeySet.fromSet].
  ///
Tong Mu's avatar
Tong Mu committed
36
  /// The same [KeyboardKey] may not be appear more than once in the set.
37 38
  KeySet(
    T key1, [
39 40 41
    T? key2,
    T? key3,
    T? key4,
42
  ])  : _keys = HashSet<T>()..add(key1) {
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
    int count = 1;
    if (key2 != null) {
      _keys.add(key2);
      assert(() {
        count++;
        return true;
      }());
    }
    if (key3 != null) {
      _keys.add(key3);
      assert(() {
        count++;
        return true;
      }());
    }
    if (key4 != null) {
      _keys.add(key4);
      assert(() {
        count++;
        return true;
      }());
    }
    assert(_keys.length == count, 'Two or more provided keys are identical. Each key must appear only once.');
  }

68
  /// Create a [KeySet] from a set of [KeyboardKey]s.
69 70 71
  ///
  /// Do not mutate the `keys` set after passing it to this object.
  ///
Tong Mu's avatar
Tong Mu committed
72
  /// The `keys` set must not be empty.
73
  KeySet.fromSet(Set<T> keys)
74
      : assert(keys.isNotEmpty),
75
        assert(!keys.contains(null)),
76
        _keys = HashSet<T>.of(keys);
77

78 79
  /// Returns a copy of the [KeyboardKey]s in this [KeySet].
  Set<T> get keys => _keys.toSet();
80
  final HashSet<T> _keys;
81 82 83 84 85 86

  @override
  bool operator ==(Object other) {
    if (other.runtimeType != runtimeType) {
      return false;
    }
87 88
    return other is KeySet<T>
        && setEquals<T>(other._keys, _keys);
89 90
  }

91 92
  // Cached hash code value. Improves [hashCode] performance by 27%-900%,
  // depending on key set size and read/write ratio.
93
  @override
Tong Mu's avatar
Tong Mu committed
94
  late final int hashCode = _computeHashCode(_keys);
95

Tong Mu's avatar
Tong Mu committed
96 97 98 99
  // Arrays used to temporarily store hash codes for sorting.
  static final List<int> _tempHashStore3 = <int>[0, 0, 0]; // used to sort exactly 3 keys
  static final List<int> _tempHashStore4 = <int>[0, 0, 0, 0]; // used to sort exactly 4 keys
  static int _computeHashCode<T>(Set<T> keys) {
100
    // Compute order-independent hash and cache it.
Tong Mu's avatar
Tong Mu committed
101 102
    final int length = keys.length;
    final Iterator<T> iterator = keys.iterator;
103 104 105 106 107 108 109

    // There's always at least one key. Just extract it.
    iterator.moveNext();
    final int h1 = iterator.current.hashCode;

    if (length == 1) {
      // Don't do anything fancy if there's exactly one key.
Tong Mu's avatar
Tong Mu committed
110
      return h1;
111 112 113 114 115 116
    }

    iterator.moveNext();
    final int h2 = iterator.current.hashCode;
    if (length == 2) {
      // No need to sort if there's two keys, just compare them.
Tong Mu's avatar
Tong Mu committed
117
      return h1 < h2
118 119
        ? Object.hash(h1, h2)
        : Object.hash(h2, h1);
120 121
    }

122
    // Sort key hash codes and feed to Object.hashAll to ensure the aggregate
123 124 125 126 127 128 129 130 131 132 133 134 135
    // hash code does not depend on the key order.
    final List<int> sortedHashes = length == 3
      ? _tempHashStore3
      : _tempHashStore4;
    sortedHashes[0] = h1;
    sortedHashes[1] = h2;
    iterator.moveNext();
    sortedHashes[2] = iterator.current.hashCode;
    if (length == 4) {
      iterator.moveNext();
      sortedHashes[3] = iterator.current.hashCode;
    }
    sortedHashes.sort();
136
    return Object.hashAll(sortedHashes);
137 138 139
  }
}

Tong Mu's avatar
Tong Mu committed
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
/// An interface to define the keyboard key combination to trigger a shortcut.
///
/// [ShortcutActivator]s are used by [Shortcuts] widgets, and are mapped to
/// [Intent]s, the intended behavior that the key combination should trigger.
/// When a [Shortcuts] widget receives a key event, its [ShortcutManager] looks
/// up the first matching [ShortcutActivator], and signals the corresponding
/// [Intent], which might trigger an action as defined by a hierarchy of
/// [Actions] widgets. For a detailed introduction on the mechanism and use of
/// the shortcut-action system, see [Actions].
///
/// The matching [ShortcutActivator] is looked up in the following way:
///
///  * Find the registered [ShortcutActivator]s whose [triggers] contain the
///    incoming event.
///  * Of the previous list, finds the first activator whose [accepts] returns
///    true in the order of insertion.
///
/// See also:
///
///  * [SingleActivator], an implementation that represents a single key combined
///    with modifiers (control, shift, alt, meta).
Tong Mu's avatar
Tong Mu committed
161 162
///  * [CharacterActivator], an implementation that represents key combinations
///    that result in the specified character, such as question mark.
Tong Mu's avatar
Tong Mu committed
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
///  * [LogicalKeySet], an implementation that requires one or more
///    [LogicalKeyboardKey]s to be pressed at the same time. Prefer
///    [SingleActivator] when possible.
abstract class ShortcutActivator {
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
  const ShortcutActivator();

  /// All the keys that might be the final event to trigger this shortcut.
  ///
  /// For example, for `Ctrl-A`, the KeyA is the only trigger, while Ctrl is not,
  /// because the shortcut should only work by pressing KeyA *after* Ctrl, but
  /// not before. For `Ctrl-A-E`, on the other hand, both KeyA and KeyE should be
  /// triggers, since either of them is allowed to trigger.
  ///
  /// The trigger keys are used as the first-pass filter for incoming events, as
  /// [Intent]s are stored in a [Map] and indexed by trigger keys. Subclasses
  /// should make sure that the return value of this method does not change
  /// throughout the lifespan of this object.
Tong Mu's avatar
Tong Mu committed
182 183 184 185 186 187 188
  ///
  /// This method might also return null, which means this activator declares
  /// all keys as the trigger key. All activators whose [triggers] returns null
  /// will be tested with [accepts] on every event. Since this becomes a
  /// linear search, and having too many might impact performance, it is
  /// preferred to return non-null [triggers] whenever possible.
  Iterable<LogicalKeyboardKey>? get triggers;
Tong Mu's avatar
Tong Mu committed
189 190 191 192 193 194

  /// Whether the triggering `event` and the keyboard `state` at the time of the
  /// event meet required conditions, providing that the event is a triggering
  /// event.
  ///
  /// For example, for `Ctrl-A`, it has to check if the event is a
195
  /// [KeyDownEvent], if either side of the Ctrl key is pressed, and none of
Tong Mu's avatar
Tong Mu committed
196 197 198 199
  /// the Shift keys, Alt keys, or Meta keys are pressed; it doesn't have to
  /// check if KeyA is pressed, since it's already guaranteed.
  ///
  /// This method must not cause any side effects for the `state`. Typically
200 201
  /// this is only used to query whether [HardwareKeyboard.logicalKeysPressed]
  /// contains a key.
Tong Mu's avatar
Tong Mu committed
202
  ///
Tong Mu's avatar
Tong Mu committed
203 204 205
  /// Since [ShortcutActivator] accepts all event types, subclasses might want
  /// to check the event type in [accepts].
  ///
Tong Mu's avatar
Tong Mu committed
206 207 208 209 210 211
  /// See also:
  ///
  ///  * [LogicalKeyboardKey.collapseSynonyms], which helps deciding whether a
  ///    modifier key is pressed when the side variation is not important.
  bool accepts(RawKeyEvent event, RawKeyboard state);

212 213 214 215 216 217 218 219 220 221
  /// Returns true if the event and keyboard state would cause this
  /// [ShortcutActivator] to be activated.
  ///
  /// If the keyboard `state` isn't supplied, then it defaults to using
  /// [RawKeyboard.instance].
  static bool isActivatedBy(ShortcutActivator activator, RawKeyEvent event) {
    return (activator.triggers?.contains(event.logicalKey) ?? true)
        && activator.accepts(event, RawKeyboard.instance);
  }

Tong Mu's avatar
Tong Mu committed
222 223 224 225 226 227
  /// Returns a description of the key set that is short and readable.
  ///
  /// Intended to be used in debug mode for logging purposes.
  String debugDescribeKeys();
}

228 229
/// A set of [LogicalKeyboardKey]s that can be used as the keys in a map.
///
Tong Mu's avatar
Tong Mu committed
230 231 232 233
/// [LogicalKeySet] can be used as a [ShortcutActivator]. It is not recommended
/// to use [LogicalKeySet] for a common shortcut such as `Delete` or `Ctrl+C`,
/// prefer [SingleActivator] when possible, whose behavior more closely resembles
/// that of typical platforms.
234
///
Tong Mu's avatar
Tong Mu committed
235 236 237 238
/// When used as a [ShortcutActivator], [LogicalKeySet] will activate the intent
/// when all [keys] are pressed, and no others, except that modifier keys are
/// considered without considering sides (e.g. control left and control right are
/// considered the same).
239
///
240
/// {@tool dartpad}
Tong Mu's avatar
Tong Mu committed
241 242 243 244 245 246 247 248 249 250 251
/// In the following example, the counter is increased when the following key
/// sequences are pressed:
///
///  * Control left, then C.
///  * Control right, then C.
///  * C, then Control left.
///
/// But not when:
///
///  * Control left, then A, then C.
///
252
/// ** See code in examples/api/lib/widgets/shortcuts/logical_key_set.0.dart **
Tong Mu's avatar
Tong Mu committed
253 254 255 256 257 258 259 260
/// {@end-tool}
///
/// This is also a thin wrapper around a [Set], but changes the equality
/// comparison from an identity comparison to a contents comparison so that
/// non-identical sets with the same keys in them will compare as equal.

class LogicalKeySet extends KeySet<LogicalKeyboardKey> with Diagnosticable
    implements ShortcutActivator {
261 262 263 264
  /// A constructor for making a [LogicalKeySet] of up to four keys.
  ///
  /// If you need a set of more than four keys, use [LogicalKeySet.fromSet].
  ///
Tong Mu's avatar
Tong Mu committed
265
  /// The same [LogicalKeyboardKey] may not be appear more than once in the set.
266
  LogicalKeySet(
267 268 269 270 271
    super.key1, [
    super.key2,
    super.key3,
    super.key4,
  ]);
272

273
  /// Create a [LogicalKeySet] from a set of [LogicalKeyboardKey]s.
274 275
  ///
  /// Do not mutate the `keys` set after passing it to this object.
276
  LogicalKeySet.fromSet(super.keys) : super.fromSet();
277

Tong Mu's avatar
Tong Mu committed
278 279 280
  @override
  Iterable<LogicalKeyboardKey> get triggers => _triggers;
  late final Set<LogicalKeyboardKey> _triggers = keys.expand(
281 282
    (LogicalKeyboardKey key) => _unmapSynonyms[key] ?? <LogicalKeyboardKey>[key],
  ).toSet();
Tong Mu's avatar
Tong Mu committed
283 284 285

  @override
  bool accepts(RawKeyEvent event, RawKeyboard state) {
286
    if (event is! RawKeyDownEvent) {
287
      return false;
288
    }
Tong Mu's avatar
Tong Mu committed
289 290 291 292
    final Set<LogicalKeyboardKey> collapsedRequired = LogicalKeyboardKey.collapseSynonyms(keys);
    final Set<LogicalKeyboardKey> collapsedPressed = LogicalKeyboardKey.collapseSynonyms(state.keysPressed);
    final bool keysEqual = collapsedRequired.difference(collapsedPressed).isEmpty
      && collapsedRequired.length == collapsedPressed.length;
293
    return keysEqual;
Tong Mu's avatar
Tong Mu committed
294 295
  }

296 297 298 299 300 301
  static final Set<LogicalKeyboardKey> _modifiers = <LogicalKeyboardKey>{
    LogicalKeyboardKey.alt,
    LogicalKeyboardKey.control,
    LogicalKeyboardKey.meta,
    LogicalKeyboardKey.shift,
  };
Tong Mu's avatar
Tong Mu committed
302 303 304 305 306 307
  static final Map<LogicalKeyboardKey, List<LogicalKeyboardKey>> _unmapSynonyms = <LogicalKeyboardKey, List<LogicalKeyboardKey>>{
    LogicalKeyboardKey.control: <LogicalKeyboardKey>[LogicalKeyboardKey.controlLeft, LogicalKeyboardKey.controlRight],
    LogicalKeyboardKey.shift: <LogicalKeyboardKey>[LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.shiftRight],
    LogicalKeyboardKey.alt: <LogicalKeyboardKey>[LogicalKeyboardKey.altLeft, LogicalKeyboardKey.altRight],
    LogicalKeyboardKey.meta: <LogicalKeyboardKey>[LogicalKeyboardKey.metaLeft, LogicalKeyboardKey.metaRight],
  };
308

Tong Mu's avatar
Tong Mu committed
309
  @override
310
  String debugDescribeKeys() {
311 312
    final List<LogicalKeyboardKey> sortedKeys = keys.toList()
      ..sort((LogicalKeyboardKey a, LogicalKeyboardKey b) {
313 314 315 316 317 318 319 320 321
          // Put the modifiers first. If it has a synonym, then it's something
          // like shiftLeft, altRight, etc.
          final bool aIsModifier = a.synonyms.isNotEmpty || _modifiers.contains(a);
          final bool bIsModifier = b.synonyms.isNotEmpty || _modifiers.contains(b);
          if (aIsModifier && !bIsModifier) {
            return -1;
          } else if (bIsModifier && !aIsModifier) {
            return 1;
          }
322
          return a.debugName!.compareTo(b.debugName!);
323
        });
324
    return sortedKeys.map<String>((LogicalKeyboardKey key) => key.debugName.toString()).join(' + ');
325 326 327 328 329 330 331 332 333
  }

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(DiagnosticsProperty<Set<LogicalKeyboardKey>>('keys', _keys, description: debugDescribeKeys()));
  }
}

334 335
/// A [DiagnosticsProperty] which handles formatting a `Map<LogicalKeySet, Intent>`
/// (the same type as the [Shortcuts.shortcuts] property) so that its
336
/// diagnostic output is human-readable.
Tong Mu's avatar
Tong Mu committed
337
class ShortcutMapProperty extends DiagnosticsProperty<Map<ShortcutActivator, Intent>> {
338
  /// Create a diagnostics property for `Map<ShortcutActivator, Intent>` objects,
339 340
  /// which are the same type as the [Shortcuts.shortcuts] property.
  ShortcutMapProperty(
341 342 343 344 345 346
    String super.name,
    Map<ShortcutActivator, Intent> super.value, {
    super.showName,
    Object super.defaultValue,
    super.level,
    super.description,
347
  });
348 349

  @override
Tong Mu's avatar
Tong Mu committed
350
  Map<ShortcutActivator, Intent> get value => super.value!;
351 352

  @override
Tong Mu's avatar
Tong Mu committed
353 354 355 356 357 358 359
  String valueToString({TextTreeConfiguration? parentConfiguration}) {
    return '{${value.keys.map<String>((ShortcutActivator keySet) => '{${keySet.debugDescribeKeys()}}: ${value[keySet]}').join(', ')}}';
  }
}

/// A shortcut key combination of a single key and modifiers.
///
Tong Mu's avatar
Tong Mu committed
360
/// The [SingleActivator] implements typical shortcuts such as:
Tong Mu's avatar
Tong Mu committed
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
///
///  * ArrowLeft
///  * Shift + Delete
///  * Control + Alt + Meta + Shift + A
///
/// More specifically, it creates shortcut key combinations that are composed of a
/// [trigger] key, and zero, some, or all of the four modifiers (control, shift,
/// alt, meta). The shortcut is activated when the following conditions are met:
///
///  * The incoming event is a down event for a [trigger] key.
///  * If [control] is true, then at least one control key must be held.
///    Otherwise, no control keys must be held.
///  * Similar conditions apply for the [alt], [shift], and [meta] keys.
///
/// This resembles the typical behavior of most operating systems, and handles
/// modifier keys differently from [LogicalKeySet] in the following way:
///
///  * [SingleActivator]s allow additional non-modifier keys being pressed in
///    order to activate the shortcut. For example, pressing key X while holding
///    ControlLeft *and key A* will be accepted by
///    `SingleActivator(LogicalKeyboardKey.keyX, control: true)`.
///  * [SingleActivator]s do not consider modifiers to be a trigger key. For
///    example, pressing ControlLeft while holding key X *will not* activate a
///    `SingleActivator(LogicalKeyboardKey.keyX, control: true)`.
Tong Mu's avatar
Tong Mu committed
385 386 387 388 389
///
/// See also:
///
///  * [CharacterActivator], an activator that represents key combinations
///    that result in the specified character, such as question mark.
390
class SingleActivator with Diagnosticable, MenuSerializableShortcut implements ShortcutActivator {
391
  /// Triggered when the [trigger] key is pressed while the modifiers are held.
Tong Mu's avatar
Tong Mu committed
392
  ///
393
  /// The [trigger] should be the non-modifier key that is pressed after all the
Tong Mu's avatar
Tong Mu committed
394 395 396
  /// modifiers, such as [LogicalKeyboardKey.keyC] as in `Ctrl+C`. It must not be
  /// a modifier key (sided or unsided).
  ///
397 398 399
  /// The [control], [shift], [alt], and [meta] flags represent whether
  /// the respect modifier keys should be held (true) or released (false).
  /// They default to false.
Tong Mu's avatar
Tong Mu committed
400
  ///
401 402 403
  /// By default, the activator is checked on all [RawKeyDownEvent] events for
  /// the [trigger] key. If `includeRepeats` is false, only the [trigger] key
  /// events with a false [RawKeyDownEvent.repeat] attribute will be considered.
404
  ///
405
  /// {@tool dartpad}
Tong Mu's avatar
Tong Mu committed
406 407
  /// In the following example, the shortcut `Control + C` increases the counter:
  ///
408
  /// ** See code in examples/api/lib/widgets/shortcuts/single_activator.single_activator.0.dart **
Tong Mu's avatar
Tong Mu committed
409 410 411 412 413 414 415
  /// {@end-tool}
  const SingleActivator(
    this.trigger, {
    this.control = false,
    this.shift = false,
    this.alt = false,
    this.meta = false,
416
    this.includeRepeats = true,
Tong Mu's avatar
Tong Mu committed
417 418
  }) : // The enumerated check with `identical` is cumbersome but the only way
       // since const constructors can not call functions such as `==` or
Tong Mu's avatar
Tong Mu committed
419 420
       // `Set.contains`. Checking with `identical` might not work when the
       // key object is created from ID, but it covers common cases.
421 422
       assert(
         !identical(trigger, LogicalKeyboardKey.control) &&
Tong Mu's avatar
Tong Mu committed
423 424 425 426 427 428 429 430 431 432 433
         !identical(trigger, LogicalKeyboardKey.controlLeft) &&
         !identical(trigger, LogicalKeyboardKey.controlRight) &&
         !identical(trigger, LogicalKeyboardKey.shift) &&
         !identical(trigger, LogicalKeyboardKey.shiftLeft) &&
         !identical(trigger, LogicalKeyboardKey.shiftRight) &&
         !identical(trigger, LogicalKeyboardKey.alt) &&
         !identical(trigger, LogicalKeyboardKey.altLeft) &&
         !identical(trigger, LogicalKeyboardKey.altRight) &&
         !identical(trigger, LogicalKeyboardKey.meta) &&
         !identical(trigger, LogicalKeyboardKey.metaLeft) &&
         !identical(trigger, LogicalKeyboardKey.metaRight),
434
       );
Tong Mu's avatar
Tong Mu committed
435 436 437 438 439 440 441 442 443 444 445

  /// The non-modifier key of the shortcut that is pressed after all modifiers
  /// to activate the shortcut.
  ///
  /// For example, for `Control + C`, [trigger] should be
  /// [LogicalKeyboardKey.keyC].
  final LogicalKeyboardKey trigger;

  /// Whether either (or both) control keys should be held for [trigger] to
  /// activate the shortcut.
  ///
446 447 448
  /// It defaults to false, meaning all Control keys must be released when the
  /// event is received in order to activate the shortcut. If it's true, then
  /// either or both Control keys must be pressed.
Tong Mu's avatar
Tong Mu committed
449 450 451 452 453 454 455 456 457
  ///
  /// See also:
  ///
  ///  * [LogicalKeyboardKey.controlLeft], [LogicalKeyboardKey.controlRight].
  final bool control;

  /// Whether either (or both) shift keys should be held for [trigger] to
  /// activate the shortcut.
  ///
458 459 460
  /// It defaults to false, meaning all Shift keys must be released when the
  /// event is received in order to activate the shortcut. If it's true, then
  /// either or both Shift keys must be pressed.
Tong Mu's avatar
Tong Mu committed
461 462 463 464 465 466 467 468 469
  ///
  /// See also:
  ///
  ///  * [LogicalKeyboardKey.shiftLeft], [LogicalKeyboardKey.shiftRight].
  final bool shift;

  /// Whether either (or both) alt keys should be held for [trigger] to
  /// activate the shortcut.
  ///
470 471 472
  /// It defaults to false, meaning all Alt keys must be released when the
  /// event is received in order to activate the shortcut. If it's true, then
  /// either or both Alt keys must be pressed.
Tong Mu's avatar
Tong Mu committed
473 474 475 476 477 478 479 480 481
  ///
  /// See also:
  ///
  ///  * [LogicalKeyboardKey.altLeft], [LogicalKeyboardKey.altRight].
  final bool alt;

  /// Whether either (or both) meta keys should be held for [trigger] to
  /// activate the shortcut.
  ///
482 483 484
  /// It defaults to false, meaning all Meta keys must be released when the
  /// event is received in order to activate the shortcut. If it's true, then
  /// either or both Meta keys must be pressed.
Tong Mu's avatar
Tong Mu committed
485 486 487 488 489 490
  ///
  /// See also:
  ///
  ///  * [LogicalKeyboardKey.metaLeft], [LogicalKeyboardKey.metaRight].
  final bool meta;

491 492 493
  /// Whether this activator accepts repeat events of the [trigger] key.
  ///
  /// If [includeRepeats] is true, the activator is checked on all
494 495
  /// [RawKeyDownEvent] events for the [trigger] key. If [includeRepeats] is
  /// false, only [trigger] key events with a false [RawKeyDownEvent.repeat]
496 497 498
  /// attribute will be considered.
  final bool includeRepeats;

Tong Mu's avatar
Tong Mu committed
499
  @override
500 501
  Iterable<LogicalKeyboardKey> get triggers {
    return <LogicalKeyboardKey>[trigger];
Tong Mu's avatar
Tong Mu committed
502 503 504 505 506 507
  }

  @override
  bool accepts(RawKeyEvent event, RawKeyboard state) {
    final Set<LogicalKeyboardKey> pressed = state.keysPressed;
    return event is RawKeyDownEvent
508
      && (includeRepeats || !event.repeat)
Tong Mu's avatar
Tong Mu committed
509 510 511 512 513 514
      && (control == (pressed.contains(LogicalKeyboardKey.controlLeft) || pressed.contains(LogicalKeyboardKey.controlRight)))
      && (shift == (pressed.contains(LogicalKeyboardKey.shiftLeft) || pressed.contains(LogicalKeyboardKey.shiftRight)))
      && (alt == (pressed.contains(LogicalKeyboardKey.altLeft) || pressed.contains(LogicalKeyboardKey.altRight)))
      && (meta == (pressed.contains(LogicalKeyboardKey.metaLeft) || pressed.contains(LogicalKeyboardKey.metaRight)));
  }

515 516 517 518 519 520 521 522 523 524 525
  @override
  ShortcutSerialization serializeForMenu() {
    return ShortcutSerialization.modifier(
      trigger,
      shift: shift,
      alt: alt,
      meta: meta,
      control: control,
    );
  }

Tong Mu's avatar
Tong Mu committed
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
  /// Returns a short and readable description of the key combination.
  ///
  /// Intended to be used in debug mode for logging purposes. In release mode,
  /// [debugDescribeKeys] returns an empty string.
  @override
  String debugDescribeKeys() {
    String result = '';
    assert(() {
      final List<String> keys = <String>[
        if (control) 'Control',
        if (alt) 'Alt',
        if (meta) 'Meta',
        if (shift) 'Shift',
        trigger.debugName ?? trigger.toStringShort(),
      ];
      result = keys.join(' + ');
      return true;
    }());
    return result;
  }

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
550
    properties.add(MessageProperty('keys', debugDescribeKeys()));
551
    properties.add(FlagProperty('includeRepeats', value: includeRepeats, ifFalse: 'excluding repeats'));
Tong Mu's avatar
Tong Mu committed
552 553 554
  }
}

Tong Mu's avatar
Tong Mu committed
555 556 557 558 559 560
/// A shortcut combination that is triggered by a key event that produces a
/// specific character.
///
/// Keys often produce different characters when combined with modifiers. For
/// example, it might be helpful for the user to bring up a help menu by
/// pressing the question mark ('?'). However, there is no logical key that
561
/// directly represents a question mark. Although 'Shift+Slash' produces a '?'
Tong Mu's avatar
Tong Mu committed
562 563 564 565 566 567 568 569
/// character on a US keyboard, its logical key is still considered a Slash key,
/// and hard-coding 'Shift+Slash' in this situation is unfriendly to other
/// keyboard layouts.
///
/// For example, `CharacterActivator('?')` is triggered when a key combination
/// results in a question mark, which is 'Shift+Slash' on a US keyboard, but
/// 'Shift+Comma' on a French keyboard.
///
570
/// {@tool dartpad}
Tong Mu's avatar
Tong Mu committed
571 572 573
/// In the following example, when a key combination results in a question mark,
/// the counter is increased:
///
574
/// ** See code in examples/api/lib/widgets/shortcuts/character_activator.0.dart **
Tong Mu's avatar
Tong Mu committed
575 576
/// {@end-tool}
///
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
/// The [alt], [control], and [meta] flags represent whether the respective
/// modifier keys should be held (true) or released (false). They default to
/// false. [CharacterActivator] cannot check shifted keys, since the Shift key
/// affects the resulting character, and will accept whether either of the
/// Shift keys are pressed or not, as long as the key event produces the
/// correct character.
///
/// By default, the activator is checked on all [RawKeyDownEvent] events for
/// the [character] in combination with the requested modifier keys. If
/// `includeRepeats` is false, only the [character] events with a false
/// [RawKeyDownEvent.repeat] attribute will be considered.
///
/// {@template flutter.widgets.shortcuts.CharacterActivator.alt}
/// On macOS and iOS, the [alt] flag indicates that the Option key (⌥) is
/// pressed. Because the Option key affects the character generated on these
/// platforms, it can be unintuitive to define [CharacterActivator]s for them.
///
/// For instance, if you want the shortcut to trigger when Option+s (⌥-s) is
/// pressed, and what you intend is to trigger whenever the character 'ß' is
/// produced, you would use `CharacterActivator('ß')` or
/// `CharacterActivator('ß', alt: true)` instead of `CharacterActivator('s',
/// alt: true)`. This is because `CharacterActivator('s', alt: true)` will
/// never trigger, since the 's' character can't be produced when the Option
/// key is held down.
///
/// If what is intended is that the shortcut is triggered when Option+s (⌥-s)
/// is pressed, regardless of which character is produced, it is better to use
/// [SingleActivator], as in `SingleActivator(LogicalKeyboardKey.keyS, alt:
/// true)`.
/// {@endtemplate}
///
Tong Mu's avatar
Tong Mu committed
608 609 610
/// See also:
///
///  * [SingleActivator], an activator that represents a single key combined
611
///    with modifiers, such as `Ctrl+C` or `Ctrl-Right Arrow`.
612
class CharacterActivator with Diagnosticable, MenuSerializableShortcut implements ShortcutActivator {
613 614
  /// Triggered when the key event yields the given character.
  const CharacterActivator(this.character, {
615
    this.alt = false,
616 617 618 619 620
    this.control = false,
    this.meta = false,
    this.includeRepeats = true,
  });

621
  /// Whether either (or both) Alt keys should be held for the [character] to
622 623 624 625
  /// activate the shortcut.
  ///
  /// It defaults to false, meaning all Alt keys must be released when the event
  /// is received in order to activate the shortcut. If it's true, then either
626 627 628 629
  /// one or both Alt keys must be pressed.
  ///
  /// {@macro flutter.widgets.shortcuts.CharacterActivator.alt}
  ///
630 631 632 633 634
  /// See also:
  ///
  /// * [LogicalKeyboardKey.altLeft], [LogicalKeyboardKey.altRight].
  final bool alt;

635
  /// Whether either (or both) Control keys should be held for the [character]
636 637 638 639
  /// to activate the shortcut.
  ///
  /// It defaults to false, meaning all Control keys must be released when the
  /// event is received in order to activate the shortcut. If it's true, then
640
  /// either one or both Control keys must be pressed.
641 642 643 644 645 646
  ///
  /// See also:
  ///
  ///  * [LogicalKeyboardKey.controlLeft], [LogicalKeyboardKey.controlRight].
  final bool control;

647
  /// Whether either (or both) Meta keys should be held for the [character] to
648 649 650 651
  /// activate the shortcut.
  ///
  /// It defaults to false, meaning all Meta keys must be released when the
  /// event is received in order to activate the shortcut. If it's true, then
652
  /// either one or both Meta keys must be pressed.
653 654 655 656 657 658 659 660 661
  ///
  /// See also:
  ///
  ///  * [LogicalKeyboardKey.metaLeft], [LogicalKeyboardKey.metaRight].
  final bool meta;

  /// Whether this activator accepts repeat events of the [character].
  ///
  /// If [includeRepeats] is true, the activator is checked on all
662
  /// [RawKeyDownEvent] events for the [character]. If [includeRepeats] is
663 664 665
  /// false, only the [character] events with a false [RawKeyDownEvent.repeat]
  /// attribute will be considered.
  final bool includeRepeats;
Tong Mu's avatar
Tong Mu committed
666

667
  /// The character which triggers the shortcut.
Tong Mu's avatar
Tong Mu committed
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
  ///
  /// This is typically a single-character string, such as '?' or 'œ', although
  /// [CharacterActivator] doesn't check the length of [character] or whether it
  /// can be matched by any key combination at all. It is case-sensitive, since
  /// the [character] is directly compared by `==` to the character reported by
  /// the platform.
  ///
  /// See also:
  ///
  ///  * [RawKeyEvent.character], the character of a key event.
  final String character;

  @override
  Iterable<LogicalKeyboardKey>? get triggers => null;

  @override
  bool accepts(RawKeyEvent event, RawKeyboard state) {
685
    final Set<LogicalKeyboardKey> pressed = state.keysPressed;
Tong Mu's avatar
Tong Mu committed
686
    return event is RawKeyDownEvent
687 688
      && event.character == character
      && (includeRepeats || !event.repeat)
689
      && (alt == (pressed.contains(LogicalKeyboardKey.altLeft) || pressed.contains(LogicalKeyboardKey.altRight)))
690 691
      && (control == (pressed.contains(LogicalKeyboardKey.controlLeft) || pressed.contains(LogicalKeyboardKey.controlRight)))
      && (meta == (pressed.contains(LogicalKeyboardKey.metaLeft) || pressed.contains(LogicalKeyboardKey.metaRight)));
Tong Mu's avatar
Tong Mu committed
692 693 694 695 696 697
  }

  @override
  String debugDescribeKeys() {
    String result = '';
    assert(() {
698
      final List<String> keys = <String>[
699
        if (alt) 'Alt',
700 701 702 703 704
        if (control) 'Control',
        if (meta) 'Meta',
        "'$character'",
      ];
      result = keys.join(' + ');
Tong Mu's avatar
Tong Mu committed
705 706 707 708 709
      return true;
    }());
    return result;
  }

710 711
  @override
  ShortcutSerialization serializeForMenu() {
712
    return ShortcutSerialization.character(character, alt: alt, control: control, meta: meta);
713 714
  }

Tong Mu's avatar
Tong Mu committed
715 716 717
  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
718 719
    properties.add(MessageProperty('character', debugDescribeKeys()));
    properties.add(FlagProperty('includeRepeats', value: includeRepeats, ifFalse: 'excluding repeats'));
Tong Mu's avatar
Tong Mu committed
720 721 722
  }
}

Tong Mu's avatar
Tong Mu committed
723 724 725 726 727 728 729 730 731 732
class _ActivatorIntentPair with Diagnosticable {
  const _ActivatorIntentPair(this.activator, this.intent);
  final ShortcutActivator activator;
  final Intent intent;

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(DiagnosticsProperty<String>('activator', activator.debugDescribeKeys()));
    properties.add(DiagnosticsProperty<Intent>('intent', intent));
733
  }
734 735
}

736 737
/// A manager of keyboard shortcut bindings used by [Shortcuts] to handle key
/// events.
738 739 740
///
/// The manager may be listened to (with [addListener]/[removeListener]) for
/// change notifications when the shortcuts change.
741 742 743 744
///
/// Typically, a [Shortcuts] widget supplies its own manager, but in uncommon
/// cases where overriding the usual shortcut manager behavior is desired, a
/// subclassed [ShortcutManager] may be supplied.
745
class ShortcutManager with Diagnosticable, ChangeNotifier {
746 747
  /// Constructs a [ShortcutManager].
  ShortcutManager({
Tong Mu's avatar
Tong Mu committed
748
    Map<ShortcutActivator, Intent> shortcuts = const <ShortcutActivator, Intent>{},
749
    this.modal = false,
750 751 752 753 754
  })  : _shortcuts = shortcuts {
    if (kFlutterMemoryAllocationsEnabled) {
      maybeDispatchObjectCreation();
    }
  }
755 756 757 758

  /// True if the [ShortcutManager] should not pass on keys that it doesn't
  /// handle to any key-handling widgets that are ancestors to this one.
  ///
759 760 761 762
  /// Setting [modal] to true will prevent any key event given to this manager
  /// from being given to any ancestor managers, even if that key doesn't appear
  /// in the [shortcuts] map.
  ///
763
  /// The net effect of setting [modal] to true is to return
764 765 766
  /// [KeyEventResult.skipRemainingHandlers] from [handleKeypress] if it does
  /// not exist in the shortcut map, instead of returning
  /// [KeyEventResult.ignored].
767 768 769 770 771 772
  final bool modal;

  /// Returns the shortcut map.
  ///
  /// When the map is changed, listeners to this manager will be notified.
  ///
773
  /// The returned map should not be modified.
Tong Mu's avatar
Tong Mu committed
774 775 776 777
  Map<ShortcutActivator, Intent> get shortcuts => _shortcuts;
  Map<ShortcutActivator, Intent> _shortcuts = <ShortcutActivator, Intent>{};
  set shortcuts(Map<ShortcutActivator, Intent> value) {
    if (!mapEquals<ShortcutActivator, Intent>(_shortcuts, value)) {
778
      _shortcuts = value;
Tong Mu's avatar
Tong Mu committed
779
      _indexedShortcutsCache = null;
780 781 782 783
      notifyListeners();
    }
  }

Tong Mu's avatar
Tong Mu committed
784 785
  static Map<LogicalKeyboardKey?, List<_ActivatorIntentPair>> _indexShortcuts(Map<ShortcutActivator, Intent> source) {
    final Map<LogicalKeyboardKey?, List<_ActivatorIntentPair>> result = <LogicalKeyboardKey?, List<_ActivatorIntentPair>>{};
Tong Mu's avatar
Tong Mu committed
786
    source.forEach((ShortcutActivator activator, Intent intent) {
Tong Mu's avatar
Tong Mu committed
787 788 789
      // This intermediate variable is necessary to comply with Dart analyzer.
      final Iterable<LogicalKeyboardKey?>? nullableTriggers = activator.triggers;
      for (final LogicalKeyboardKey? trigger in nullableTriggers ?? <LogicalKeyboardKey?>[null]) {
Tong Mu's avatar
Tong Mu committed
790 791 792 793 794 795
        result.putIfAbsent(trigger, () => <_ActivatorIntentPair>[])
          .add(_ActivatorIntentPair(activator, intent));
      }
    });
    return result;
  }
796

Tong Mu's avatar
Tong Mu committed
797
  Map<LogicalKeyboardKey?, List<_ActivatorIntentPair>> get _indexedShortcuts {
798
    return _indexedShortcutsCache ??= _indexShortcuts(shortcuts);
Tong Mu's avatar
Tong Mu committed
799
  }
800

Tong Mu's avatar
Tong Mu committed
801
  Map<LogicalKeyboardKey?, List<_ActivatorIntentPair>>? _indexedShortcutsCache;
Tong Mu's avatar
Tong Mu committed
802

803 804
  /// Returns the [Intent], if any, that matches the current set of pressed
  /// keys.
805
  ///
806 807
  /// Returns null if no intent matches the current set of pressed keys.
  ///
808 809
  /// Defaults to a set derived from [RawKeyboard.keysPressed] if `keysPressed`
  /// is not supplied.
Tong Mu's avatar
Tong Mu committed
810
  Intent? _find(RawKeyEvent event, RawKeyboard state) {
Tong Mu's avatar
Tong Mu committed
811 812 813 814 815 816
    final List<_ActivatorIntentPair>? candidatesByKey = _indexedShortcuts[event.logicalKey];
    final List<_ActivatorIntentPair>? candidatesByNull = _indexedShortcuts[null];
    final List<_ActivatorIntentPair> candidates = <_ActivatorIntentPair>[
      if (candidatesByKey != null) ...candidatesByKey,
      if (candidatesByNull != null) ...candidatesByNull,
    ];
Tong Mu's avatar
Tong Mu committed
817 818 819
    for (final _ActivatorIntentPair activatorIntent in candidates) {
      if (activatorIntent.activator.accepts(event, state)) {
        return activatorIntent.intent;
820 821
      }
    }
Tong Mu's avatar
Tong Mu committed
822
    return null;
823 824 825 826
  }

  /// Handles a key press `event` in the given `context`.
  ///
Tong Mu's avatar
Tong Mu committed
827 828 829 830
  /// If a key mapping is found, then the associated action will be invoked using
  /// the [Intent] activated by the [ShortcutActivator] in the [shortcuts] map,
  /// and the currently focused widget's context (from
  /// [FocusManager.primaryFocus]).
831
  ///
832
  /// Returns a [KeyEventResult.handled] if an action was invoked, otherwise a
833 834 835
  /// [KeyEventResult.skipRemainingHandlers] if [modal] is true, or if it maps
  /// to a [DoNothingAction] with [DoNothingAction.consumesKey] set to false,
  /// and in all other cases returns [KeyEventResult.ignored].
836 837 838 839
  ///
  /// In order for an action to be invoked (and [KeyEventResult.handled]
  /// returned), a pressed [KeySet] must be mapped to an [Intent], the [Intent]
  /// must be mapped to an [Action], and the [Action] must be enabled.
840
  @protected
Tong Mu's avatar
Tong Mu committed
841 842
  KeyEventResult handleKeypress(BuildContext context, RawKeyEvent event) {
    final Intent? matchedIntent = _find(event, RawKeyboard.instance);
843
    if (matchedIntent != null) {
844 845 846 847 848 849
      final BuildContext? primaryContext = primaryFocus?.context;
      if (primaryContext != null) {
        final Action<Intent>? action = Actions.maybeFind<Intent>(
          primaryContext,
          intent: matchedIntent,
        );
850 851 852 853 854 855 856
        if (action != null) {
          final (bool enabled, Object? invokeResult) = Actions.of(primaryContext).invokeActionIfEnabled(
            action, matchedIntent, primaryContext,
          );
          if (enabled) {
            return action.toKeyEventResult(matchedIntent, invokeResult);
          }
857
        }
858
      }
859
    }
860
    return modal ? KeyEventResult.skipRemainingHandlers : KeyEventResult.ignored;
861 862 863 864 865
  }

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
866
    properties.add(DiagnosticsProperty<Map<ShortcutActivator, Intent>>('shortcuts', shortcuts));
867 868 869 870
    properties.add(FlagProperty('modal', value: modal, ifTrue: 'modal', defaultValue: false));
  }
}

871
/// A widget that creates key bindings to specific actions for its
872 873
/// descendants.
///
874 875
/// {@youtube 560 315 https://www.youtube.com/watch?v=6ZcQmdoz9N8}
///
876
/// This widget establishes a [ShortcutManager] to be used by its descendants
877 878 879
/// when invoking an [Action] via a keyboard key combination that maps to an
/// [Intent].
///
880 881 882 883 884 885 886
/// This is similar to but more powerful than the [CallbackShortcuts] widget.
/// Unlike [CallbackShortcuts], this widget separates key bindings and their
/// implementations. This separation allows [Shortcuts] to have key bindings
/// that adapt to the focused context. For example, the desired action for a
/// deletion intent may be to delete a character in a text input, or to delete
/// a file in a file menu.
///
887 888 889 890
/// See the article on [Using Actions and
/// Shortcuts](https://docs.flutter.dev/development/ui/advanced/actions_and_shortcuts)
/// for a detailed explanation.
///
891
/// {@tool dartpad}
892 893 894 895 896 897 898
/// Here, we will use the [Shortcuts] and [Actions] widgets to add and subtract
/// from a counter. When the child widget has keyboard focus, and a user presses
/// the keys that have been defined in [Shortcuts], the action that is bound
/// to the appropriate [Intent] for the key is invoked.
///
/// It also shows the use of a [CallbackAction] to avoid creating a new [Action]
/// subclass.
899
///
900
/// ** See code in examples/api/lib/widgets/shortcuts/shortcuts.0.dart **
901 902
/// {@end-tool}
///
903
/// {@tool dartpad}
904 905 906 907 908 909 910 911 912 913 914 915
/// This slightly more complicated, but more flexible, example creates a custom
/// [Action] subclass to increment and decrement within a widget (a [Column])
/// that has keyboard focus. When the user presses the up and down arrow keys,
/// the counter will increment and decrement a data model using the custom
/// actions.
///
/// One thing that this demonstrates is passing arguments to the [Intent] to be
/// carried to the [Action]. This shows how actions can get data either from
/// their own construction (like the `model` in this example), or from the
/// intent passed to them when invoked (like the increment `amount` in this
/// example).
///
916
/// ** See code in examples/api/lib/widgets/shortcuts/shortcuts.1.dart **
917 918
/// {@end-tool}
///
919 920
/// See also:
///
921 922
///  * [CallbackShortcuts], a simpler but less flexible widget that defines key
///    bindings that invoke callbacks.
923 924 925
///  * [Intent], a class for containing a description of a user action to be
///    invoked.
///  * [Action], a class for defining an invocation of a user action.
926
///  * [CallbackAction], a class for creating an action from a callback.
927
class Shortcuts extends StatefulWidget {
928 929 930 931
  /// Creates a const [Shortcuts] widget that owns the map of shortcuts and
  /// creates its own manager.
  ///
  /// When using this constructor, [manager] will return null.
932
  ///
Tong Mu's avatar
Tong Mu committed
933
  /// The [child] and [shortcuts] arguments are required.
934 935 936 937 938
  ///
  /// See also:
  ///
  ///  * [Shortcuts.manager], a constructor that uses a [ShortcutManager] to
  ///    manage the shortcuts list instead.
939
  const Shortcuts({
940
    super.key,
941 942 943 944
    required Map<ShortcutActivator, Intent> shortcuts,
    required this.child,
    this.debugLabel,
  }) : _shortcuts = shortcuts,
945
       manager = null;
946 947 948 949 950 951 952 953 954 955 956

  /// Creates a const [Shortcuts] widget that uses the [manager] to
  /// manage the map of shortcuts.
  ///
  /// If this constructor is used, [shortcuts] will return the contents of
  /// [ShortcutManager.shortcuts].
  ///
  /// The [child] and [manager] arguments are required.
  const Shortcuts.manager({
    super.key,
    required ShortcutManager this.manager,
957
    required this.child,
958
    this.debugLabel,
959
  }) : _shortcuts = const <ShortcutActivator, Intent>{};
960 961 962 963

  /// The [ShortcutManager] that will manage the mapping between key
  /// combinations and [Action]s.
  ///
964 965 966
  /// If this widget was created with [Shortcuts.manager], then
  /// [ShortcutManager.shortcuts] will be used as the source for shortcuts. If
  /// the unnamed constructor is used, this manager will be null, and a
967
  /// default-constructed [ShortcutManager] will be used.
968
  final ShortcutManager? manager;
969

970
  /// {@template flutter.widgets.shortcuts.shortcuts}
971 972 973
  /// The map of shortcuts that describes the mapping between a key sequence
  /// defined by a [ShortcutActivator] and the [Intent] that will be emitted
  /// when that key sequence is pressed.
974
  /// {@endtemplate}
975 976 977 978
  Map<ShortcutActivator, Intent> get shortcuts {
    return manager == null ? _shortcuts : manager!.shortcuts;
  }
  final Map<ShortcutActivator, Intent> _shortcuts;
979 980 981

  /// The child widget for this [Shortcuts] widget.
  ///
982
  /// {@macro flutter.widgets.ProxyWidget.child}
983 984
  final Widget child;

985 986 987 988 989 990
  /// The debug label that is printed for this node when logged.
  ///
  /// If this label is set, then it will be displayed instead of the shortcut
  /// map when logged.
  ///
  /// This allows simplifying the diagnostic output to avoid cluttering it
991
  /// unnecessarily with large default shortcut maps.
992
  final String? debugLabel;
993

994
  @override
995
  State<Shortcuts> createState() => _ShortcutsState();
996 997 998 999

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
1000 1001
    properties.add(DiagnosticsProperty<ShortcutManager>('manager', manager, defaultValue: null));
    properties.add(ShortcutMapProperty('shortcuts', shortcuts, description: debugLabel?.isNotEmpty ?? false ? debugLabel : null));
1002 1003 1004 1005
  }
}

class _ShortcutsState extends State<Shortcuts> {
1006 1007
  ShortcutManager? _internalManager;
  ShortcutManager get manager => widget.manager ?? _internalManager!;
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019

  @override
  void dispose() {
    _internalManager?.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    if (widget.manager == null) {
      _internalManager = ShortcutManager();
1020
      _internalManager!.shortcuts = widget.shortcuts;
1021 1022 1023 1024 1025 1026
    }
  }

  @override
  void didUpdateWidget(Shortcuts oldWidget) {
    super.didUpdateWidget(oldWidget);
1027
    if (widget.manager != oldWidget.manager) {
1028 1029 1030 1031 1032 1033 1034
      if (widget.manager != null) {
        _internalManager?.dispose();
        _internalManager = null;
      } else {
        _internalManager ??= ShortcutManager();
      }
    }
1035
    _internalManager?.shortcuts = widget.shortcuts;
1036 1037
  }

1038
  KeyEventResult _handleOnKey(FocusNode node, RawKeyEvent event) {
1039
    if (node.context == null) {
1040
      return KeyEventResult.ignored;
1041
    }
1042
    return manager.handleKeypress(node.context!, event);
1043 1044 1045 1046 1047
  }

  @override
  Widget build(BuildContext context) {
    return Focus(
1048
      debugLabel: '$Shortcuts',
1049
      canRequestFocus: false,
1050
      onKey: _handleOnKey,
1051
      child: widget.child,
1052 1053 1054 1055
    );
  }
}

1056
/// A widget that binds key combinations to specific callbacks.
1057
///
1058 1059
/// {@youtube 560 315 https://www.youtube.com/watch?v=VcQQ1ns_qNY}
///
1060 1061 1062
/// This is similar to but simpler than the [Shortcuts] widget as it doesn't
/// require [Intent]s and [Actions] widgets. Instead, it accepts a map
/// of [ShortcutActivator]s to [VoidCallback]s.
1063
///
1064 1065 1066 1067 1068
/// Unlike [Shortcuts], this widget does not separate key bindings and their
/// implementations. This separation allows [Shortcuts] to have key bindings
/// that adapt to the focused context. For example, the desired action for a
/// deletion intent may be to delete a character in a text input, or to delete
/// a file in a file menu.
1069
///
1070 1071 1072 1073 1074 1075 1076
/// {@tool dartpad}
/// This example uses the [CallbackShortcuts] widget to add and subtract
/// from a counter when the up or down arrow keys are pressed.
///
/// ** See code in examples/api/lib/widgets/shortcuts/callback_shortcuts.0.dart **
/// {@end-tool}
///
1077 1078 1079 1080
/// [Shortcuts] and [CallbackShortcuts] can both be used in the same app. As
/// with any key handling widget, if this widget handles a key event then
/// widgets above it in the focus chain will not receive the event. This means
/// that if this widget handles a key, then an ancestor [Shortcuts] widget (or
1081
/// any other key handling widget) will not receive that key. Similarly, if
1082 1083 1084
/// a descendant of this widget handles the key, then the key event will not
/// reach this widget for handling.
///
1085 1086 1087 1088
/// See the article on [Using Actions and
/// Shortcuts](https://docs.flutter.dev/development/ui/advanced/actions_and_shortcuts)
/// for a detailed explanation.
///
1089
/// See also:
1090
///  * [Shortcuts], a more powerful widget for defining key bindings.
1091 1092 1093 1094
///  * [Focus], a widget that defines which widgets can receive keyboard focus.
class CallbackShortcuts extends StatelessWidget {
  /// Creates a const [CallbackShortcuts] widget.
  const CallbackShortcuts({
1095
    super.key,
1096 1097
    required this.bindings,
    required this.child,
1098
  });
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126

  /// A map of key combinations to callbacks used to define the shortcut
  /// bindings.
  ///
  /// If a descendant of this widget has focus, and a key is pressed, the
  /// activator keys of this map will be asked if they accept the key event. If
  /// they do, then the corresponding callback is invoked, and the key event
  /// propagation is halted. If none of the activators accept the key event,
  /// then the key event continues to be propagated up the focus chain.
  ///
  /// If more than one activator accepts the key event, then all of the
  /// callbacks associated with activators that accept the key event are
  /// invoked.
  ///
  /// Some examples of [ShortcutActivator] subclasses that can be used to define
  /// the key combinations here are [SingleActivator], [CharacterActivator], and
  /// [LogicalKeySet].
  final Map<ShortcutActivator, VoidCallback> bindings;

  /// The widget below this widget in the tree.
  ///
  /// {@macro flutter.widgets.ProxyWidget.child}
  final Widget child;

  // A helper function to make the stack trace more useful if the callback
  // throws, by providing the activator and event as arguments that will appear
  // in the stack trace.
  bool _applyKeyBinding(ShortcutActivator activator, RawKeyEvent event) {
1127 1128 1129
    if (ShortcutActivator.isActivatedBy(activator, event)) {
      bindings[activator]!.call();
      return true;
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
    }
    return false;
  }

  @override
  Widget build(BuildContext context) {
    return Focus(
      canRequestFocus: false,
      skipTraversal: true,
      onKey: (FocusNode node, RawKeyEvent event) {
        KeyEventResult result = KeyEventResult.ignored;
        // Activates all key bindings that match, returns "handled" if any handle it.
        for (final ShortcutActivator activator in bindings.keys) {
          result = _applyKeyBinding(activator, event) ? KeyEventResult.handled : result;
        }
        return result;
      },
      child: child,
    );
  }
1150
}
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187

/// A entry returned by [ShortcutRegistry.addAll] that allows the caller to
/// identify the shortcuts they registered with the [ShortcutRegistry] through
/// the [ShortcutRegistrar].
///
/// When the entry is no longer needed, [dispose] should be called, and the
/// entry should no longer be used.
class ShortcutRegistryEntry {
  // Tokens can only be created by the ShortcutRegistry.
  const ShortcutRegistryEntry._(this.registry);

  /// The [ShortcutRegistry] that this entry was issued by.
  final ShortcutRegistry registry;

  /// Replaces the given shortcut bindings in the [ShortcutRegistry] that this
  /// entry was created from.
  ///
  /// This method will assert in debug mode if another [ShortcutRegistryEntry]
  /// exists (i.e. hasn't been disposed of) that has already added a given
  /// shortcut.
  ///
  /// It will also assert if this entry has already been disposed.
  ///
  /// If two equivalent, but different, [ShortcutActivator]s are added, all of
  /// them will be executed when triggered. For example, if both
  /// `SingleActivator(LogicalKeyboardKey.keyA)` and `CharacterActivator('a')`
  /// are added, then both will be executed when an "a" key is pressed.
  void replaceAll(Map<ShortcutActivator, Intent> value) {
    registry._replaceAll(this, value);
  }

  /// Called when the entry is no longer needed.
  ///
  /// Call this will remove all shortcuts associated with this
  /// [ShortcutRegistryEntry] from the [registry].
  @mustCallSuper
  void dispose() {
1188
    registry._disposeEntry(this);
1189 1190 1191 1192 1193 1194 1195 1196 1197
  }
}

/// A class used by [ShortcutRegistrar] that allows adding or removing shortcut
/// bindings by descendants of the [ShortcutRegistrar].
///
/// You can reach the nearest [ShortcutRegistry] using [of] and [maybeOf].
///
/// The registry may be listened to (with [addListener]/[removeListener]) for
1198
/// change notifications when the registered shortcuts change. Change
1199
/// notifications take place after the current frame is drawn, so that
1200 1201
/// widgets that are not descendants of the registry can listen to it (e.g. in
/// overlays).
1202
class ShortcutRegistry with ChangeNotifier {
1203 1204 1205 1206 1207 1208 1209
  /// Creates an instance of [ShortcutRegistry].
  ShortcutRegistry() {
    if (kFlutterMemoryAllocationsEnabled) {
      maybeDispatchObjectCreation();
    }
  }

1210 1211 1212 1213 1214 1215 1216 1217 1218
  bool _notificationScheduled = false;
  bool _disposed = false;

  @override
  void dispose() {
    super.dispose();
    _disposed = true;
  }

1219
  /// Gets the combined shortcut bindings from all contexts that are registered
1220
  /// with this [ShortcutRegistry].
1221 1222 1223 1224 1225
  ///
  /// Listeners will be notified when the value returned by this getter changes.
  ///
  /// Returns a copy: modifying the returned map will have no effect.
  Map<ShortcutActivator, Intent> get shortcuts {
1226
    assert(ChangeNotifier.debugAssertNotDisposed(this));
1227
    return <ShortcutActivator, Intent>{
1228
      for (final MapEntry<ShortcutRegistryEntry, Map<ShortcutActivator, Intent>> entry in _registeredShortcuts.entries)
1229 1230 1231
        ...entry.value,
    };
  }
1232 1233

  final Map<ShortcutRegistryEntry, Map<ShortcutActivator, Intent>> _registeredShortcuts =
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
    <ShortcutRegistryEntry, Map<ShortcutActivator, Intent>>{};

  /// Adds all the given shortcut bindings to this [ShortcutRegistry], and
  /// returns a entry for managing those bindings.
  ///
  /// The entry should have [ShortcutRegistryEntry.dispose] called on it when
  /// these shortcuts are no longer needed. This will remove them from the
  /// registry, and invalidate the entry.
  ///
  /// This method will assert in debug mode if another entry exists (i.e. hasn't
  /// been disposed of) that has already added a given shortcut.
  ///
  /// If two equivalent, but different, [ShortcutActivator]s are added, all of
  /// them will be executed when triggered. For example, if both
  /// `SingleActivator(LogicalKeyboardKey.keyA)` and `CharacterActivator('a')`
  /// are added, then both will be executed when an "a" key is pressed.
  ///
  /// See also:
  ///
  ///  * [ShortcutRegistryEntry.replaceAll], a function used to replace the set of
  ///    shortcuts associated with a particular entry.
  ///  * [ShortcutRegistryEntry.dispose], a function used to remove the set of
  ///    shortcuts associated with a particular entry.
  ShortcutRegistryEntry addAll(Map<ShortcutActivator, Intent> value) {
1258
    assert(ChangeNotifier.debugAssertNotDisposed(this));
1259
    assert(value.isNotEmpty, 'Cannot register an empty map of shortcuts');
1260
    final ShortcutRegistryEntry entry = ShortcutRegistryEntry._(this);
1261
    _registeredShortcuts[entry] = value;
1262
    assert(_debugCheckForDuplicates());
1263
    _notifyListenersNextFrame();
1264 1265 1266
    return entry;
  }

1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
  // Subscriber notification has to happen in the next frame because shortcuts
  // are often registered that affect things in the overlay or different parts
  // of the tree, and so can cause build ordering issues if notifications happen
  // during the build. The _notificationScheduled check makes sure we only
  // notify once per frame.
  void _notifyListenersNextFrame() {
    if (!_notificationScheduled) {
      SchedulerBinding.instance.addPostFrameCallback((Duration _) {
        _notificationScheduled = false;
        if (!_disposed) {
          notifyListeners();
        }
      });
      _notificationScheduled = true;
    }
  }

1284 1285 1286
  /// Returns the [ShortcutRegistry] that belongs to the [ShortcutRegistrar]
  /// which most tightly encloses the given [BuildContext].
  ///
1287
  /// If no [ShortcutRegistrar] widget encloses the context given, [of] will
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
  /// throw an exception in debug mode.
  ///
  /// There is a default [ShortcutRegistrar] instance in [WidgetsApp], so if
  /// [WidgetsApp], [MaterialApp] or [CupertinoApp] are used, an additional
  /// [ShortcutRegistrar] isn't needed.
  ///
  /// See also:
  ///
  ///  * [maybeOf], which is similar to this function, but will return null if
  ///    it doesn't find a [ShortcutRegistrar] ancestor.
  static ShortcutRegistry of(BuildContext context) {
1299 1300
    final _ShortcutRegistrarScope? inherited =
      context.dependOnInheritedWidgetOfExactType<_ShortcutRegistrarScope>();
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
    assert(() {
      if (inherited == null) {
        throw FlutterError(
          'Unable to find a $ShortcutRegistrar widget in the context.\n'
          '$ShortcutRegistrar.of() was called with a context that does not contain a '
          '$ShortcutRegistrar widget.\n'
          'No $ShortcutRegistrar ancestor could be found starting from the context that was '
          'passed to $ShortcutRegistrar.of().\n'
          'The context used was:\n'
          '  $context',
        );
      }
      return true;
    }());
    return inherited!.registry;
  }

  /// Returns [ShortcutRegistry] of the [ShortcutRegistrar] that most tightly
  /// encloses the given [BuildContext].
  ///
1321
  /// If no [ShortcutRegistrar] widget encloses the given context, [maybeOf]
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
  /// will return null.
  ///
  /// There is a default [ShortcutRegistrar] instance in [WidgetsApp], so if
  /// [WidgetsApp], [MaterialApp] or [CupertinoApp] are used, an additional
  /// [ShortcutRegistrar] isn't needed.
  ///
  /// See also:
  ///
  ///  * [of], which is similar to this function, but returns a non-nullable
  ///    result, and will throw an exception if it doesn't find a
  ///    [ShortcutRegistrar] ancestor.
  static ShortcutRegistry? maybeOf(BuildContext context) {
1334 1335
    final _ShortcutRegistrarScope? inherited =
      context.dependOnInheritedWidgetOfExactType<_ShortcutRegistrarScope>();
1336 1337 1338 1339 1340 1341
    return inherited?.registry;
  }

  // Replaces all the shortcuts associated with the given entry from this
  // registry.
  void _replaceAll(ShortcutRegistryEntry entry, Map<ShortcutActivator, Intent> value) {
1342
    assert(ChangeNotifier.debugAssertNotDisposed(this));
1343 1344
    assert(_debugCheckEntryIsValid(entry));
    _registeredShortcuts[entry] = value;
1345
    assert(_debugCheckForDuplicates());
1346
    _notifyListenersNextFrame();
1347 1348 1349 1350
  }

  // Removes all the shortcuts associated with the given entry from this
  // registry.
1351 1352 1353 1354 1355
  void _disposeEntry(ShortcutRegistryEntry entry) {
    assert(_debugCheckEntryIsValid(entry));
    final Map<ShortcutActivator, Intent>? removedShortcut = _registeredShortcuts.remove(entry);
    if (removedShortcut != null) {
      _notifyListenersNextFrame();
1356 1357 1358
    }
  }

1359 1360
  bool _debugCheckEntryIsValid(ShortcutRegistryEntry entry) {
    if (!_registeredShortcuts.containsKey(entry)) {
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
      if (entry.registry == this) {
        throw FlutterError('entry ${describeIdentity(entry)} is invalid.\n'
          'The entry has already been disposed of. Tokens are not valid after '
          'dispose is called on them, and should no longer be used.');
      } else {
        throw FlutterError('Foreign entry ${describeIdentity(entry)} used.\n'
          'This entry was not created by this registry, it was created by '
          '${describeIdentity(entry.registry)}, and should be used with that '
          'registry instead.');
      }
    }
    return true;
  }

  bool _debugCheckForDuplicates() {
    final Map<ShortcutActivator, ShortcutRegistryEntry?> previous = <ShortcutActivator, ShortcutRegistryEntry?>{};
1377
    for (final MapEntry<ShortcutRegistryEntry, Map<ShortcutActivator, Intent>> tokenEntry in _registeredShortcuts.entries) {
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
      for (final ShortcutActivator shortcut in tokenEntry.value.keys) {
        if (previous.containsKey(shortcut)) {
          throw FlutterError(
            '$ShortcutRegistry: Received a duplicate registration for the '
            'shortcut $shortcut in ${describeIdentity(tokenEntry.key)} and ${previous[shortcut]}.');
        }
        previous[shortcut] = tokenEntry.key;
      }
    }
    return true;
  }
}

/// A widget that holds a [ShortcutRegistry] which allows descendants to add,
/// remove, or replace shortcuts.
///
/// This widget holds a [ShortcutRegistry] so that its descendants can find it
/// with [ShortcutRegistry.of] or [ShortcutRegistry.maybeOf].
///
/// The registered shortcuts are valid whenever a widget below this one in the
/// hierarchy has focus.
///
/// To add shortcuts to the registry, call [ShortcutRegistry.of] or
/// [ShortcutRegistry.maybeOf] to get the [ShortcutRegistry], and then add them
/// using [ShortcutRegistry.addAll], which will return a [ShortcutRegistryEntry]
/// which must be disposed by calling [ShortcutRegistryEntry.dispose] when the
/// shortcuts are no longer needed.
///
/// To replace or update the shortcuts in the registry, call
/// [ShortcutRegistryEntry.replaceAll].
///
/// To remove previously added shortcuts from the registry, call
/// [ShortcutRegistryEntry.dispose] on the entry returned by
/// [ShortcutRegistry.addAll].
class ShortcutRegistrar extends StatefulWidget {
  /// Creates a const [ShortcutRegistrar].
  ///
  /// The [child] parameter is required.
  const ShortcutRegistrar({super.key, required this.child});

  /// The widget below this widget in the tree.
  ///
  /// {@macro flutter.widgets.ProxyWidget.child}
  final Widget child;

  @override
  State<ShortcutRegistrar> createState() => _ShortcutRegistrarState();
}

class _ShortcutRegistrarState extends State<ShortcutRegistrar> {
  final ShortcutRegistry registry = ShortcutRegistry();
  final ShortcutManager manager = ShortcutManager();

  @override
  void initState() {
    super.initState();
    registry.addListener(_shortcutsChanged);
  }

  void _shortcutsChanged() {
    // This shouldn't need to update the widget, and avoids calling setState
    // during build phase.
    manager.shortcuts = registry.shortcuts;
  }

  @override
  void dispose() {
    registry.removeListener(_shortcutsChanged);
    registry.dispose();
1447
    manager.dispose();
1448 1449 1450 1451 1452
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
1453
    return _ShortcutRegistrarScope(
1454 1455 1456
      registry: registry,
      child: Shortcuts.manager(
        manager: manager,
1457 1458 1459 1460 1461 1462
        child: widget.child,
      ),
    );
  }
}

1463 1464
class _ShortcutRegistrarScope extends InheritedWidget {
  const _ShortcutRegistrarScope({
1465 1466 1467 1468 1469 1470 1471
    required this.registry,
    required super.child,
  });

  final ShortcutRegistry registry;

  @override
1472
  bool updateShouldNotify(covariant _ShortcutRegistrarScope oldWidget) {
1473 1474 1475
    return registry != oldWidget.registry;
  }
}