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

5 6 7
import 'dart:collection';
import 'dart:io';

8 9 10 11 12
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';

13
void main() {
14 15 16 17 18 19
  runApp(const MaterialApp(
    title: 'Actions Demo',
    home: FocusDemo(),
  ));
}

20 21 22 23 24
/// A class that can hold invocation information that an [UndoableAction] can
/// use to undo/redo itself.
///
/// Instances of this class are returned from [UndoableAction]s and placed on
/// the undo stack when they are invoked.
25
class Memento extends Object with Diagnosticable {
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
  const Memento({
    @required this.name,
    @required this.undo,
    @required this.redo,
  });

  /// Returns true if this Memento can be used to undo.
  ///
  /// Subclasses could override to provide their own conditions when a command is
  /// undoable.
  bool get canUndo => true;

  /// Returns true if this Memento can be used to redo.
  ///
  /// Subclasses could override to provide their own conditions when a command is
  /// redoable.
  bool get canRedo => true;

  final String name;
  final VoidCallback undo;
  final ValueGetter<Memento> redo;

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(StringProperty('name', name));
    properties.add(FlagProperty('undo', value: undo != null, ifTrue: 'undo'));
    properties.add(FlagProperty('redo', value: redo != null, ifTrue: 'redo'));
  }
}

57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
/// Undoable Actions

/// An [ActionDispatcher] subclass that manages the invocation of undoable
/// actions.
class UndoableActionDispatcher extends ActionDispatcher implements Listenable {
  /// Constructs a new [UndoableActionDispatcher].
  ///
  /// The [maxUndoLevels] argument must not be null.
  UndoableActionDispatcher({
    int maxUndoLevels = _defaultMaxUndoLevels,
  })  : assert(maxUndoLevels != null),
        _maxUndoLevels = maxUndoLevels;

  // A stack of actions that have been performed. The most recent action
  // performed is at the end of the list.
72
  final DoubleLinkedQueue<Memento> _completedActions = DoubleLinkedQueue<Memento>();
73 74
  // A stack of actions that can be redone. The most recent action performed is
  // at the end of the list.
75
  final List<Memento> _undoneActions = <Memento>[];
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

  static const int _defaultMaxUndoLevels = 1000;

  /// The maximum number of undo levels allowed.
  ///
  /// If this value is set to a value smaller than the number of completed
  /// actions, then the stack of completed actions is truncated to only include
  /// the last [maxUndoLevels] actions.
  int get maxUndoLevels => _maxUndoLevels;
  int _maxUndoLevels;
  set maxUndoLevels(int value) {
    _maxUndoLevels = value;
    _pruneActions();
  }

  final Set<VoidCallback> _listeners = <VoidCallback>{};

  @override
  void addListener(VoidCallback listener) {
    _listeners.add(listener);
  }

  @override
  void removeListener(VoidCallback listener) {
    _listeners.remove(listener);
  }

  /// Notifies listeners that the [ActionDispatcher] has changed state.
  ///
  /// May only be called by subclasses.
  @protected
  void notifyListeners() {
108
    for (final VoidCallback callback in _listeners) {
109 110 111 112 113
      callback();
    }
  }

  @override
114 115
  Object invokeAction(Action<Intent> action, Intent intent, [BuildContext context]) {
    final Object result = super.invokeAction(action, intent, context);
116 117
    print('Invoking ${action is UndoableAction ? 'undoable ' : ''}$intent as $action: $this ');
    if (action is UndoableAction) {
118
      _completedActions.addLast(result as Memento);
119 120 121 122 123 124 125 126 127 128
      _undoneActions.clear();
      _pruneActions();
      notifyListeners();
    }
    return result;
  }

  // Enforces undo level limit.
  void _pruneActions() {
    while (_completedActions.length > _maxUndoLevels) {
129
      _completedActions.removeFirst();
130 131 132 133 134 135
    }
  }

  /// Returns true if there is an action on the stack that can be undone.
  bool get canUndo {
    if (_completedActions.isNotEmpty) {
136
      return _completedActions.first.canUndo;
137 138 139 140 141 142 143
    }
    return false;
  }

  /// Returns true if an action that has been undone can be re-invoked.
  bool get canRedo {
    if (_undoneActions.isNotEmpty) {
144
      return _undoneActions.first.canRedo;
145 146 147 148 149 150 151 152 153 154 155 156
    }
    return false;
  }

  /// Undoes the last action executed if possible.
  ///
  /// Returns true if the action was successfully undone.
  bool undo() {
    print('Undoing. $this');
    if (!canUndo) {
      return false;
    }
157 158 159
    final Memento memento = _completedActions.removeLast();
    memento.undo();
    _undoneActions.add(memento);
160 161 162 163 164 165 166 167 168 169 170 171
    notifyListeners();
    return true;
  }

