/
shortcuts.dart
1531 lines (1413 loc) · 58.6 KB
/
shortcuts.dart
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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:collection';
import 'package:flutter/foundation.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'actions.dart';
import 'focus_manager.dart';
import 'focus_scope.dart';
import 'framework.dart';
import 'platform_menu_bar.dart';
final Set<LogicalKeyboardKey> _controlSynonyms = LogicalKeyboardKey.expandSynonyms(<LogicalKeyboardKey>{LogicalKeyboardKey.control});
final Set<LogicalKeyboardKey> _shiftSynonyms = LogicalKeyboardKey.expandSynonyms(<LogicalKeyboardKey>{LogicalKeyboardKey.shift});
final Set<LogicalKeyboardKey> _altSynonyms = LogicalKeyboardKey.expandSynonyms(<LogicalKeyboardKey>{LogicalKeyboardKey.alt});
final Set<LogicalKeyboardKey> _metaSynonyms = LogicalKeyboardKey.expandSynonyms(<LogicalKeyboardKey>{LogicalKeyboardKey.meta});
/// 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:
///
/// * [ShortcutManager], which uses [LogicalKeySet] (a [KeySet] subclass) to
/// define its key map.
@immutable
class KeySet<T extends KeyboardKey> {
/// A constructor for making a [KeySet] of up to four keys.
///
/// If you need a set of more than four keys, use [KeySet.fromSet].
///
/// The same [KeyboardKey] may not be appear more than once in the set.
KeySet(
T key1, [
T? key2,
T? key3,
T? key4,
]) : _keys = HashSet<T>()..add(key1) {
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.');
}
/// Create a [KeySet] from a set of [KeyboardKey]s.
///
/// Do not mutate the `keys` set after passing it to this object.
///
/// The `keys` set must not be empty.
KeySet.fromSet(Set<T> keys)
: assert(keys.isNotEmpty),
assert(!keys.contains(null)),
_keys = HashSet<T>.of(keys);
/// Returns a copy of the [KeyboardKey]s in this [KeySet].
Set<T> get keys => _keys.toSet();
final HashSet<T> _keys;
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is KeySet<T>
&& setEquals<T>(other._keys, _keys);
}
// Cached hash code value. Improves [hashCode] performance by 27%-900%,
// depending on key set size and read/write ratio.
@override
late final int hashCode = _computeHashCode(_keys);
// 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) {
// Compute order-independent hash and cache it.
final int length = keys.length;
final Iterator<T> iterator = keys.iterator;
// 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.
return h1;
}
iterator.moveNext();
final int h2 = iterator.current.hashCode;
if (length == 2) {
// No need to sort if there's two keys, just compare them.
return h1 < h2
? Object.hash(h1, h2)
: Object.hash(h2, h1);
}
// Sort key hash codes and feed to Object.hashAll to ensure the aggregate
// 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();
return Object.hashAll(sortedHashes);
}
}
/// Determines how the state of a lock key is used to accept a shortcut.
enum LockState {
/// The lock key state is not used to determine [SingleActivator.accepts] result.
ignored,
/// The lock key must be locked to trigger the shortcut.
locked,
/// The lock key must be unlocked to trigger the shortcut.
unlocked,
}
/// 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).
/// * [CharacterActivator], an implementation that represents key combinations
/// that result in the specified character, such as question mark.
/// * [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();
/// An optional property to provide all the keys that might be the final event
/// to trigger this shortcut.
///
/// For example, for `Ctrl-A`, [LogicalKeyboardKey.keyA] is the only trigger,
/// while [LogicalKeyboardKey.control] 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.
///
/// If provided, trigger keys can be used as a first-pass filter for incoming
/// events in order to optimize lookups, as [Intent]s are stored in a [Map]
/// and indexed by trigger keys. It is up to the individual implementors of
/// this interface to decide if they ignore triggers or not.
///
/// Subclasses should make sure that the return value of this method does not
/// change throughout the lifespan of this object.
///
/// This method might also return null, which means this activator declares
/// all keys as trigger keys. Activators whose [triggers] return 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 => null;
/// 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
/// [KeyDownEvent], if either side of the Ctrl key is pressed, and none of 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.
///
/// As a possible performance improvement, implementers of this function are
/// encouraged (but not required) to check the [triggers] member, if it is
/// non-null, to see if it contains the event's logical key before doing more
/// complicated work.
///
/// This method must not cause any side effects for the `state`. Typically
/// this is only used to query whether [HardwareKeyboard.logicalKeysPressed]
/// contains a key.
///
/// See also:
///
/// * [LogicalKeyboardKey.collapseSynonyms], which helps deciding whether a
/// modifier key is pressed when the side variation is not important.
bool accepts(KeyEvent event, HardwareKeyboard state);
/// Returns true if the event and current [HardwareKeyboard] state would cause
/// this [ShortcutActivator] to be activated.
@Deprecated(
'Call accepts on the activator instead. '
'This feature was deprecated after v3.16.0-15.0.pre.',
)
static bool isActivatedBy(ShortcutActivator activator, KeyEvent event) {
return activator.accepts(event, HardwareKeyboard.instance);
}
/// Returns a description of the key set that is short and readable.
///
/// Intended to be used in debug mode for logging purposes.
String debugDescribeKeys();
}
/// A set of [LogicalKeyboardKey]s that can be used as the keys in a map.
///
/// [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.
///
/// 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).
///
/// {@tool dartpad}
/// 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.
///
/// ** See code in examples/api/lib/widgets/shortcuts/logical_key_set.0.dart **
/// {@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 {
/// A constructor for making a [LogicalKeySet] of up to four keys.
///
/// If you need a set of more than four keys, use [LogicalKeySet.fromSet].
///
/// The same [LogicalKeyboardKey] may not be appear more than once in the set.
LogicalKeySet(
super.key1, [
super.key2,
super.key3,
super.key4,
]);
/// Create a [LogicalKeySet] from a set of [LogicalKeyboardKey]s.
///
/// Do not mutate the `keys` set after passing it to this object.
LogicalKeySet.fromSet(super.keys) : super.fromSet();
@override
Iterable<LogicalKeyboardKey> get triggers => _triggers;
late final Set<LogicalKeyboardKey> _triggers = keys.expand(
(LogicalKeyboardKey key) => _unmapSynonyms[key] ?? <LogicalKeyboardKey>[key],
).toSet();
bool _checkKeyRequirements(Set<LogicalKeyboardKey> pressed) {
final Set<LogicalKeyboardKey> collapsedRequired = LogicalKeyboardKey.collapseSynonyms(keys);
final Set<LogicalKeyboardKey> collapsedPressed = LogicalKeyboardKey.collapseSynonyms(pressed);
return collapsedRequired.length == collapsedPressed.length
&& collapsedRequired.difference(collapsedPressed).isEmpty;
}
@override
bool accepts(KeyEvent event, HardwareKeyboard state) {
if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
return false;
}
return triggers.contains(event.logicalKey)
&& _checkKeyRequirements(state.logicalKeysPressed);
}
static final Set<LogicalKeyboardKey> _modifiers = <LogicalKeyboardKey>{
LogicalKeyboardKey.alt,
LogicalKeyboardKey.control,
LogicalKeyboardKey.meta,
LogicalKeyboardKey.shift,
};
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],
};
@override
String debugDescribeKeys() {
final List<LogicalKeyboardKey> sortedKeys = keys.toList()
..sort((LogicalKeyboardKey a, LogicalKeyboardKey b) {
// 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;
}
return a.debugName!.compareTo(b.debugName!);
});
return sortedKeys.map<String>((LogicalKeyboardKey key) => key.debugName.toString()).join(' + ');
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Set<LogicalKeyboardKey>>('keys', _keys, description: debugDescribeKeys()));
}
}
/// A [DiagnosticsProperty] which handles formatting a `Map<LogicalKeySet, Intent>`
/// (the same type as the [Shortcuts.shortcuts] property) so that its
/// diagnostic output is human-readable.
class ShortcutMapProperty extends DiagnosticsProperty<Map<ShortcutActivator, Intent>> {
/// Create a diagnostics property for `Map<ShortcutActivator, Intent>` objects,
/// which are the same type as the [Shortcuts.shortcuts] property.
ShortcutMapProperty(
String super.name,
Map<ShortcutActivator, Intent> super.value, {
super.showName,
Object super.defaultValue,
super.level,
super.description,
});
@override
Map<ShortcutActivator, Intent> get value => super.value!;
@override
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.
///
/// The [SingleActivator] implements typical shortcuts such as:
///
/// * 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)`.
///
/// See also:
///
/// * [CharacterActivator], an activator that represents key combinations
/// that result in the specified character, such as question mark.
class SingleActivator with Diagnosticable, MenuSerializableShortcut implements ShortcutActivator {
/// Triggered when the [trigger] key is pressed while the modifiers are held.
///
/// The [trigger] should be the non-modifier key that is pressed after all the
/// modifiers, such as [LogicalKeyboardKey.keyC] as in `Ctrl+C`. It must not
/// be a modifier key (sided or unsided).
///
/// The [control], [shift], [alt], and [meta] flags represent whether the
/// respective modifier keys should be held (true) or released (false). They
/// default to false.
///
/// By default, the activator is checked on all [KeyDownEvent] events for the
/// [trigger] key. If [includeRepeats] is false, only [trigger] key events
/// which are not [KeyRepeatEvent]s will be considered.
///
/// {@tool dartpad}
/// In the following example, the shortcut `Control + C` increases the
/// counter:
///
/// ** See code in examples/api/lib/widgets/shortcuts/single_activator.single_activator.0.dart **
/// {@end-tool}
const SingleActivator(
this.trigger, {
this.control = false,
this.shift = false,
this.alt = false,
this.meta = false,
this.numLock = LockState.ignored,
this.includeRepeats = true,
}) : // The enumerated check with `identical` is cumbersome but the only way
// since const constructors can not call functions such as `==` or
// `Set.contains`. Checking with `identical` might not work when the
// key object is created from ID, but it covers common cases.
assert(
!identical(trigger, LogicalKeyboardKey.control) &&
!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),
);
/// 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.
///
/// 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.
///
/// See also:
///
/// * [LogicalKeyboardKey.controlLeft], [LogicalKeyboardKey.controlRight].
final bool control;
/// Whether either (or both) shift keys should be held for [trigger] to
/// activate the shortcut.
///
/// 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.
///
/// See also:
///
/// * [LogicalKeyboardKey.shiftLeft], [LogicalKeyboardKey.shiftRight].
final bool shift;
/// Whether either (or both) alt keys should be held for [trigger] to
/// 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 or both Alt keys must be pressed.
///
/// See also:
///
/// * [LogicalKeyboardKey.altLeft], [LogicalKeyboardKey.altRight].
final bool alt;
/// Whether either (or both) meta keys should be held for [trigger] to
/// 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
/// either or both Meta keys must be pressed.
///
/// See also:
///
/// * [LogicalKeyboardKey.metaLeft], [LogicalKeyboardKey.metaRight].
final bool meta;
/// Whether the NumLock key state should be checked for [trigger] to activate
/// the shortcut.
///
/// It defaults to [LockState.ignored], meaning the NumLock state is ignored
/// when the event is received in order to activate the shortcut.
/// If it's [LockState.locked], then the NumLock key must be locked.
/// If it's [LockState.unlocked], then the NumLock key must be unlocked.
///
/// See also:
///
/// * [LogicalKeyboardKey.numLock].
final LockState numLock;
/// Whether this activator accepts repeat events of the [trigger] key.
///
/// If [includeRepeats] is true, the activator is checked on all
/// [KeyDownEvent] or [KeyRepeatEvent]s for the [trigger] key. If
/// [includeRepeats] is false, only [trigger] key events which are
/// [KeyDownEvent]s will be considered.
final bool includeRepeats;
@override
Iterable<LogicalKeyboardKey> get triggers {
return <LogicalKeyboardKey>[trigger];
}
bool _shouldAcceptModifiers(Set<LogicalKeyboardKey> pressed) {
return control == pressed.intersection(_controlSynonyms).isNotEmpty
&& shift == pressed.intersection(_shiftSynonyms).isNotEmpty
&& alt == pressed.intersection(_altSynonyms).isNotEmpty
&& meta == pressed.intersection(_metaSynonyms).isNotEmpty;
}
bool _shouldAcceptNumLock(HardwareKeyboard state) {
return switch (numLock) {
LockState.ignored => true,
LockState.locked => state.lockModesEnabled.contains(KeyboardLockMode.numLock),
LockState.unlocked => !state.lockModesEnabled.contains(KeyboardLockMode.numLock),
};
}
@override
bool accepts(KeyEvent event, HardwareKeyboard state) {
return (event is KeyDownEvent || (includeRepeats && event is KeyRepeatEvent))
&& triggers.contains(event.logicalKey)
&& _shouldAcceptModifiers(state.logicalKeysPressed)
&& _shouldAcceptNumLock(state);
}
@override
ShortcutSerialization serializeForMenu() {
return ShortcutSerialization.modifier(
trigger,
shift: shift,
alt: alt,
meta: meta,
control: control,
);
}
/// 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);
properties.add(MessageProperty('keys', debugDescribeKeys()));
properties.add(FlagProperty('includeRepeats', value: includeRepeats, ifFalse: 'excluding repeats'));
}
}
/// 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
/// directly represents a question mark. Although 'Shift+Slash' produces a '?'
/// 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.
///
/// {@tool dartpad}
/// In the following example, when a key combination results in a question mark,
/// the [SnackBar] gets shown:
///
/// ** See code in examples/api/lib/widgets/shortcuts/character_activator.0.dart **
/// {@end-tool}
///
/// 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 [KeyDownEvent] or
/// [KeyRepeatEvent]s for the [character] in combination with the requested
/// modifier keys. If `includeRepeats` is false, only the [character] events
/// with that are [KeyDownEvent]s 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}
///
/// See also:
///
/// * [SingleActivator], an activator that represents a single key combined
/// with modifiers, such as `Ctrl+C` or `Ctrl-Right Arrow`.
class CharacterActivator with Diagnosticable, MenuSerializableShortcut implements ShortcutActivator {
/// Triggered when the key event yields the given character.
const CharacterActivator(this.character, {
this.alt = false,
this.control = false,
this.meta = false,
this.includeRepeats = true,
});
/// Whether either (or both) Alt keys should be held for the [character] to
/// 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
/// one or both Alt keys must be pressed.
///
/// {@macro flutter.widgets.shortcuts.CharacterActivator.alt}
///
/// See also:
///
/// * [LogicalKeyboardKey.altLeft], [LogicalKeyboardKey.altRight].
final bool alt;
/// Whether either (or both) Control keys should be held for the [character]
/// 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
/// either one or both Control keys must be pressed.
///
/// See also:
///
/// * [LogicalKeyboardKey.controlLeft], [LogicalKeyboardKey.controlRight].
final bool control;
/// Whether either (or both) Meta keys should be held for the [character] to
/// 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
/// either one or both Meta keys must be pressed.
///
/// 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
/// [KeyDownEvent] and [KeyRepeatEvent]s for the [character]. If
/// [includeRepeats] is false, only the [character] events that are
/// [KeyDownEvent]s will be considered.
final bool includeRepeats;
/// The character which triggers the shortcut.
///
/// 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:
///
/// * [KeyEvent.character], the character of a key event.
final String character;
@override
Iterable<LogicalKeyboardKey>? get triggers => null;
bool _shouldAcceptModifiers(Set<LogicalKeyboardKey> pressed) {
// Doesn't look for shift, since the character will encode that.
return control == pressed.intersection(_controlSynonyms).isNotEmpty
&& alt == pressed.intersection(_altSynonyms).isNotEmpty
&& meta == pressed.intersection(_metaSynonyms).isNotEmpty;
}
@override
bool accepts(KeyEvent event, HardwareKeyboard state) {
// Ignore triggers, since we're only interested in the character.
return event.character == character
&& (event is KeyDownEvent || (includeRepeats && event is KeyRepeatEvent))
&& _shouldAcceptModifiers(state.logicalKeysPressed);
}
@override
String debugDescribeKeys() {
String result = '';
assert(() {
final List<String> keys = <String>[
if (alt) 'Alt',
if (control) 'Control',
if (meta) 'Meta',
"'$character'",
];
result = keys.join(' + ');
return true;
}());
return result;
}
@override
ShortcutSerialization serializeForMenu() {
return ShortcutSerialization.character(character, alt: alt, control: control, meta: meta);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(MessageProperty('character', debugDescribeKeys()));
properties.add(FlagProperty('includeRepeats', value: includeRepeats, ifFalse: 'excluding repeats'));
}
}
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));
}
}
/// A manager of keyboard shortcut bindings used by [Shortcuts] to handle key
/// events.
///
/// The manager may be listened to (with [addListener]/[removeListener]) for
/// change notifications when the shortcuts change.
///
/// 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.
class ShortcutManager with Diagnosticable, ChangeNotifier {
/// Constructs a [ShortcutManager].
ShortcutManager({
Map<ShortcutActivator, Intent> shortcuts = const <ShortcutActivator, Intent>{},
this.modal = false,
}) : _shortcuts = shortcuts {
if (kFlutterMemoryAllocationsEnabled) {
ChangeNotifier.maybeDispatchObjectCreation(this);
}
}
/// 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.
///
/// 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.
///
/// The net effect of setting [modal] to true is to return
/// [KeyEventResult.skipRemainingHandlers] from [handleKeypress] if it does
/// not exist in the shortcut map, instead of returning
/// [KeyEventResult.ignored].
final bool modal;
/// Returns the shortcut map.
///
/// When the map is changed, listeners to this manager will be notified.
///
/// The returned map should not be modified.
Map<ShortcutActivator, Intent> get shortcuts => _shortcuts;
Map<ShortcutActivator, Intent> _shortcuts = <ShortcutActivator, Intent>{};
set shortcuts(Map<ShortcutActivator, Intent> value) {
if (!mapEquals<ShortcutActivator, Intent>(_shortcuts, value)) {
_shortcuts = value;
_indexedShortcutsCache = null;
notifyListeners();
}
}
static Map<LogicalKeyboardKey?, List<_ActivatorIntentPair>> _indexShortcuts(Map<ShortcutActivator, Intent> source) {
final Map<LogicalKeyboardKey?, List<_ActivatorIntentPair>> result = <LogicalKeyboardKey?, List<_ActivatorIntentPair>>{};
source.forEach((ShortcutActivator activator, Intent intent) {
// This intermediate variable is necessary to comply with Dart analyzer.
final Iterable<LogicalKeyboardKey?>? nullableTriggers = activator.triggers;
for (final LogicalKeyboardKey? trigger in nullableTriggers ?? <LogicalKeyboardKey?>[null]) {
result.putIfAbsent(trigger, () => <_ActivatorIntentPair>[])
.add(_ActivatorIntentPair(activator, intent));
}
});
return result;
}
Map<LogicalKeyboardKey?, List<_ActivatorIntentPair>> get _indexedShortcuts {
return _indexedShortcutsCache ??= _indexShortcuts(shortcuts);
}
Map<LogicalKeyboardKey?, List<_ActivatorIntentPair>>? _indexedShortcutsCache;
Iterable<_ActivatorIntentPair> _getCandidates(LogicalKeyboardKey key) {
return <_ActivatorIntentPair>[
... _indexedShortcuts[key] ?? <_ActivatorIntentPair>[],
... _indexedShortcuts[null] ?? <_ActivatorIntentPair>[],
];
}
/// Returns the [Intent], if any, that matches the current set of pressed
/// keys.
///
/// Returns null if no intent matches the current set of pressed keys.
Intent? _find(KeyEvent event, HardwareKeyboard state) {
for (final _ActivatorIntentPair activatorIntent in _getCandidates(event.logicalKey)) {
if (activatorIntent.activator.accepts(event, state)) {
return activatorIntent.intent;
}
}
return null;
}
/// Handles a key press `event` in the given `context`.
///
/// 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]).
///
/// Returns a [KeyEventResult.handled] if an action was invoked, otherwise a
/// [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].
///
/// In order for an action to be invoked (and [KeyEventResult.handled]
/// returned), a [ShortcutActivator] must accept the given [KeyEvent], be
/// mapped to an [Intent], the [Intent] must be mapped to an [Action], and the
/// [Action] must be enabled.
@protected
KeyEventResult handleKeypress(BuildContext context, KeyEvent event) {
final Intent? matchedIntent = _find(event, HardwareKeyboard.instance);
if (matchedIntent != null) {
final BuildContext? primaryContext = primaryFocus?.context;
if (primaryContext != null) {
final Action<Intent>? action = Actions.maybeFind<Intent>(
primaryContext,
intent: matchedIntent,
);
if (action != null) {
final (bool enabled, Object? invokeResult) = Actions.of(primaryContext).invokeActionIfEnabled(
action, matchedIntent, primaryContext,
);
if (enabled) {
return action.toKeyEventResult(matchedIntent, invokeResult);
}
}
}
}
return modal ? KeyEventResult.skipRemainingHandlers : KeyEventResult.ignored;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Map<ShortcutActivator, Intent>>('shortcuts', shortcuts));
properties.add(FlagProperty('modal', value: modal, ifTrue: 'modal', defaultValue: false));
}
}
/// A widget that creates key bindings to specific actions for its
/// descendants.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=6ZcQmdoz9N8}
///
/// This widget establishes a [ShortcutManager] to be used by its descendants
/// when invoking an [Action] via a keyboard key combination that maps to an
/// [Intent].
///
/// 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.
///
/// See the article on [Using Actions and
/// Shortcuts](https://docs.flutter.dev/development/ui/advanced/actions_and_shortcuts)
/// for a detailed explanation.
///
/// {@tool dartpad}
/// 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.
///
/// ** See code in examples/api/lib/widgets/shortcuts/shortcuts.0.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// 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).
///
/// ** See code in examples/api/lib/widgets/shortcuts/shortcuts.1.dart **
/// {@end-tool}
///
/// See also:
///
/// * [CallbackShortcuts], a simpler but less flexible widget that defines key
/// bindings that invoke callbacks.
/// * [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.
/// * [CallbackAction], a class for creating an action from a callback.
class Shortcuts extends StatefulWidget {
/// Creates a const [Shortcuts] widget that owns the map of shortcuts and
/// creates its own manager.
///
/// When using this constructor, [manager] will return null.
///
/// The [child] and [shortcuts] arguments are required.
///
/// See also:
///
/// * [Shortcuts.manager], a constructor that uses a [ShortcutManager] to
/// manage the shortcuts list instead.
const Shortcuts({
super.key,
required Map<ShortcutActivator, Intent> shortcuts,
required this.child,
this.debugLabel,
}) : _shortcuts = shortcuts,