OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. |
| 4 |
| 5 import 'dart:html'; |
| 6 import 'dart:collection'; |
| 7 import 'dart:async'; |
| 8 |
| 9 /// A generic rendering task that can be scheduled. |
| 10 abstract class RenderingTask { |
| 11 /// Rendering synchronous callback. |
| 12 void render(); |
| 13 } |
| 14 |
| 15 /// A generic synchronization system for rendering operations. |
| 16 abstract class RenderingBarrier { |
| 17 /// Future to the next synchronization barrier (ms from application start). |
| 18 Future<num> get next; |
| 19 } |
| 20 |
| 21 /// Synchronization system based on the AnimationFrame. |
| 22 class NextAnimationFrameBarrier implements RenderingBarrier { |
| 23 Future<num> get next => window.animationFrame; |
| 24 } |
| 25 |
| 26 /// MOCK synchronization system for manual barrier triggering. |
| 27 class RenderingBarrierMock implements RenderingBarrier { |
| 28 final StreamController<num> _stream = new StreamController<num>.broadcast(); |
| 29 num _ms = 0; |
| 30 |
| 31 Future<num> get next => _stream.stream.first; |
| 32 |
| 33 /// Trigger the next barrier with an optional numer of ms elapsed. |
| 34 void triggerRenderingBarrier({num step: 20}) { |
| 35 assert(step != null); |
| 36 _stream.add(_ms += step); |
| 37 } |
| 38 } |
| 39 |
| 40 /// RenderingTask queuing and synchronization system. |
| 41 class RenderingQueue { |
| 42 final RenderingBarrier _barrier; |
| 43 final Queue<RenderingTask> _queue = new Queue<RenderingTask>(); |
| 44 |
| 45 bool get isEmpty => _queue.isEmpty; |
| 46 bool get isNotEmpty => _queue.isNotEmpty; |
| 47 |
| 48 /// Creates a RenderingQueue with the default synchronization barrier. |
| 49 RenderingQueue() : this.fromBarrier(new NextAnimationFrameBarrier()); |
| 50 |
| 51 /// Creates a RenderingQueue with a custom synchronization barrier. |
| 52 RenderingQueue.fromBarrier(this._barrier) { |
| 53 assert(this._barrier != null); |
| 54 } |
| 55 |
| 56 /// Add a task to the queue. |
| 57 /// If the current rendering phase is running it will be executed during this |
| 58 /// rendering cicle, otherwise it will be queued for the next one. |
| 59 void enqueue(RenderingTask r) { |
| 60 assert(r != null); |
| 61 // If no task are in the queue there is no rendering phase scheduled. |
| 62 if (isEmpty) _render(); |
| 63 _queue.addLast(r); |
| 64 } |
| 65 |
| 66 Future _render() async { |
| 67 await _barrier.next; |
| 68 while (_queue.isNotEmpty) { |
| 69 _queue.removeFirst().render(); |
| 70 } |
| 71 } |
| 72 } |
OLD | NEW |