  /// Re-invokes a previously undone action, if possible.
  ///
  /// Returns true if the action was successfully invoked.
  bool redo() {
    print('Redoing. $this');
    if (!canRedo) {
      return false;
    }
172 173 174
    final Memento memento = _undoneActions.removeLast();
    final Memento replacement = memento.redo();
    _completedActions.add(replacement);
175 176 177 178 179 180 181 182 183 184
    _pruneActions();
    notifyListeners();
    return true;
  }

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(IntProperty('undoable items', _completedActions.length));
    properties.add(IntProperty('redoable items', _undoneActions.length));
185 186
    properties.add(IterableProperty<Memento>('undo stack', _completedActions));
    properties.add(IterableProperty<Memento>('redo stack', _undoneActions));
187 188 189 190
  }
}

class UndoIntent extends Intent {
191 192
  const UndoIntent();
}
193

194
class UndoAction extends Action<UndoIntent> {
195
  @override
196
  bool isEnabled(UndoIntent intent) {
197
    final UndoableActionDispatcher manager = Actions.of(primaryFocus?.context ?? FocusDemo.appKey.currentContext, nullOk: true) as UndoableActionDispatcher;
198 199
    return manager.canUndo;
  }
200 201 202 203 204 205

  @override
  void invoke(UndoIntent intent) {
    final UndoableActionDispatcher manager = Actions.of(primaryFocus?.context ?? FocusDemo.appKey.currentContext, nullOk: true) as UndoableActionDispatcher;
    manager?.undo();
  }
206 207 208
}

class RedoIntent extends Intent {
209 210
  const RedoIntent();
}
211

212
class RedoAction extends Action<RedoIntent> {
213
  @override
214
  bool isEnabled(RedoIntent intent) {
215
    final UndoableActionDispatcher manager = Actions.of(primaryFocus.context, nullOk: true) as UndoableActionDispatcher;
216 217 218
    return manager.canRedo;
  }

219 220 221
  @override
  RedoAction invoke(RedoIntent intent) {
    final UndoableActionDispatcher manager = Actions.of(primaryFocus.context, nullOk: true) as UndoableActionDispatcher;
222
    manager?.redo();
223 224 225
    return this;
  }
}
226 227

/// An action that can be undone.
228
abstract class UndoableAction<T extends Intent> extends Action<T> {
229 230 231 232 233 234 235 236 237
  /// The [Intent] this action was originally invoked with.
  Intent get invocationIntent => _invocationTag;
  Intent _invocationTag;

  @protected
  set invocationIntent(Intent value) => _invocationTag = value;

  @override
  @mustCallSuper
238
  void invoke(T intent) {
239
    invocationIntent = intent;
240 241 242
  }
}

243
class UndoableFocusActionBase<T extends Intent> extends UndoableAction<T> {
244
  @override
245 246 247 248 249 250 251 252 253
  @mustCallSuper
  Memento invoke(T intent) {
    super.invoke(intent);
    final FocusNode previousFocus = primaryFocus;
    return Memento(name: previousFocus.debugLabel, undo: () {
      previousFocus.requestFocus();
    }, redo: () {
      return invoke(intent);
    });
254 255 256
  }
}

257
class UndoableRequestFocusAction extends UndoableFocusActionBase<RequestFocusIntent> {
258
  @override
259 260 261 262
  Memento invoke(RequestFocusIntent intent) {
    final Memento memento = super.invoke(intent);
    intent.focusNode.requestFocus();
    return memento;
263 264 265 266
  }
}

/// Actions for manipulating focus.
267
class UndoableNextFocusAction extends UndoableFocusActionBase<NextFocusIntent> {
268
  @override
269 270 271 272
  Memento invoke(NextFocusIntent intent) {
    final Memento memento = super.invoke(intent);
    primaryFocus.nextFocus();
    return memento;
273 274 275
  }
}

276
class UndoablePreviousFocusAction extends UndoableFocusActionBase<PreviousFocusIntent> {
277
  @override
278 279 280 281
  Memento invoke(PreviousFocusIntent intent) {
    final Memento memento = super.invoke(intent);
    primaryFocus.previousFocus();
    return memento;
282 283 284
  }
}

285
class UndoableDirectionalFocusAction extends UndoableFocusActionBase<DirectionalFocusIntent> {
286 287 288
  TraversalDirection direction;

  @override
289 290 291 292
  Memento invoke(DirectionalFocusIntent intent) {
    final Memento memento = super.invoke(intent);
    primaryFocus.focusInDirection(intent.direction);
    return memento;
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
  }
}

/// A button class that takes focus when clicked.
class DemoButton extends StatefulWidget {
  const DemoButton({this.name});

  final String name;

  @override
  _DemoButtonState createState() => _DemoButtonState();
}

class _DemoButtonState extends State<DemoButton> {
  FocusNode _focusNode;
308
  final GlobalKey _nameKey = GlobalKey();
309 310 311 312 313 314 315 316 317 318

  @override
  void initState() {
    super.initState();
    _focusNode = FocusNode(debugLabel: widget.name);
  }

  void _handleOnPressed() {
    print('Button ${widget.name} pressed.');
    setState(() {
319
      Actions.invoke(_nameKey.currentContext, RequestFocusIntent(_focusNode));
320 321 322 323 324 325 326 327 328 329 330
    });
  }

