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
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

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

19 20 21 22 23
/// 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.
24
class Memento extends Object with Diagnosticable {
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
  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'));
  }
}

56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
/// 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.
71
  final DoubleLinkedQueue<Memento> _completedActions = DoubleLinkedQueue<Memento>();
72 73
  // A stack of actions that can be redone. The most recent action performed is
  // at the end of the list.
74
  final List<Memento> _undoneActions = <Memento>[];
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

  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() {
107
    for (final VoidCallback callback in _listeners) {
108 109 110 111 112
      callback();
    }
  }

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

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

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

  /// Returns true if an action that has been undone can be re-invoked.
  bool get canRedo {
    if (_undoneActions.isNotEmpty) {
143
      return _undoneActions.first.canRedo;
144 145 146 147 148 149 150 151 152 153 154 155
    }
    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;
    }
156 157 158
    final Memento memento = _completedActions.removeLast();
    memento.undo();
    _undoneActions.add(memento);
159 160 161 162 163 164 165 166 167 168 169 170
    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;
    }
171 172 173
    final Memento memento = _undoneActions.removeLast();
    final Memento replacement = memento.redo();
    _completedActions.add(replacement);
174 175 176 177 178 179 180 181 182 183
    _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));
184 185
    properties.add(IterableProperty<Memento>('undo stack', _completedActions));
    properties.add(IterableProperty<Memento>('redo stack', _undoneActions));
186 187 188 189
  }
}

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

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

  @override
  void invoke(UndoIntent intent) {
202
    final UndoableActionDispatcher manager = Actions.of(primaryFocus?.context ?? FocusDemo.appKey.currentContext) as UndoableActionDispatcher;
203 204
    manager?.undo();
  }
205 206 207
}

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

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

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

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

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

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

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

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

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

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

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

  @override
288 289 290 291
  Memento invoke(DirectionalFocusIntent intent) {
    final Memento memento = super.invoke(intent);
    primaryFocus.focusInDirection(intent.direction);
    return memento;
292 293 294 295 296
  }
}

/// A button class that takes focus when clicked.
class DemoButton extends StatefulWidget {
297
  const DemoButton({Key key, this.name}) : super(key: key);
298 299 300 301 302 303 304 305 306

  final String name;

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

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

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

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

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

  @override
  Widget build(BuildContext context) {
330
    return TextButton(
331
      focusNode: _focusNode,
332 333 334 335 336 337 338 339 340 341
      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;
        }),
      ),
342
      onPressed: () => _handleOnPressed(),
343
      child: Text(widget.name, key: _nameKey),
344 345 346 347 348 349 350
    );
  }
}

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

351 352
  static GlobalKey appKey = GlobalKey();

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
  @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;
396 397
    return Actions(
      dispatcher: dispatcher,
398 399 400 401 402 403 404
      actions: <Type, Action<Intent>>{
        RequestFocusIntent: UndoableRequestFocusAction(),
        NextFocusIntent: UndoableNextFocusAction(),
        PreviousFocusIntent: UndoablePreviousFocusAction(),
        DirectionalFocusIntent: UndoableDirectionalFocusAction(),
        UndoIntent: UndoAction(),
        RedoIntent: RedoAction(),
405
      },
406
      child: FocusTraversalGroup(
407 408 409
        policy: ReadingOrderTraversalPolicy(),
        child: Shortcuts(
          shortcuts: <LogicalKeySet, Intent>{
410 411
            LogicalKeySet(Platform.isMacOS ? LogicalKeyboardKey.meta : LogicalKeyboardKey.control, LogicalKeyboardKey.shift, LogicalKeyboardKey.keyZ): const RedoIntent(),
            LogicalKeySet(Platform.isMacOS ? LogicalKeyboardKey.meta : LogicalKeyboardKey.control, LogicalKeyboardKey.keyZ): const UndoIntent(),
412 413
          },
          child: FocusScope(
414
            key: FocusDemo.appKey,
415 416 417
            debugLabel: 'Scope',
            autofocus: true,
            child: DefaultTextStyle(
418
              style: textTheme.headline4,
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
              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),
457
                              child: ElevatedButton(
458 459 460
                                child: const Text('UNDO'),
                                onPressed: canUndo
                                    ? () {
461
                                        Actions.invoke(context, const UndoIntent());
462 463
                                      }
                                    : null,
464
                              ),
465 466 467
                            ),
                            Padding(
                              padding: const EdgeInsets.all(8.0),
468
                              child: ElevatedButton(
469 470 471
                                child: const Text('REDO'),
                                onPressed: canRedo
                                    ? () {
472
                                        Actions.invoke(context, const RedoIntent());
473 474
                                      }
                                    : null,
475
                              ),
476 477 478 479 480 481
                            ),
                          ],
                        ),
                      ],
                    );
                  }),
482 483 484 485 486 487 488 489 490
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}