OLD | NEW |
| (Empty) |
1 // Copyright (c) 2013, 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 library observe.src.path_observer; | |
6 | |
7 import 'dart:async'; | |
8 import 'dart:collection'; | |
9 import 'dart:math' show min; | |
10 | |
11 import 'package:logging/logging.dart' show Logger, Level; | |
12 import 'package:observe/observe.dart'; | |
13 import 'package:smoke/smoke.dart' as smoke; | |
14 | |
15 import 'package:utf/utf.dart' show stringToCodepoints; | |
16 | |
17 /// A data-bound path starting from a view-model or model object, for example | |
18 /// `foo.bar.baz`. | |
19 /// | |
20 /// When [open] is called, this will observe changes to the object and any | |
21 /// intermediate object along the path, and send updated values accordingly. | |
22 /// When [close] is called it will stop observing the objects. | |
23 /// | |
24 /// This class is used to implement `Node.bind` and similar functionality in | |
25 /// the [template_binding](pub.dartlang.org/packages/template_binding) package. | |
26 class PathObserver extends _Observer implements Bindable { | |
27 PropertyPath _path; | |
28 Object _object; | |
29 _ObservedSet _directObserver; | |
30 | |
31 /// Observes [path] on [object] for changes. This returns an object | |
32 /// that can be used to get the changes and get/set the value at this path. | |
33 /// | |
34 /// The path can be a [PropertyPath], or a [String] used to construct it. | |
35 /// | |
36 /// See [open] and [value]. | |
37 PathObserver(Object object, [path]) | |
38 : _object = object, | |
39 _path = new PropertyPath(path); | |
40 | |
41 PropertyPath get path => _path; | |
42 | |
43 /// Sets the value at this path. | |
44 void set value(Object newValue) { | |
45 if (_path != null) _path.setValueFrom(_object, newValue); | |
46 } | |
47 | |
48 int get _reportArgumentCount => 2; | |
49 | |
50 /// Initiates observation and returns the initial value. | |
51 /// The callback will be passed the updated [value], and may optionally be | |
52 /// declared to take a second argument, which will contain the previous value. | |
53 open(callback) => super.open(callback); | |
54 | |
55 void _connect() { | |
56 _directObserver = new _ObservedSet(this, _object); | |
57 _check(skipChanges: true); | |
58 } | |
59 | |
60 void _disconnect() { | |
61 _value = null; | |
62 if (_directObserver != null) { | |
63 _directObserver.close(this); | |
64 _directObserver = null; | |
65 } | |
66 // Dart note: the JS impl does not do this, but it seems consistent with | |
67 // CompoundObserver. After closing the PathObserver can't be reopened. | |
68 _path = null; | |
69 _object = null; | |
70 } | |
71 | |
72 void _iterateObjects(void observe(obj, prop)) { | |
73 _path._iterateObjects(_object, observe); | |
74 } | |
75 | |
76 bool _check({bool skipChanges: false}) { | |
77 var oldValue = _value; | |
78 _value = _path.getValueFrom(_object); | |
79 if (skipChanges || _value == oldValue) return false; | |
80 | |
81 _report(_value, oldValue, this); | |
82 return true; | |
83 } | |
84 } | |
85 | |
86 /// A dot-delimieted property path such as "foo.bar" or "foo.10.bar". | |
87 /// | |
88 /// The path specifies how to get a particular value from an object graph, where | |
89 /// the graph can include arrays and maps. Each segment of the path describes | |
90 /// how to take a single step in the object graph. Properties like 'foo' or | |
91 /// 'bar' are read as properties on objects, or as keys if the object is a [Map] | |
92 /// or a [Indexable], while integer values are read as indexes in a [List]. | |
93 // TODO(jmesserly): consider specialized subclasses for: | |
94 // * empty path | |
95 // * "value" | |
96 // * single token in path, e.g. "foo" | |
97 class PropertyPath { | |
98 /// The segments of the path. | |
99 final List<Object> _segments; | |
100 | |
101 /// Creates a new [PropertyPath]. These can be stored to avoid excessive | |
102 /// parsing of path strings. | |
103 /// | |
104 /// The provided [path] should be a String or a List. If it is a list it | |
105 /// should contain only Symbols and integers. This can be used to avoid | |
106 /// parsing. | |
107 /// | |
108 /// Note that this constructor will canonicalize identical paths in some cases | |
109 /// to save memory, but this is not guaranteed. Use [==] for comparions | |
110 /// purposes instead of [identical]. | |
111 // Dart note: this is ported from `function getPath`. | |
112 factory PropertyPath([path]) { | |
113 if (path is PropertyPath) return path; | |
114 if (path == null || (path is List && path.isEmpty)) path = ''; | |
115 | |
116 if (path is List) { | |
117 var copy = new List.from(path, growable: false); | |
118 for (var segment in copy) { | |
119 // Dart note: unlike Javascript, we don't support arbitraty objects that | |
120 // can be converted to a String. | |
121 // TODO(sigmund): consider whether we should support that here. It might | |
122 // be easier to add support for that if we switch first to use strings | |
123 // for everything instead of symbols. | |
124 if (segment is! int && segment is! String && segment is! Symbol) { | |
125 throw new ArgumentError( | |
126 'List must contain only ints, Strings, and Symbols'); | |
127 } | |
128 } | |
129 return new PropertyPath._(copy); | |
130 } | |
131 | |
132 var pathObj = _pathCache[path]; | |
133 if (pathObj != null) return pathObj; | |
134 | |
135 | |
136 final segments = new _PathParser().parse(path); | |
137 if (segments == null) return _InvalidPropertyPath._instance; | |
138 | |
139 // TODO(jmesserly): we could use an UnmodifiableListView here, but that adds | |
140 // memory overhead. | |
141 pathObj = new PropertyPath._(segments.toList(growable: false)); | |
142 if (_pathCache.length >= _pathCacheLimit) { | |
143 _pathCache.remove(_pathCache.keys.first); | |
144 } | |
145 _pathCache[path] = pathObj; | |
146 return pathObj; | |
147 } | |
148 | |
149 PropertyPath._(this._segments); | |
150 | |
151 int get length => _segments.length; | |
152 bool get isEmpty => _segments.isEmpty; | |
153 bool get isValid => true; | |
154 | |
155 String toString() { | |
156 if (!isValid) return '<invalid path>'; | |
157 var sb = new StringBuffer(); | |
158 bool first = true; | |
159 for (var key in _segments) { | |
160 if (key is Symbol) { | |
161 if (!first) sb.write('.'); | |
162 sb.write(smoke.symbolToName(key)); | |
163 } else { | |
164 _formatAccessor(sb, key); | |
165 } | |
166 first = false; | |
167 } | |
168 return sb.toString(); | |
169 } | |
170 | |
171 _formatAccessor(StringBuffer sb, Object key) { | |
172 if (key is int) { | |
173 sb.write('[$key]'); | |
174 } else { | |
175 sb.write('["${key.toString().replaceAll('"', '\\"')}"]'); | |
176 } | |
177 } | |
178 | |
179 bool operator ==(other) { | |
180 if (identical(this, other)) return true; | |
181 if (other is! PropertyPath) return false; | |
182 if (isValid != other.isValid) return false; | |
183 | |
184 int len = _segments.length; | |
185 if (len != other._segments.length) return false; | |
186 for (int i = 0; i < len; i++) { | |
187 if (_segments[i] != other._segments[i]) return false; | |
188 } | |
189 return true; | |
190 } | |
191 | |
192 /// This is the [Jenkins hash function][1] but using masking to keep | |
193 /// values in SMI range. | |
194 /// [1]: http://en.wikipedia.org/wiki/Jenkins_hash_function | |
195 // TODO(jmesserly): should reuse this instead, see | |
196 // https://code.google.com/p/dart/issues/detail?id=11617 | |
197 int get hashCode { | |
198 int hash = 0; | |
199 for (int i = 0, len = _segments.length; i < len; i++) { | |
200 hash = 0x1fffffff & (hash + _segments[i].hashCode); | |
201 hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10)); | |
202 hash = hash ^ (hash >> 6); | |
203 } | |
204 hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3)); | |
205 hash = hash ^ (hash >> 11); | |
206 return 0x1fffffff & (hash + ((0x00003fff & hash) << 15)); | |
207 } | |
208 | |
209 /// Returns the current value of the path from the provided [obj]ect. | |
210 getValueFrom(Object obj) { | |
211 if (!isValid) return null; | |
212 for (var segment in _segments) { | |
213 if (obj == null) return null; | |
214 obj = _getObjectProperty(obj, segment); | |
215 } | |
216 return obj; | |
217 } | |
218 | |
219 /// Attempts to set the [value] of the path from the provided [obj]ect. | |
220 /// Returns true if and only if the path was reachable and set. | |
221 bool setValueFrom(Object obj, Object value) { | |
222 var end = _segments.length - 1; | |
223 if (end < 0) return false; | |
224 for (int i = 0; i < end; i++) { | |
225 if (obj == null) return false; | |
226 obj = _getObjectProperty(obj, _segments[i]); | |
227 } | |
228 return _setObjectProperty(obj, _segments[end], value); | |
229 } | |
230 | |
231 void _iterateObjects(Object obj, void observe(obj, prop)) { | |
232 if (!isValid || isEmpty) return; | |
233 | |
234 int i = 0, last = _segments.length - 1; | |
235 while (obj != null) { | |
236 // _segments[i] is passed to indicate that we are only observing that | |
237 // property of obj. See observe declaration in _ObservedSet. | |
238 observe(obj, _segments[i]); | |
239 | |
240 if (i >= last) break; | |
241 obj = _getObjectProperty(obj, _segments[i++]); | |
242 } | |
243 } | |
244 | |
245 // Dart note: it doesn't make sense to have compiledGetValueFromFn in Dart. | |
246 } | |
247 | |
248 | |
249 /// Visible only for testing: | |
250 getSegmentsOfPropertyPathForTesting(p) => p._segments; | |
251 | |
252 class _InvalidPropertyPath extends PropertyPath { | |
253 static final _instance = new _InvalidPropertyPath(); | |
254 | |
255 bool get isValid => false; | |
256 _InvalidPropertyPath() : super._([]); | |
257 } | |
258 | |
259 bool _changeRecordMatches(record, key) { | |
260 if (record is PropertyChangeRecord) { | |
261 return (record as PropertyChangeRecord).name == key; | |
262 } | |
263 if (record is MapChangeRecord) { | |
264 if (key is Symbol) key = smoke.symbolToName(key); | |
265 return (record as MapChangeRecord).key == key; | |
266 } | |
267 return false; | |
268 } | |
269 | |
270 /// Properties in [Map] that need to be read as properties and not as keys in | |
271 /// the map. We exclude methods ('containsValue', 'containsKey', 'putIfAbsent', | |
272 /// 'addAll', 'remove', 'clear', 'forEach') because there is no use in reading | |
273 /// them as part of path-observer segments. | |
274 const _MAP_PROPERTIES = const [#keys, #values, #length, #isEmpty, #isNotEmpty]; | |
275 | |
276 _getObjectProperty(object, property) { | |
277 if (object == null) return null; | |
278 | |
279 if (property is int) { | |
280 if (object is List && property >= 0 && property < object.length) { | |
281 return object[property]; | |
282 } | |
283 } else if (property is String) { | |
284 return object[property]; | |
285 } else if (property is Symbol) { | |
286 // Support indexer if available, e.g. Maps or polymer_expressions Scope. | |
287 // This is the default syntax used by polymer/nodebind and | |
288 // polymer/observe-js PathObserver. | |
289 // TODO(sigmund): should we also support using checking dynamically for | |
290 // whether the type practically implements the indexer API | |
291 // (smoke.hasInstanceMethod(type, const Symbol('[]')))? | |
292 if (object is Indexable<String, dynamic> || | |
293 object is Map<String, dynamic> && !_MAP_PROPERTIES.contains(property)) { | |
294 return object[smoke.symbolToName(property)]; | |
295 } | |
296 try { | |
297 return smoke.read(object, property); | |
298 } on NoSuchMethodError catch (e) { | |
299 // Rethrow, unless the type implements noSuchMethod, in which case we | |
300 // interpret the exception as a signal that the method was not found. | |
301 // Dart note: getting invalid properties is an error, unlike in JS where | |
302 // it returns undefined. | |
303 if (!smoke.hasNoSuchMethod(object.runtimeType)) rethrow; | |
304 } | |
305 } | |
306 | |
307 if (_logger.isLoggable(Level.FINER)) { | |
308 _logger.finer("can't get $property in $object"); | |
309 } | |
310 return null; | |
311 } | |
312 | |
313 bool _setObjectProperty(object, property, value) { | |
314 if (object == null) return false; | |
315 | |
316 if (property is int) { | |
317 if (object is List && property >= 0 && property < object.length) { | |
318 object[property] = value; | |
319 return true; | |
320 } | |
321 } else if (property is Symbol) { | |
322 // Support indexer if available, e.g. Maps or polymer_expressions Scope. | |
323 if (object is Indexable<String, dynamic> || | |
324 object is Map<String, dynamic> && !_MAP_PROPERTIES.contains(property)) { | |
325 object[smoke.symbolToName(property)] = value; | |
326 return true; | |
327 } | |
328 try { | |
329 smoke.write(object, property, value); | |
330 return true; | |
331 } on NoSuchMethodError catch (e, s) { | |
332 if (!smoke.hasNoSuchMethod(object.runtimeType)) rethrow; | |
333 } | |
334 } | |
335 | |
336 if (_logger.isLoggable(Level.FINER)) { | |
337 _logger.finer("can't set $property in $object"); | |
338 } | |
339 return false; | |
340 } | |
341 | |
342 // From: https://github.com/rafaelw/ChangeSummary/blob/master/change_summary.js | |
343 | |
344 final _identRegExp = () { | |
345 const identStart = '[\$_a-zA-Z]'; | |
346 const identPart = '[\$_a-zA-Z0-9]'; | |
347 return new RegExp('^$identStart+$identPart*\$'); | |
348 }(); | |
349 | |
350 _isIdent(s) => _identRegExp.hasMatch(s); | |
351 | |
352 // Dart note: refactored to convert to codepoints once and operate on codepoints | |
353 // rather than characters. | |
354 class _PathParser { | |
355 List keys = []; | |
356 int index = -1; | |
357 String key; | |
358 | |
359 final Map<String, List<String>> _pathStateMachine = { | |
360 'beforePath': { | |
361 'ws': ['beforePath'], | |
362 'ident': ['inIdent', 'append'], | |
363 '[': ['beforeElement'], | |
364 'eof': ['afterPath'] | |
365 }, | |
366 | |
367 'inPath': { | |
368 'ws': ['inPath'], | |
369 '.': ['beforeIdent'], | |
370 '[': ['beforeElement'], | |
371 'eof': ['afterPath'] | |
372 }, | |
373 | |
374 'beforeIdent': { | |
375 'ws': ['beforeIdent'], | |
376 'ident': ['inIdent', 'append'] | |
377 }, | |
378 | |
379 'inIdent': { | |
380 'ident': ['inIdent', 'append'], | |
381 '0': ['inIdent', 'append'], | |
382 'number': ['inIdent', 'append'], | |
383 'ws': ['inPath', 'push'], | |
384 '.': ['beforeIdent', 'push'], | |
385 '[': ['beforeElement', 'push'], | |
386 'eof': ['afterPath', 'push'] | |
387 }, | |
388 | |
389 'beforeElement': { | |
390 'ws': ['beforeElement'], | |
391 '0': ['afterZero', 'append'], | |
392 'number': ['inIndex', 'append'], | |
393 "'": ['inSingleQuote', 'append', ''], | |
394 '"': ['inDoubleQuote', 'append', ''] | |
395 }, | |
396 | |
397 'afterZero': { | |
398 'ws': ['afterElement', 'push'], | |
399 ']': ['inPath', 'push'] | |
400 }, | |
401 | |
402 'inIndex': { | |
403 '0': ['inIndex', 'append'], | |
404 'number': ['inIndex', 'append'], | |
405 'ws': ['afterElement'], | |
406 ']': ['inPath', 'push'] | |
407 }, | |
408 | |
409 'inSingleQuote': { | |
410 "'": ['afterElement'], | |
411 'eof': ['error'], | |
412 'else': ['inSingleQuote', 'append'] | |
413 }, | |
414 | |
415 'inDoubleQuote': { | |
416 '"': ['afterElement'], | |
417 'eof': ['error'], | |
418 'else': ['inDoubleQuote', 'append'] | |
419 }, | |
420 | |
421 'afterElement': { | |
422 'ws': ['afterElement'], | |
423 ']': ['inPath', 'push'] | |
424 } | |
425 }; | |
426 | |
427 /// From getPathCharType: determines the type of a given [code]point. | |
428 String _getPathCharType(code) { | |
429 if (code == null) return 'eof'; | |
430 switch(code) { | |
431 case 0x5B: // [ | |
432 case 0x5D: // ] | |
433 case 0x2E: // . | |
434 case 0x22: // " | |
435 case 0x27: // ' | |
436 case 0x30: // 0 | |
437 return _char(code); | |
438 | |
439 case 0x5F: // _ | |
440 case 0x24: // $ | |
441 return 'ident'; | |
442 | |
443 case 0x20: // Space | |
444 case 0x09: // Tab | |
445 case 0x0A: // Newline | |
446 case 0x0D: // Return | |
447 case 0xA0: // No-break space | |
448 case 0xFEFF: // Byte Order Mark | |
449 case 0x2028: // Line Separator | |
450 case 0x2029: // Paragraph Separator | |
451 return 'ws'; | |
452 } | |
453 | |
454 // a-z, A-Z | |
455 if ((0x61 <= code && code <= 0x7A) || (0x41 <= code && code <= 0x5A)) | |
456 return 'ident'; | |
457 | |
458 // 1-9 | |
459 if (0x31 <= code && code <= 0x39) | |
460 return 'number'; | |
461 | |
462 return 'else'; | |
463 } | |
464 | |
465 static String _char(int codepoint) => new String.fromCharCodes([codepoint]); | |
466 | |
467 void push() { | |
468 if (key == null) return; | |
469 | |
470 // Dart note: we store the keys with different types, rather than | |
471 // parsing/converting things later in toString. | |
472 if (_isIdent(key)) { | |
473 keys.add(smoke.nameToSymbol(key)); | |
474 } else { | |
475 var index = int.parse(key, radix: 10, onError: (_) => null); | |
476 keys.add(index != null ? index : key); | |
477 } | |
478 key = null; | |
479 } | |
480 | |
481 void append(newChar) { | |
482 key = (key == null) ? newChar : '$key$newChar'; | |
483 } | |
484 | |
485 bool _maybeUnescapeQuote(String mode, codePoints) { | |
486 if (index >= codePoints.length) return false; | |
487 var nextChar = _char(codePoints[index + 1]); | |
488 if ((mode == 'inSingleQuote' && nextChar == "'") || | |
489 (mode == 'inDoubleQuote' && nextChar == '"')) { | |
490 index++; | |
491 append(nextChar); | |
492 return true; | |
493 } | |
494 return false; | |
495 } | |
496 | |
497 /// Returns the parsed keys, or null if there was a parse error. | |
498 List<String> parse(String path) { | |
499 var codePoints = stringToCodepoints(path); | |
500 var mode = 'beforePath'; | |
501 | |
502 while (mode != null) { | |
503 index++; | |
504 var c = index >= codePoints.length ? null : codePoints[index]; | |
505 | |
506 if (c != null && | |
507 _char(c) == '\\' && _maybeUnescapeQuote(mode, codePoints)) continue; | |
508 | |
509 var type = _getPathCharType(c); | |
510 if (mode == 'error') return null; | |
511 | |
512 var typeMap = _pathStateMachine[mode]; | |
513 var transition = typeMap[type]; | |
514 if (transition == null) transition = typeMap['else']; | |
515 if (transition == null) return null; // parse error; | |
516 | |
517 mode = transition[0]; | |
518 var actionName = transition.length > 1 ? transition[1] : null; | |
519 if (actionName == 'push' && key != null) push(); | |
520 if (actionName == 'append') { | |
521 var newChar = transition.length > 2 && transition[2] != null | |
522 ? transition[2] : _char(c); | |
523 append(newChar); | |
524 } | |
525 | |
526 if (mode == 'afterPath') return keys; | |
527 } | |
528 return null; // parse error | |
529 } | |
530 } | |
531 | |
532 final Logger _logger = new Logger('observe.PathObserver'); | |
533 | |
534 | |
535 /// This is a simple cache. It's like LRU but we don't update an item on a | |
536 /// cache hit, because that would require allocation. Better to let it expire | |
537 /// and reallocate the PropertyPath. | |
538 // TODO(jmesserly): this optimization is from observe-js, how valuable is it in | |
539 // practice? | |
540 final _pathCache = new LinkedHashMap<String, PropertyPath>(); | |
541 | |
542 /// The size of a path like "foo.bar" is approximately 160 bytes, so this | |
543 /// reserves ~16Kb of memory for recently used paths. Since paths are frequently | |
544 /// reused, the theory is that this ends up being a good tradeoff in practice. | |
545 // (Note: the 160 byte estimate is from Dart VM 1.0.0.10_r30798 on x64 without | |
546 // using UnmodifiableListView in PropertyPath) | |
547 const int _pathCacheLimit = 100; | |
548 | |
549 /// [CompoundObserver] is a [Bindable] object which knows how to listen to | |
550 /// multiple values (registered via [addPath] or [addObserver]) and invoke a | |
551 /// callback when one or more of the values have changed. | |
552 /// | |
553 /// var obj = new ObservableMap.from({'a': 1, 'b': 2}); | |
554 /// var otherObj = new ObservableMap.from({'c': 3}); | |
555 /// | |
556 /// var observer = new CompoundObserver() | |
557 /// ..addPath(obj, 'a'); | |
558 /// ..addObserver(new PathObserver(obj, 'b')); | |
559 /// ..addPath(otherObj, 'c'); | |
560 /// ..open((values) { | |
561 /// for (int i = 0; i < values.length; i++) { | |
562 /// print('The value at index $i is now ${values[i]}'); | |
563 /// } | |
564 /// }); | |
565 /// | |
566 /// obj['a'] = 10; // print will be triggered async | |
567 /// | |
568 class CompoundObserver extends _Observer implements Bindable { | |
569 _ObservedSet _directObserver; | |
570 bool _reportChangesOnOpen; | |
571 List _observed = []; | |
572 | |
573 CompoundObserver([this._reportChangesOnOpen = false]) { | |
574 _value = []; | |
575 } | |
576 | |
577 int get _reportArgumentCount => 3; | |
578 | |
579 /// Initiates observation and returns the initial value. | |
580 /// The callback will be passed the updated [value], and may optionally be | |
581 /// declared to take a second argument, which will contain the previous value. | |
582 /// | |
583 /// Implementation note: a third argument can also be declared, which will | |
584 /// receive a list of objects and paths, such that `list[2 * i]` will access | |
585 /// the object and `list[2 * i + 1]` will access the path, where `i` is the | |
586 /// order of the [addPath] call. This parameter is only used by | |
587 /// `package:polymer` as a performance optimization, and should not be relied | |
588 /// on in new code. | |
589 open(callback) => super.open(callback); | |
590 | |
591 void _connect() { | |
592 for (var i = 0; i < _observed.length; i += 2) { | |
593 var object = _observed[i]; | |
594 if (!identical(object, _observerSentinel)) { | |
595 _directObserver = new _ObservedSet(this, object); | |
596 break; | |
597 } | |
598 } | |
599 | |
600 _check(skipChanges: !_reportChangesOnOpen); | |
601 } | |
602 | |
603 void _disconnect() { | |
604 for (var i = 0; i < _observed.length; i += 2) { | |
605 if (identical(_observed[i], _observerSentinel)) { | |
606 _observed[i + 1].close(); | |
607 } | |
608 } | |
609 | |
610 _observed = null; | |
611 _value = null; | |
612 | |
613 if (_directObserver != null) { | |
614 _directObserver.close(this); | |
615 _directObserver = null; | |
616 } | |
617 } | |
618 | |
619 /// Adds a dependency on the property [path] accessed from [object]. | |
620 /// [path] can be a [PropertyPath] or a [String]. If it is omitted an empty | |
621 /// path will be used. | |
622 void addPath(Object object, [path]) { | |
623 if (_isOpen || _isClosed) { | |
624 throw new StateError('Cannot add paths once started.'); | |
625 } | |
626 | |
627 path = new PropertyPath(path); | |
628 _observed..add(object)..add(path); | |
629 if (!_reportChangesOnOpen) return; | |
630 _value.add(path.getValueFrom(object)); | |
631 } | |
632 | |
633 void addObserver(Bindable observer) { | |
634 if (_isOpen || _isClosed) { | |
635 throw new StateError('Cannot add observers once started.'); | |
636 } | |
637 | |
638 _observed..add(_observerSentinel)..add(observer); | |
639 if (!_reportChangesOnOpen) return; | |
640 _value.add(observer.open((_) => deliver())); | |
641 } | |
642 | |
643 void _iterateObjects(void observe(obj, prop)) { | |
644 for (var i = 0; i < _observed.length; i += 2) { | |
645 var object = _observed[i]; | |
646 if (!identical(object, _observerSentinel)) { | |
647 (_observed[i + 1] as PropertyPath)._iterateObjects(object, observe); | |
648 } | |
649 } | |
650 } | |
651 | |
652 bool _check({bool skipChanges: false}) { | |
653 bool changed = false; | |
654 _value.length = _observed.length ~/ 2; | |
655 var oldValues = null; | |
656 for (var i = 0; i < _observed.length; i += 2) { | |
657 var object = _observed[i]; | |
658 var path = _observed[i + 1]; | |
659 var value; | |
660 if (identical(object, _observerSentinel)) { | |
661 var observable = path as Bindable; | |
662 value = _state == _Observer._UNOPENED ? | |
663 observable.open((_) => this.deliver()) : | |
664 observable.value; | |
665 } else { | |
666 value = (path as PropertyPath).getValueFrom(object); | |
667 } | |
668 | |
669 if (skipChanges) { | |
670 _value[i ~/ 2] = value; | |
671 continue; | |
672 } | |
673 | |
674 if (value == _value[i ~/ 2]) continue; | |
675 | |
676 // don't allocate this unless necessary. | |
677 if (_notifyArgumentCount >= 2) { | |
678 if (oldValues == null) oldValues = new Map(); | |
679 oldValues[i ~/ 2] = _value[i ~/ 2]; | |
680 } | |
681 | |
682 changed = true; | |
683 _value[i ~/ 2] = value; | |
684 } | |
685 | |
686 if (!changed) return false; | |
687 | |
688 // TODO(rafaelw): Having _observed as the third callback arg here is | |
689 // pretty lame API. Fix. | |
690 _report(_value, oldValues, _observed); | |
691 return true; | |
692 } | |
693 } | |
694 | |
695 /// An object accepted by [PropertyPath] where properties are read and written | |
696 /// as indexing operations, just like a [Map]. | |
697 abstract class Indexable<K, V> { | |
698 V operator [](K key); | |
699 operator []=(K key, V value); | |
700 } | |
701 | |
702 const _observerSentinel = const _ObserverSentinel(); | |
703 class _ObserverSentinel { const _ObserverSentinel(); } | |
704 | |
705 // Visible for testing | |
706 get observerSentinelForTesting => _observerSentinel; | |
707 | |
708 // A base class for the shared API implemented by PathObserver and | |
709 // CompoundObserver and used in _ObservedSet. | |
710 abstract class _Observer extends Bindable { | |
711 Function _notifyCallback; | |
712 int _notifyArgumentCount; | |
713 var _value; | |
714 | |
715 // abstract members | |
716 void _iterateObjects(void observe(obj, prop)); | |
717 void _connect(); | |
718 void _disconnect(); | |
719 bool _check({bool skipChanges: false}); | |
720 | |
721 static int _UNOPENED = 0; | |
722 static int _OPENED = 1; | |
723 static int _CLOSED = 2; | |
724 int _state = _UNOPENED; | |
725 bool get _isOpen => _state == _OPENED; | |
726 bool get _isClosed => _state == _CLOSED; | |
727 | |
728 /// The number of arguments the subclass will pass to [_report]. | |
729 int get _reportArgumentCount; | |
730 | |
731 open(callback) { | |
732 if (_isOpen || _isClosed) { | |
733 throw new StateError('Observer has already been opened.'); | |
734 } | |
735 | |
736 if (smoke.minArgs(callback) > _reportArgumentCount) { | |
737 throw new ArgumentError('callback should take $_reportArgumentCount or ' | |
738 'fewer arguments'); | |
739 } | |
740 | |
741 _notifyCallback = callback; | |
742 _notifyArgumentCount = min(_reportArgumentCount, smoke.maxArgs(callback)); | |
743 | |
744 _connect(); | |
745 _state = _OPENED; | |
746 return _value; | |
747 } | |
748 | |
749 get value => _discardChanges(); | |
750 | |
751 void close() { | |
752 if (!_isOpen) return; | |
753 | |
754 _disconnect(); | |
755 _value = null; | |
756 _notifyCallback = null; | |
757 _state = _CLOSED; | |
758 } | |
759 | |
760 _discardChanges() { | |
761 _check(skipChanges: true); | |
762 return _value; | |
763 } | |
764 | |
765 void deliver() { | |
766 if (_isOpen) _dirtyCheck(); | |
767 } | |
768 | |
769 bool _dirtyCheck() { | |
770 var cycles = 0; | |
771 while (cycles < _MAX_DIRTY_CHECK_CYCLES && _check()) { | |
772 cycles++; | |
773 } | |
774 return cycles > 0; | |
775 } | |
776 | |
777 void _report(newValue, oldValue, [extraArg]) { | |
778 try { | |
779 switch (_notifyArgumentCount) { | |
780 case 0: _notifyCallback(); break; | |
781 case 1: _notifyCallback(newValue); break; | |
782 case 2: _notifyCallback(newValue, oldValue); break; | |
783 case 3: _notifyCallback(newValue, oldValue, extraArg); break; | |
784 } | |
785 } catch (e, s) { | |
786 // Deliver errors async, so if a single callback fails it doesn't prevent | |
787 // other things from working. | |
788 new Completer().completeError(e, s); | |
789 } | |
790 } | |
791 } | |
792 | |
793 /// The observedSet abstraction is a perf optimization which reduces the total | |
794 /// number of Object.observe observations of a set of objects. The idea is that | |
795 /// groups of Observers will have some object dependencies in common and this | |
796 /// observed set ensures that each object in the transitive closure of | |
797 /// dependencies is only observed once. The observedSet acts as a write barrier | |
798 /// such that whenever any change comes through, all Observers are checked for | |
799 /// changed values. | |
800 /// | |
801 /// Note that this optimization is explicitly moving work from setup-time to | |
802 /// change-time. | |
803 /// | |
804 /// TODO(rafaelw): Implement "garbage collection". In order to move work off | |
805 /// the critical path, when Observers are closed, their observed objects are | |
806 /// not Object.unobserve(d). As a result, it's possible that if the observedSet | |
807 /// is kept open, but some Observers have been closed, it could cause "leaks" | |
808 /// (prevent otherwise collectable objects from being collected). At some | |
809 /// point, we should implement incremental "gc" which keeps a list of | |
810 /// observedSets which may need clean-up and does small amounts of cleanup on a | |
811 /// timeout until all is clean. | |
812 class _ObservedSet { | |
813 /// To prevent sequential [PathObserver]s and [CompoundObserver]s from | |
814 /// observing the same object, we check if they are observing the same root | |
815 /// as the most recently created observer, and if so merge it into the | |
816 /// existing _ObservedSet. | |
817 /// | |
818 /// See <https://github.com/Polymer/observe-js/commit/f0990b1> and | |
819 /// <https://codereview.appspot.com/46780044/>. | |
820 static _ObservedSet _lastSet; | |
821 | |
822 /// The root object for a [PathObserver]. For a [CompoundObserver], the root | |
823 /// object of the first path observed. This is used by the constructor to | |
824 /// reuse an [_ObservedSet] that starts from the same object. | |
825 Object _rootObject; | |
826 | |
827 /// Subset of properties in [_rootObject] that we care about. | |
828 Set _rootObjectProperties; | |
829 | |
830 /// Observers associated with this root object, in birth order. | |
831 final List<_Observer> _observers = []; | |
832 | |
833 // Dart note: the JS implementation is O(N^2) because Array.indexOf is used | |
834 // for lookup in this array. We use HashMap to avoid this problem. It | |
835 // also gives us a nice way of tracking the StreamSubscription. | |
836 Map<Object, StreamSubscription> _objects; | |
837 | |
838 factory _ObservedSet(_Observer observer, Object rootObject) { | |
839 if (_lastSet == null || !identical(_lastSet._rootObject, rootObject)) { | |
840 _lastSet = new _ObservedSet._(rootObject); | |
841 } | |
842 _lastSet.open(observer, rootObject); | |
843 } | |
844 | |
845 _ObservedSet._(rootObject) | |
846 : _rootObject = rootObject, | |
847 _rootObjectProperties = rootObject == null ? null : new Set(); | |
848 | |
849 void open(_Observer obs, Object rootObject) { | |
850 if (_rootObject == null) { | |
851 _rootObject = rootObject; | |
852 _rootObjectProperties = new Set(); | |
853 } | |
854 | |
855 _observers.add(obs); | |
856 obs._iterateObjects(observe); | |
857 } | |
858 | |
859 void close(_Observer obs) { | |
860 if (_observers.isNotEmpty) return; | |
861 | |
862 if (_objects != null) { | |
863 for (var sub in _objects) sub.cancel(); | |
864 _objects = null; | |
865 } | |
866 _rootObject = null; | |
867 _rootObjectProperties = null; | |
868 if (identical(_lastSet, this)) _lastSet = null; | |
869 } | |
870 | |
871 /// Observe now takes a second argument to indicate which property of an | |
872 /// object is being observed, so we don't trigger change notifications on | |
873 /// changes to unrelated properties. | |
874 void observe(Object obj, Object prop) { | |
875 if (identical(obj, _rootObject)) _rootObjectProperties.add(prop); | |
876 if (obj is ObservableList) _observeStream(obj.listChanges); | |
877 if (obj is Observable) _observeStream(obj.changes); | |
878 } | |
879 | |
880 void _observeStream(Stream stream) { | |
881 // TODO(jmesserly): we hash on streams as we have two separate change | |
882 // streams for ObservableList. Not sure if that is the design we will use | |
883 // going forward. | |
884 | |
885 if (_objects == null) _objects = new HashMap(); | |
886 if (!_objects.containsKey(stream)) { | |
887 _objects[stream] = stream.listen(_callback); | |
888 } | |
889 } | |
890 | |
891 /// Whether we can ignore all change events in [records]. This is true if all | |
892 /// records are for properties in the [_rootObject] and we are not observing | |
893 /// any of those properties. Changes on objects other than [_rootObject], or | |
894 /// changes for properties in [_rootObjectProperties] can't be ignored. | |
895 // Dart note: renamed from `allRootObjNonObservedProps` in the JS code. | |
896 bool _canIgnoreRecords(List<ChangeRecord> records) { | |
897 for (var rec in records) { | |
898 if (rec is PropertyChangeRecord) { | |
899 if (!identical(rec.object, _rootObject) || | |
900 _rootObjectProperties.contains(rec.name)) { | |
901 return false; | |
902 } | |
903 } else if (rec is ListChangeRecord) { | |
904 if (!identical(rec.object, _rootObject) || | |
905 _rootObjectProperties.contains(rec.index)) { | |
906 return false; | |
907 } | |
908 } else { | |
909 // TODO(sigmund): consider adding object to MapChangeRecord, and make | |
910 // this more precise. | |
911 return false; | |
912 } | |
913 } | |
914 return true; | |
915 } | |
916 | |
917 void _callback(records) { | |
918 if (_canIgnoreRecords(records)) return; | |
919 for (var observer in _observers.toList(growable: false)) { | |
920 if (observer._isOpen) observer._iterateObjects(observe); | |
921 } | |
922 | |
923 for (var observer in _observers.toList(growable: false)) { | |
924 if (observer._isOpen) observer._check(); | |
925 } | |
926 } | |
927 } | |
928 | |
929 const int _MAX_DIRTY_CHECK_CYCLES = 1000; | |
OLD | NEW |