  @override
  void dispose() {
    super.dispose();
    _focusNode.dispose();
  }

  @override
  Widget build(BuildContext context) {
331
    return TextButton(
332
      focusNode: _focusNode,
333 334 335 336 337 338 339 340 341 342
      style: ButtonStyle(
        foregroundColor: MaterialStateProperty.all<Color>(Colors.black),
        overlayColor: MaterialStateProperty.resolveWith<Color>((Set<MaterialState> states) {
          if (states.contains(MaterialState.focused))
            return Colors.red;
          if (states.contains(MaterialState.hovered))
            return Colors.blue;
          return null;
        }),
      ),
343
      onPressed: () => _handleOnPressed(),
344
      child: Text(widget.name, key: _nameKey),
345 346 347 348 349 350 351
    );
  }
}

class FocusDemo extends StatefulWidget {
  const FocusDemo({Key key}) : super(key: key);

352 353
  static GlobalKey appKey = GlobalKey();

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
  @override
  _FocusDemoState createState() => _FocusDemoState();
}

class _FocusDemoState extends State<FocusDemo> {
  FocusNode outlineFocus;
  UndoableActionDispatcher dispatcher;
  bool canUndo;
  bool canRedo;

  @override
  void initState() {
    super.initState();
    outlineFocus = FocusNode(debugLabel: 'Demo Focus Node');
    dispatcher = UndoableActionDispatcher();
    canUndo = dispatcher.canUndo;
    canRedo = dispatcher.canRedo;
    dispatcher.addListener(_handleUndoStateChange);
  }

  void _handleUndoStateChange() {
    if (dispatcher.canUndo != canUndo) {
      setState(() {
        canUndo = dispatcher.canUndo;
      });
    }
    if (dispatcher.canRedo != canRedo) {
      setState(() {
        canRedo = dispatcher.canRedo;
      });
    }
  }

  @override
  void dispose() {
    dispatcher.removeListener(_handleUndoStateChange);
    outlineFocus.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final TextTheme textTheme = Theme.of(context).textTheme;
397 398
    return Actions(
      dispatcher: dispatcher,
399 400 401 402 403 404 405
      actions: <Type, Action<Intent>>{
        RequestFocusIntent: UndoableRequestFocusAction(),
        NextFocusIntent: UndoableNextFocusAction(),
        PreviousFocusIntent: UndoablePreviousFocusAction(),
        DirectionalFocusIntent: UndoableDirectionalFocusAction(),
        UndoIntent: UndoAction(),
        RedoIntent: RedoAction(),
406
      },
407
      child: FocusTraversalGroup(
408 409 410
        policy: ReadingOrderTraversalPolicy(),
        child: Shortcuts(
          shortcuts: <LogicalKeySet, Intent>{
411 412
            LogicalKeySet(Platform.isMacOS ? LogicalKeyboardKey.meta : LogicalKeyboardKey.control, LogicalKeyboardKey.shift, LogicalKeyboardKey.keyZ): const RedoIntent(),
            LogicalKeySet(Platform.isMacOS ? LogicalKeyboardKey.meta : LogicalKeyboardKey.control, LogicalKeyboardKey.keyZ): const UndoIntent(),
413 414
          },
          child: FocusScope(
415
            key: FocusDemo.appKey,
416 417 418
            debugLabel: 'Scope',
            autofocus: true,
            child: DefaultTextStyle(
419
              style: textTheme.headline4,
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
              child: Scaffold(
                appBar: AppBar(
                  title: const Text('Actions Demo'),
                ),
                body: Center(
                  child: Builder(builder: (BuildContext context) {
                    return Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: const <Widget>[
                            DemoButton(name: 'One'),
                            DemoButton(name: 'Two'),
                            DemoButton(name: 'Three'),
                          ],
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: const <Widget>[
                            DemoButton(name: 'Four'),
                            DemoButton(name: 'Five'),
                            DemoButton(name: 'Six'),
                          ],
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: const <Widget>[
                            DemoButton(name: 'Seven'),
                            DemoButton(name: 'Eight'),
                            DemoButton(name: 'Nine'),
                          ],
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Padding(
                              padding: const EdgeInsets.all(8.0),
458
                              child: ElevatedButton(
459 460 461
                                child: const Text('UNDO'),
                                onPressed: canUndo
                                    ? () {
462
                                        Actions.invoke(context, const UndoIntent());
463 464
                                      }
                                    : null,
465
                              ),
466 467 468
                            ),
                            Padding(
                              padding: const EdgeInsets.all(8.0),
469
                              child: ElevatedButton(
470 471 472
                                child: const Text('REDO'),
                                onPressed: canRedo
                                    ? () {
473
                                        Actions.invoke(context, const RedoIntent());
474 475
                                      }
                                    : null,
476
                              ),
477 478 479 480 481 482
                            ),
                          ],
                        ),
                      ],
                    );
                  }),
483 484 485 486 487 488 489 490 491
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}