arena.dart 9.66 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
Adam Barth's avatar
Adam Barth committed
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 7
import 'dart:async';

8 9 10 11
import 'package:flutter/foundation.dart';

import 'debug.dart';

12
/// Whether the gesture was accepted or rejected.
Adam Barth's avatar
Adam Barth committed
13
enum GestureDisposition {
14
  /// This gesture was accepted as the interpretation of the user's input.
Adam Barth's avatar
Adam Barth committed
15
  accepted,
16

17
  /// This gesture was rejected as the interpretation of the user's input.
18
  rejected,
Adam Barth's avatar
Adam Barth committed
19 20
}

21 22 23 24
/// Represents an object participating in an arena.
///
/// Receives callbacks from the GestureArena to notify the object when it wins
/// or loses a gesture negotiation. Exactly one of [acceptGesture] or
25
/// [rejectGesture] will be called for each arena this member was added to,
26 27 28
/// regardless of what caused the arena to be resolved. For example, if a
/// member resolves the arena itself, that member still receives an
/// [acceptGesture] callback.
Adam Barth's avatar
Adam Barth committed
29
abstract class GestureArenaMember {
30 31
  /// Called when this member wins the arena for the given pointer id.
  void acceptGesture(int pointer);
Adam Barth's avatar
Adam Barth committed
32

33 34
  /// Called when this member loses the arena for the given pointer id.
  void rejectGesture(int pointer);
Adam Barth's avatar
Adam Barth committed
35 36
}

37
/// An interface to pass information to an arena.
38 39
///
/// A given [GestureArenaMember] can have multiple entries in multiple arenas
40
/// with different pointer ids.
Adam Barth's avatar
Adam Barth committed
41
class GestureArenaEntry {
42
  GestureArenaEntry._(this._arena, this._pointer, this._member);
Adam Barth's avatar
Adam Barth committed
43

44 45
  final GestureArenaManager _arena;
  final int _pointer;
Adam Barth's avatar
Adam Barth committed
46 47 48
  final GestureArenaMember _member;

  /// Call this member to claim victory (with accepted) or admit defeat (with rejected).
49
  ///
50 51
  /// It's fine to attempt to resolve a gesture recognizer for an arena that is
  /// already resolved.
Adam Barth's avatar
Adam Barth committed
52
  void resolve(GestureDisposition disposition) {
53
    _arena._resolve(_pointer, _member, disposition);
Adam Barth's avatar
Adam Barth committed
54 55 56
  }
}

57
class _GestureArena {
58
  final List<GestureArenaMember> members = <GestureArenaMember>[];
59
  bool isOpen = true;
60
  bool isHeld = false;
61
  bool hasPendingSweep = false;
62

63
  /// If a member attempts to win while the arena is still open, it becomes the
64
  /// "eager winner". We look for an eager winner when closing the arena to new
65
  /// participants, and if there is one, we resolve the arena in its favor at
Hixie's avatar
Hixie committed
66
  /// that time.
67
  GestureArenaMember? eagerWinner;
Hixie's avatar
Hixie committed
68

69 70 71 72
  void add(GestureArenaMember member) {
    assert(isOpen);
    members.add(member);
  }
73 74 75

  @override
  String toString() {
76
    final StringBuffer buffer = StringBuffer();
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
    if (members.isEmpty) {
      buffer.write('<empty>');
    } else {
      buffer.write(members.map<String>((GestureArenaMember member) {
        if (member == eagerWinner)
          return '$member (eager winner)';
        return '$member';
      }).join(', '));
    }
    if (isOpen)
      buffer.write(' [open]');
    if (isHeld)
      buffer.write(' [held]');
    if (hasPendingSweep)
      buffer.write(' [hasPendingSweep]');
    return buffer.toString();
  }
94 95
}

