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(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 || object is Map && !_MAP_PROPERTIES.contains(proper
ty)) { | |
293 return object[smoke.symbolToName(property)]; | |
294 } | |
295 try { | |
296 return smoke.read(object, property); | |
297 } on NoSuchMethodError catch (e) { | |
298 // Rethrow, unless the type implements noSuchMethod, in which case we | |
299 // interpret the exception as a signal that the method was not found. | |
300 // Dart note: getting invalid properties is an error, unlike in JS where | |
301 // it returns undefined. | |
302 if (!smoke.hasNoSuchMethod(object.runtimeType)) rethrow; | |
303 } | |
304 } | |
305 | |
306 if (_logger.isLoggable(Level.FINER)) { | |
307 _logger.finer("can't get $property in $object"); | |
308 } | |
309 return null; | |
310 } | |
311 | |
312 bool _setObjectProperty(object, property, value) { | |
313 if (object == null) return false; | |
314 | |
315 if (property is int) { | |
316 if (object is List && property >= 0 && property < object.length) { | |
317 object[property] = value; | |
318 return true; | |
319 } | |
320 } else if (property is Symbol) { | |
321 // Support indexer if available, e.g. Maps or polymer_expressions Scope. | |
322 if (object is Indexable || object is Map && !_MAP_PROPERTIES.contains(proper
ty)) { | |
323 object[smoke.symbolToName(property)] = value; | |
324 return true; | |
325 } | |
326 try { | |
327 smoke.write(object, property, value); | |
328 return true; | |
329 } on NoSuchMethodError catch (e, s) { | |
330 if (!smoke.hasNoSuchMethod(object.runtimeType)) rethrow; | |
331 } | |
332 } | |
333 | |
334 if (_logger.isLoggable(Level.FINER)) { | |
335 _logger.finer("can't set $property in $object"); | |
336 } | |
337 return false; | |
338 } | |
339 | |
340 // From: https://github.com/rafaelw/ChangeSummary/blob/master/change_summary.js | |
341 | |
342 final _identRegExp = () { | |
343 const identStart = '[\$_a-zA-Z]'; | |
344 const identPart = '[\$_a-zA-Z0-9]'; | |
345 return new RegExp('^$identStart+$identPart*\$'); | |
346 }(); | |
347 | |
348 _isIdent(s) => _identRegExp.hasMatch(s); | |
349 | |
350 // Dart note: refactored to convert to codepoints once and operate on codepoints | |
351 // rather than characters. | |
352 class _PathParser { | |
353 List keys = []; | |
354 int index = -1; | |
355 String key; | |
356 | |
357 final Map<String, List<String>> _pathStateMachine = { | |
358 'beforePath': { | |
359 'ws': ['beforePath'], | |
360 'ident': ['inIdent', 'append'], | |
361 '[': ['beforeElement'], | |
362 'eof': ['afterPath'] | |
363 }, | |
364 | |
365 'inPath': { | |
366 'ws': ['inPath'], | |
367 '.': ['beforeIdent'], | |
368 '[': ['beforeElement'], | |
369 'eof': ['afterPath'] | |
370 }, | |
371 | |
372 'beforeIdent': { | |
373 'ws': ['beforeIdent'], | |
374 'ident': ['inIdent', 'append'] | |
375 }, | |
376 | |
377 'inIdent': { | |
378 'ident': ['inIdent', 'append'], | |
379 '0': ['inIdent', 'append'], | |
380 'number': ['inIdent', 'append'], | |
381 'ws': ['inPath', 'push'], | |
382 '.': ['beforeIdent', 'push'], | |
383 '[': ['beforeElement', 'push'], | |
384 'eof': ['afterPath', 'push'] | |
385 }, | |
386 | |
387 'beforeElement': { | |
388 'ws': ['beforeElement'], | |
389 '0': ['afterZero', 'append'], | |
390 'number': ['inIndex', 'append'], | |
391 "'": ['inSingleQuote', 'append', ''], | |
392 '"': ['inDoubleQuote', 'append', ''] | |
393 }, | |
394 | |
395 'afterZero': { | |
396 'ws': ['afterElement', 'push'], | |
397 ']': ['inPath', 'push'] | |
398 }, | |
399 | |
400 'inIndex': { | |
401 '0': ['inIndex', 'append'], | |
402 'number': ['inIndex', 'append'], | |
403 'ws': ['afterElement'], | |
404 ']': ['inPath', 'push'] | |
405 }, | |
406 | |
407 'inSingleQuote': { | |
408 "'": ['afterElement'], | |
409 'eof': ['error'], | |
410 'else': ['inSingleQuote', 'append'] | |
411 }, | |
412 | |
413 'inDoubleQuote': { | |
414 '"': ['afterElement'], | |
415 'eof': ['error'], | |
416 'else': ['inDoubleQuote', 'append'] | |
417 }, | |
418 | |
419 'afterElement': { | |
420 'ws': ['afterElement'], | |
421 ']': ['inPath', 'push'] | |
422 } | |
423 }; | |
424 | |
425 /// From getPathCharType: determines the type of a given [code]point. | |
426 String _getPathCharType(code) { | |
427 if (code == null) return 'eof'; | |
428 switch(code) { | |
429 case 0x5B: // [ | |
430 case 0x5D: // ] | |
431 case 0x2E: // . | |
432 case 0x22: // " | |
433 case 0x27: // ' | |
434 case 0x30: // 0 | |
435 return _char(code); | |
436 | |
437 case 0x5F: // _ | |
438 case 0x24: // $ | |
439 return 'ident'; | |
440 | |
441 case 0x20: // Space | |
442 case 0x09: // Tab | |
443 case 0x0A: // Newline | |
444 case 0x0D: // Return | |
445 case 0xA0: // No-break space | |
446 case 0xFEFF: // Byte Order Mark | |
447 case 0x2028: // Line Separator | |
448 case 0x2029: // Paragraph Separator | |
449 return 'ws'; | |
450 } | |
451 | |
452 // a-z, A-Z | |
453 if ((0x61 <= code && code <= 0x7A) || (0x41 <= code && code <= 0x5A)) | |
454 return 'ident'; | |
455 | |
456 // 1-9 | |
457 if (0x31 <= code && code <= 0x39) | |
458 return 'number'; | |
459 | |
460 return 'else'; | |
461 } | |
462 | |
463 static String _char(int codepoint) => new String.fromCharCodes([codepoint]); | |
464 | |
465 void push() { | |
466 if (key == null) return; | |
467 | |
468 // Dart note: we store the keys with different types, rather than | |
469 // parsing/converting things later in toString. | |
470 if (_isIdent(key)) { | |
471 keys.add(smoke.nameToSymbol(key)); | |
472 } else { | |
473 var index = int.parse(key, radix: 10, onError: (_) => null); | |
474 keys.add(index != null ? index : key); | |
475 } | |
476 key = null; | |
477 } | |
478 | |
479 void append(newChar) { | |
480 key = (key == null) ? newChar : '$key$newChar'; | |
481 } | |
482 | |
483 bool _maybeUnescapeQuote(String mode, codePoints) { | |
484 if (index >= codePoints.length) return false; | |
485 var nextChar = _char(codePoints[index + 1]); | |
486 if ((mode == 'inSingleQuote' && nextChar == "'") || | |
487 (mode == 'inDoubleQuote' && nextChar == '"')) { | |
488 index++; | |
489 append(nextChar); | |
490 return true; | |
491 } | |
492 return false; | |
493 } | |
494 | |
495 /// Returns the parsed keys, or null if there was a parse error. | |
496 List<String> parse(String path) { | |
497 var codePoints = stringToCodepoints(path); | |
498 var mode = 'beforePath'; | |
499 | |
500 while (mode != null) { | |
501 index++; | |
502 var c = index >= codePoints.length ? null : codePoints[index]; | |
503 | |
504 if (c != null && | |
505 _char(c) == '\\' && _maybeUnescapeQuote(mode, codePoints)) continue; | |
506 | |
507 var type = _getPathCharType(c); | |
508 if (mode == 'error') return null; | |
509 | |
510 var typeMap = _pathStateMachine[mode]; | |
511 var transition = typeMap[type]; | |
512 if (transition == null) transition = typeMap['else']; | |
513 if (transition == null) return null; // parse error; | |
514 | |
515 mode = transition[0]; | |
516 var actionName = transition.length > 1 ? transition[1] : null; | |
517 if (actionName == 'push' && key != null) push(); | |
518 if (actionName == 'append') { | |
519 var newChar = transition.length > 2 && transition[2] != null | |
520 ? transition[2] : _char(c); | |
521 append(newChar); | |
522 } | |
523 | |
524 if (mode == 'afterPath') return keys; | |
525 } | |
526 return null; // parse error | |
527 } | |
528 } | |
529 | |
530 final Logger _logger = new Logger('observe.PathObserver'); | |
531 | |
532 | |
533 /// This is a simple cache. It's like LRU but we don't update an item on a | |
534 /// cache hit, because that would require allocation. Better to let it expire | |
535 /// and reallocate the PropertyPath. | |
536 // TODO(jmesserly): this optimization is from observe-js, how valuable is it in | |
537 // practice? | |
538 final _pathCache = new LinkedHashMap<String, PropertyPath>(); | |
539 | |
540 /// The size of a path like "foo.bar" is approximately 160 bytes, so this | |
541 /// reserves ~16Kb of memory for recently used paths. Since paths are frequently | |
542 /// reused, the theory is that this ends up being a good tradeoff in practice. | |
543 // (Note: the 160 byte estimate is from Dart VM 1.0.0.10_r30798 on x64 without | |
544 // using UnmodifiableListView in PropertyPath) | |
545 const int _pathCacheLimit = 100; | |
546 | |
547 /// [CompoundObserver] is a [Bindable] object which knows how to listen to | |
548 /// multiple values (registered via [addPath] or [addObserver]) and invoke a | |
549 /// callback when one or more of the values have changed. | |
550 /// | |
551 /// var obj = new ObservableMap.from({'a': 1, 'b': 2}); | |
552 /// var otherObj = new ObservableMap.from({'c': 3}); | |
553 /// | |
554 /// var observer = new CompoundObserver() | |
555 /// ..addPath(obj, 'a'); | |
556 /// ..addObserver(new PathObserver(obj, 'b')); | |
557 /// ..addPath(otherObj, 'c'); | |
558 /// ..open((values) { | |
559 /// for (int i = 0; i < values.length; i++) { | |
560 /// print('The value at index $i is now ${values[i]}'); | |
561 /// } | |
562 /// }); | |
563 /// | |
564 /// obj['a'] = 10; // print will be triggered async | |
565 /// | |
566 class CompoundObserver extends _Observer implements Bindable { | |
567 _ObservedSet _directObserver; | |
568 bool _reportChangesOnOpen; | |
569 List _observed = []; | |
570 | |
571 CompoundObserver([this._reportChangesOnOpen = false]) { | |
572 _value = []; | |
573 } | |
574 | |
575 int get _reportArgumentCount => 3; | |
576 | |
577 /// Initiates observation and returns the initial value. | |
578 /// The callback will be passed the updated [value], and may optionally be | |
579 /// declared to take a second argument, which will contain the previous value. | |
580 /// | |
581 /// Implementation note: a third argument can also be declared, which will | |
582 /// receive a list of objects and paths, such that `list[2 * i]` will access | |
583 /// the object and `list[2 * i + 1]` will access the path, where `i` is the | |
584 /// order of the [addPath] call. This parameter is only used by | |
585 /// `package:polymer` as a performance optimization, and should not be relied | |
586 /// on in new code. | |
587 open(callback) => super.open(callback); | |
588 | |
589 void _connect() { | |
590 for (var i = 0; i < _observed.length; i += 2) { | |
591 var object = _observed[i]; | |
592 if (!identical(object, _observerSentinel)) { | |
593 _directObserver = new _ObservedSet(this, object); | |
594 break; | |
595 } | |
596 } | |
597 | |
598 _check(skipChanges: !_reportChangesOnOpen); | |
599 } | |
600 | |
601 void _disconnect() { | |
602 for (var i = 0; i < _observed.length; i += 2) { | |
603 if (identical(_observed[i], _observerSentinel)) { | |
604 _observed[i + 1].close(); | |
605 } | |
606 } | |
607 | |
608 _observed = null; | |
609 _value = null; | |
610 | |
611 if (_directObserver != null) { | |
612 _directObserver.close(this); | |
613 _directObserver = null; | |
614 } | |
615 } | |
616 | |
617 /// Adds a dependency on the property [path] accessed from [object]. | |
618 /// [path] can be a [PropertyPath] or a [String]. If it is omitted an empty | |
619 /// path will be used. | |
620 void addPath(Object object, [path]) { | |
621 if (_isOpen || _isClosed) { | |
622 throw new StateError('Cannot add paths once started.'); | |
623 } | |
624 | |
625 path = new PropertyPath(path); | |
626 _observed..add(object)..add(path); | |
627 if (!_reportChangesOnOpen) return; | |
628 _value.add(path.getValueFrom(object)); | |
629 } | |
630 | |
631 void addObserver(Bindable observer) { | |
632 if (_isOpen || _isClosed) { | |
633 throw new StateError('Cannot add observers once started.'); | |
634 } | |
635 | |
636 _observed..add(_observerSentinel)..add(observer); | |
637 if (!_reportChangesOnOpen) return; | |
638 _value.add(observer.open((_) => deliver())); | |
639 } | |
640 | |
641 void _iterateObjects(void observe(obj, prop)) { | |
642 for (var i = 0; i < _observed.length; i += 2) { | |
643 var object = _observed[i]; | |
644 if (!identical(object, _observerSentinel)) { | |
645 (_observed[i + 1] as PropertyPath)._iterateObjects(object, observe); | |
646 } | |
647 } | |
648 } | |
649 | |
650 bool _check({bool skipChanges: false}) { | |
651 bool changed = false; | |
652 _value.length = _observed.length ~/ 2; | |
653 var oldValues = null; | |
654 for (var i = 0; i < _observed.length; i += 2) { | |
655 var object = _observed[i]; | |
656 var path = _observed[i + 1]; | |
657 var value; | |
658 if (identical(object, _observerSentinel)) { | |
659 var observable = path as Bindable; | |
660 value = _state == _Observer._UNOPENED ? | |
661 observable.open((_) => this.deliver()) : | |
662 observable.value; | |
663 } else { | |
664 value = (path as PropertyPath).getValueFrom(object); | |
665 } | |
666 | |
667 if (skipChanges) { | |
668 _value[i ~/ 2] = value; | |
669 continue; | |
670 } | |
671 | |
672 if (value == _value[i ~/ 2]) continue; | |
673 | |
674 // don't allocate this unless necessary. | |
675 if (_notifyArgumentCount >= 2) { | |
676 if (oldValues == null) oldValues = new Map(); | |
677 oldValues[i ~/ 2] = _value[i ~/ 2]; | |
678 } | |
679 | |
680 changed = true; | |
681 _value[i ~/ 2] = value; | |
682 } | |
683 | |
684 if (!changed) return false; | |
685 | |
686 // TODO(rafaelw): Having _observed as the third callback arg here is | |
687 // pretty lame API. Fix. | |
688 _report(_value, oldValues, _observed); | |
689 return true; | |
690 } | |
691 } | |
692 | |
693 /// An object accepted by [PropertyPath] where properties are read and written | |
694 /// as indexing operations, just like a [Map]. | |
695 abstract class Indexable<K, V> { | |
696 V operator [](K key); | |
697 operator []=(K key, V value); | |
698 } | |
699 | |
700 const _observerSentinel = const _ObserverSentinel(); | |
701 class _ObserverSentinel { const _ObserverSentinel(); } | |
702 | |
703 // Visible for testing | |
704 get observerSentinelForTesting => _observerSentinel; | |
705 | |
706 // A base class for the shared API implemented by PathObserver and | |
707 // CompoundObserver and used in _ObservedSet. | |
708 abstract class _Observer extends Bindable { | |
709 Function _notifyCallback; | |
710 int _notifyArgumentCount; | |
711 var _value; | |
712 | |
713 // abstract members | |
714 void _iterateObjects(void observe(obj, prop)); | |
715 void _connect(); | |
716 void _disconnect(); | |
717 bool _check({bool skipChanges: false}); | |
718 | |
719 static int _UNOPENED = 0; | |
720 static int _OPENED = 1; | |
721 static int _CLOSED = 2; | |
722 int _state = _UNOPENED; | |
723 bool get _isOpen => _state == _OPENED; | |
724 bool get _isClosed => _state == _CLOSED; | |
725 | |
726 /// The number of arguments the subclass will pass to [_report]. | |
727 int get _reportArgumentCount; | |
728 | |
729 open(callback) { | |
730 if (_isOpen || _isClosed) { | |
731 throw new StateError('Observer has already been opened.'); | |
732 } | |
733 | |
734 if (smoke.minArgs(callback) > _reportArgumentCount) { | |
735 throw new ArgumentError('callback should take $_reportArgumentCount or ' | |
736 'fewer arguments'); | |
737 } | |
738 | |
739 _notifyCallback = callback; | |
740 _notifyArgumentCount = min(_reportArgumentCount, smoke.maxArgs(callback)); | |
741 | |
742 _connect(); | |
743 _state = _OPENED; | |
744 return _value; | |
745 } | |
746 | |
747 get value => _discardChanges(); | |
748 | |
749 void close() { | |
750 if (!_isOpen) return; | |
751 | |
752 _disconnect(); | |
753 _value = null; | |
754 _notifyCallback = null; | |
755 _state = _CLOSED; | |
756 } | |
757 | |
758 _discardChanges() { | |
759 _check(skipChanges: true); | |
760 return _value; | |
761 } | |
762 | |
763 void deliver() { | |
764 if (_isOpen) _dirtyCheck(); | |
765 } | |
766 | |
767 bool _dirtyCheck() { | |
768 var cycles = 0; | |
769 while (cycles < _MAX_DIRTY_CHECK_CYCLES && _check()) { | |
770 cycles++; | |
771 } | |
772 return cycles > 0; | |
773 } | |
774 | |
775 void _report(newValue, oldValue, [extraArg]) { | |
776 try { | |
777 switch (_notifyArgumentCount) { | |
778 case 0: _notifyCallback(); break; | |
779 case 1: _notifyCallback(newValue); break; | |
780 case 2: _notifyCallback(newValue, oldValue); break; | |
781 case 3: _notifyCallback(newValue, oldValue, extraArg); break; | |
782 } | |
783 } catch (e, s) { | |
784 // Deliver errors async, so if a single callback fails it doesn't prevent | |
785 // other things from working. | |
786 new Completer().completeError(e, s); | |
787 } | |
788 } | |
789 } | |
790 | |
791 /// The observedSet abstraction is a perf optimization which reduces the total | |
792 /// number of Object.observe observations of a set of objects. The idea is that | |
793 /// groups of Observers will have some object dependencies in common and this | |
794 /// observed set ensures that each object in the transitive closure of | |
795 /// dependencies is only observed once. The observedSet acts as a write barrier | |
796 /// such that whenever any change comes through, all Observers are checked for | |
797 /// changed values. | |
798 /// | |
799 /// Note that this optimization is explicitly moving work from setup-time to | |
800 /// change-time. | |
801 /// | |
802 /// TODO(rafaelw): Implement "garbage collection". In order to move work off | |
803 /// the critical path, when Observers are closed, their observed objects are | |
804 /// not Object.unobserve(d). As a result, it's possible that if the observedSet | |
805 /// is kept open, but some Observers have been closed, it could cause "leaks" | |
806 /// (prevent otherwise collectable objects from being collected). At some | |
807 /// point, we should implement incremental "gc" which keeps a list of | |
808 /// observedSets which may need clean-up and does small amounts of cleanup on a | |
809 /// timeout until all is clean. | |
810 class _ObservedSet { | |
811 /// To prevent sequential [PathObserver]s and [CompoundObserver]s from | |
812 /// observing the same object, we check if they are observing the same root | |
813 /// as the most recently created observer, and if so merge it into the | |
814 /// existing _ObservedSet. | |
815 /// | |
816 /// See <https://github.com/Polymer/observe-js/commit/f0990b1> and | |
817 /// <https://codereview.appspot.com/46780044/>. | |
818 static _ObservedSet _lastSet; | |
819 | |
820 /// The root object for a [PathObserver]. For a [CompoundObserver], the root | |
821 /// object of the first path observed. This is used by the constructor to | |
822 /// reuse an [_ObservedSet] that starts from the same object. | |
823 Object _rootObject; | |
824 | |
825 /// Subset of properties in [_rootObject] that we care about. | |
826 Set _rootObjectProperties; | |
827 | |
828 /// Observers associated with this root object, in birth order. | |
829 final List<_Observer> _observers = []; | |
830 | |
831 // Dart note: the JS implementation is O(N^2) because Array.indexOf is used | |
832 // for lookup in this array. We use HashMap to avoid this problem. It | |
833 // also gives us a nice way of tracking the StreamSubscription. | |
834 Map<Object, StreamSubscription> _objects; | |
835 | |
836 factory _ObservedSet(_Observer observer, Object rootObject) { | |
837 if (_lastSet == null || !identical(_lastSet._rootObject, rootObject)) { | |
838 _lastSet = new _ObservedSet._(rootObject); | |
839 } | |
840 _lastSet.open(observer, rootObject); | |
841 return _lastSet; | |
842 } | |
843 | |
844 _ObservedSet._(rootObject) | |
845 : _rootObject = rootObject, | |
846 _rootObjectProperties = rootObject == null ? null : new Set(); | |
847 | |
848 void open(_Observer obs, Object rootObject) { | |
849 if (_rootObject == null) { | |
850 _rootObject = rootObject; | |
851 _rootObjectProperties = new Set(); | |
852 } | |
853 | |
854 _observers.add(obs); | |
855 obs._iterateObjects(observe); | |
856 } | |
857 | |
858 void close(_Observer obs) { | |
859 _observers.remove(obs); | |
860 if (_observers.isNotEmpty) return; | |
861 | |
862 if (_objects != null) { | |
863 for (var sub in _objects.values) 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 |