pointer_router.dart 1.62 KB
Newer Older
Adam Barth's avatar
Adam Barth committed
1 2 3 4
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

Kris Giesing's avatar
Kris Giesing committed
5
import 'events.dart';
Adam Barth's avatar
Adam Barth committed
6

7 8
/// A callback that receives a [PointerInputEvent]
typedef void PointerRoute(PointerInputEvent event);
Adam Barth's avatar
Adam Barth committed
9

10
/// A routing table for [PointerInputEvent] events.
11
class PointerRouter {
Adam Barth's avatar
Adam Barth committed
12
  final Map<int, List<PointerRoute>> _routeMap = new Map<int, List<PointerRoute>>();
Adam Barth's avatar
Adam Barth committed
13

Adam Barth's avatar
Adam Barth committed
14 15
  /// Adds a route to the routing table
  ///
16
  /// Whenever this object routes a [PointerInputEvent] corresponding to
Adam Barth's avatar
Adam Barth committed
17 18 19
  /// pointer, call route.
  void addRoute(int pointer, PointerRoute route) {
    List<PointerRoute> routes = _routeMap.putIfAbsent(pointer, () => new List<PointerRoute>());
Adam Barth's avatar
Adam Barth committed
20 21 22 23
    assert(!routes.contains(route));
    routes.add(route);
  }

Adam Barth's avatar
Adam Barth committed
24 25
  /// Removes a route from the routing table
  ///
26
  /// No longer call route when routing a [PointerInputEvent] corresponding to
Adam Barth's avatar
Adam Barth committed
27 28
  /// pointer. Requires that this route was previously added to the router.
  void removeRoute(int pointer, PointerRoute route) {
Adam Barth's avatar
Adam Barth committed
29
    assert(_routeMap.containsKey(pointer));
Adam Barth's avatar
Adam Barth committed
30
    List<PointerRoute> routes = _routeMap[pointer];
Adam Barth's avatar
Adam Barth committed
31 32 33 34 35 36
    assert(routes.contains(route));
    routes.remove(route);
    if (routes.isEmpty)
      _routeMap.remove(pointer);
  }

Adam Barth's avatar
Adam Barth committed
37 38 39
  /// Call the routes registed for this pointer event.
  ///
  /// Calls the routes in the order in which they were added to the route.
40
  void route(PointerInputEvent event) {
Adam Barth's avatar
Adam Barth committed
41
    List<PointerRoute> routes = _routeMap[event.pointer];
Adam Barth's avatar
Adam Barth committed
42
    if (routes == null)
43
      return;
Adam Barth's avatar
Adam Barth committed
44
    for (PointerRoute route in new List<PointerRoute>.from(routes))
Adam Barth's avatar
Adam Barth committed
45 46 47
      route(event);
  }
}