96
/// The first member to accept or the last member to not reject wins.
97
///
98
/// See <https://flutter.dev/gestures/#gesture-disambiguation> for more
99
/// information about the role this class plays in the gesture system.
100 101 102
///
/// To debug problems with gestures, consider using
/// [debugPrintGestureArenaDiagnostics].
103
class GestureArenaManager {
104
  final Map<int, _GestureArena> _arenas = <int, _GestureArena>{};
Adam Barth's avatar
Adam Barth committed
105

106
  /// Adds a new member (e.g., gesture recognizer) to the arena.
107
  GestureArenaEntry add(int pointer, GestureArenaMember member) {
108 109
    final _GestureArena state = _arenas.putIfAbsent(pointer, () {
      assert(_debugLogDiagnostic(pointer, '★ Opening new gesture arena.'));
110
      return _GestureArena();
111
    });
112
    state.add(member);
113
    assert(_debugLogDiagnostic(pointer, 'Adding: $member'));
114
    return GestureArenaEntry._(this, pointer, member);
Adam Barth's avatar
Adam Barth committed
115 116
  }

117 118 119
  /// Prevents new members from entering the arena.
  ///
  /// Called after the framework has finished dispatching the pointer down event.
120
  void close(int pointer) {
121
    final _GestureArena? state = _arenas[pointer];
122
    if (state == null)
123
      return; // This arena either never existed or has been resolved.
124
    state.isOpen = false;
125
    assert(_debugLogDiagnostic(pointer, 'Closing', state));
126
    _tryToResolveArena(pointer, state);
127 128
  }

129
  /// Forces resolution of the arena, giving the win to the first member.
130 131 132 133 134 135 136 137 138 139 140 141
  ///
  /// Sweep is typically after all the other processing for a [PointerUpEvent]
  /// have taken place. It ensures that multiple passive gestures do not cause a
  /// stalemate that prevents the user from interacting with the app.
  ///
  /// Recognizers that wish to delay resolving an arena past [PointerUpEvent]
  /// should call [hold] to delay sweep until [release] is called.
  ///
  /// See also:
  ///
  ///  * [hold]
  ///  * [release]
142
  void sweep(int pointer) {
143
    final _GestureArena? state = _arenas[pointer];
144
    if (state == null)
145
      return; // This arena either never existed or has been resolved.
146
    assert(!state.isOpen);
147 148
    if (state.isHeld) {
      state.hasPendingSweep = true;
149
      assert(_debugLogDiagnostic(pointer, 'Delaying sweep', state));
150
      return; // This arena is being held for a long-lived member.
151
    }
152
    assert(_debugLogDiagnostic(pointer, 'Sweeping', state));
153
    _arenas.remove(pointer);
Ian Hickson's avatar
Ian Hickson committed
154
    if (state.members.isNotEmpty) {
155 156
      // First member wins.
      assert(_debugLogDiagnostic(pointer, 'Winner: ${state.members.first}'));
157
      state.members.first.acceptGesture(pointer);
158
      // Give all the other members the bad news.
159
      for (int i = 1; i < state.members.length; i++)
160
        state.members[i].rejectGesture(pointer);
161 162 163
    }
  }

Florian Loitsch's avatar
Florian Loitsch committed
164
  /// Prevents the arena from being swept.
165 166 167 168 169 170 171 172 173 174 175
  ///
  /// Typically, a winner is chosen in an arena after all the other
  /// [PointerUpEvent] processing by [sweep]. If a recognizer wishes to delay
  /// resolving an arena past [PointerUpEvent], the recognizer can [hold] the
  /// arena open using this function. To release such a hold and let the arena
  /// resolve, call [release].
  ///
  /// See also:
  ///
  ///  * [sweep]
  ///  * [release]
176
  void hold(int pointer) {
177
    final _GestureArena? state = _arenas[pointer];
178
    if (state == null)
179
      return; // This arena either never existed or has been resolved.
180
    state.isHeld = true;
181
    assert(_debugLogDiagnostic(pointer, 'Holding', state));
182 183
  }

Florian Loitsch's avatar
Florian Loitsch committed
184 185
  /// Releases a hold, allowing the arena to be swept.
  ///
186
  /// If a sweep was attempted on a held arena, the sweep will be done
Florian Loitsch's avatar
Florian Loitsch committed
187
  /// on release.
188 189 190 191 192
  ///
  /// See also:
  ///
  ///  * [sweep]
  ///  * [hold]
193
  void release(int pointer) {
194
    final _GestureArena? state = _arenas[pointer];
195
    if (state == null)
196
      return; // This arena either never existed or has been resolved.
197
    state.isHeld = false;
198
    assert(_debugLogDiagnostic(pointer, 'Releasing', state));
199
    if (state.hasPendingSweep)
200
      sweep(pointer);
201 202
  }

203 204 205
  /// Reject or accept a gesture recognizer.
  ///
  /// This is called by calling [GestureArenaEntry.resolve] on the object returned from [add].
206
  void _resolve(int pointer, GestureArenaMember member, GestureDisposition disposition) {
207
    final _GestureArena? state = _arenas[pointer];
208
    if (state == null)
209
      return; // This arena has already resolved.
210
    assert(_debugLogDiagnostic(pointer, '${ disposition == GestureDisposition.accepted ? "Accepting" : "Rejecting" }: $member'));
211
    assert(state.members.contains(member));
Adam Barth's avatar
Adam Barth committed
212
    if (disposition == GestureDisposition.rejected) {
213
      state.members.remove(member);
214
      member.rejectGesture(pointer);
Hixie's avatar
Hixie committed
215
      if (!state.isOpen)
216
        _tryToResolveArena(pointer, state);
Adam Barth's avatar
Adam Barth committed
217 218
    } else {
      assert(disposition == GestureDisposition.accepted);
Hixie's avatar
Hixie committed
219
      if (state.isOpen) {
Ian Hickson's avatar
Ian Hickson committed
220
        state.eagerWinner ??= member;
Hixie's avatar
Hixie committed
221
      } else {
222
        assert(_debugLogDiagnostic(pointer, 'Self-declared winner: $member'));
223
        _resolveInFavorOf(pointer, state, member);
Adam Barth's avatar
Adam Barth committed
224 225 226
      }
    }
  }
Hixie's avatar
Hixie committed
227

228 229 230 231 232 233 234 235 236 237
  void _tryToResolveArena(int pointer, _GestureArena state) {
    assert(_arenas[pointer] == state);
    assert(!state.isOpen);
    if (state.members.length == 1) {
      scheduleMicrotask(() => _resolveByDefault(pointer, state));
    } else if (state.members.isEmpty) {
      _arenas.remove(pointer);
      assert(_debugLogDiagnostic(pointer, 'Arena empty.'));
    } else if (state.eagerWinner != null) {
      assert(_debugLogDiagnostic(pointer, 'Eager winner: ${state.eagerWinner}'));
238
      _resolveInFavorOf(pointer, state, state.eagerWinner!);
239 240 241 242 243
    }
  }

  void _resolveByDefault(int pointer, _GestureArena state) {
    if (!_arenas.containsKey(pointer))
244
      return; // Already resolved earlier.
245 246 247 248 249 250 251 252 253
    assert(_arenas[pointer] == state);
    assert(!state.isOpen);
    final List<GestureArenaMember> members = state.members;
    assert(members.length == 1);
    _arenas.remove(pointer);
    assert(_debugLogDiagnostic(pointer, 'Default winner: ${state.members.first}'));
    state.members.first.acceptGesture(pointer);
  }

254 255
  void _resolveInFavorOf(int pointer, _GestureArena state, GestureArenaMember member) {
    assert(state == _arenas[pointer]);
Hixie's avatar
Hixie committed
256 257 258
    assert(state != null);
    assert(state.eagerWinner == null || state.eagerWinner == member);
    assert(!state.isOpen);
259
    _arenas.remove(pointer);
260
    for (final GestureArenaMember rejectedMember in state.members) {
Hixie's avatar
Hixie committed
261
      if (rejectedMember != member)
262
        rejectedMember.rejectGesture(pointer);
Hixie's avatar
Hixie committed
263
    }
264
    member.acceptGesture(pointer);
Hixie's avatar
Hixie committed
265
  }
266

267
  bool _debugLogDiagnostic(int pointer, String message, [ _GestureArena? state ]) {
268 269
    assert(() {
      if (debugPrintGestureArenaDiagnostics) {
270
        final int? count = state != null ? state.members.length : null;
271 272 273 274
        final String s = count != 1 ? 's' : '';
        debugPrint('Gesture arena ${pointer.toString().padRight(4)}$message${ count != null ? " with $count member$s." : ""}');
      }
      return true;
275
    }());
276 277
    return true;
  }
Ian Hickson's avatar
Ian Hickson committed
278
}