This repository has been archived by the owner on Feb 22, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
js.dart
1341 lines (1204 loc) · 42.1 KB
/
js.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/**
* The js.dart library provides simple JavaScript invocation from Dart that
* works on both Dartium and on other modern browsers via Dart2JS.
*
* It provides a model based on scoped [Proxy] objects. Proxies give Dart
* code access to JavaScript objects, fields, and functions as well as the
* ability to pass Dart objects and functions to JavaScript functions. Scopes
* enable developers to use proxies without memory leaks - a common challenge
* with cross-runtime interoperation.
*
* The top-level [context] getter provides a [Proxy] to the global JavaScript
* context for the page your Dart code is running on. In the following example:
*
* import 'package:js/js.dart' as js;
*
* void main() {
* js.scoped(() {
* js.context.alert('Hello from Dart via JavaScript');
* });
* }
*
* js.context.alert creates a proxy to the top-level alert function in
* JavaScript. It is invoked from Dart as a regular function that forwards to
* the underlying JavaScript one. The proxies allocated within the scope are
* released once the scope is exited.
*
* The library also enables JavaScript proxies to Dart objects and functions.
* For example, the following Dart code:
*
* scoped(() {
* js.context.dartCallback = new Callback.once((x) => print(x*2));
* });
*
* defines a top-level JavaScript function 'dartCallback' that is a proxy to
* the corresponding Dart function. The [Callback.once] constructor allows the
* proxy to the Dart function to be retained beyond the end of the scope;
* instead it is released after the first invocation. (This is a common
* pattern for asychronous callbacks.)
*
* Note, parameters and return values are intuitively passed by value for
* primitives and by reference for non-primitives. In the latter case, the
* references are automatically wrapped and unwrapped as proxies by the library.
*
* This library also allows construction of JavaScripts objects given a [Proxy]
* to a corresponding JavaScript constructor. For example, if the following
* JavaScript is loaded on the page:
*
* function Foo(x) {
* this.x = x;
* }
*
* Foo.prototype.add = function(other) {
* return new Foo(this.x + other.x);
* }
*
* then, the following Dart:
*
* var foo = new js.Proxy(js.context.Foo, 42);
* var foo2 = foo.add(foo);
* print(foo2.x);
*
* will construct a JavaScript Foo object with the parameter 42, invoke its
* add method, and return a [Proxy] to a new Foo object whose x field is 84.
*
* See [samples](http://dart-lang.github.com/js-interop/example) for more
* examples of usage.
*/
// TODO(vsm): Add a link to an article.
library js;
import 'dart:html';
import 'dart:isolate';
// JavaScript bootstrapping code.
// TODO(vsm): Migrate this to use a builtin resource mechanism once we have
// one.
// NOTE: Please re-run tools/create_bootstrap.dart on any modification of
// this bootstrap string.
final _JS_BOOTSTRAP = r"""
(function() {
// Proxy support for js.dart.
var globalContext = window;
// Support for binding the receiver (this) in proxied functions.
function bindIfFunction(f, _this) {
if (typeof(f) != "function") {
return f;
} else {
return new BoundFunction(_this, f);
}
}
function unbind(obj) {
if (obj instanceof BoundFunction) {
return obj.object;
} else {
return obj;
}
}
function getBoundThis(obj) {
if (obj instanceof BoundFunction) {
return obj._this;
} else {
return globalContext;
}
}
function BoundFunction(_this, object) {
this._this = _this;
this.object = object;
}
// Table for local objects and functions that are proxied.
function ProxiedObjectTable() {
// Name for debugging.
this.name = 'js-ref';
// Table from IDs to JS objects.
this.map = {};
// Generator for new IDs.
this._nextId = 0;
// Counter for deleted proxies.
this._deletedCount = 0;
// Flag for one-time initialization.
this._initialized = false;
// Ports for managing communication to proxies.
this.port = new ReceivePortSync();
this.sendPort = this.port.toSendPort();
// Set of IDs that are global.
// These will not be freed on an exitScope().
this.globalIds = {};
// Stack of scoped handles.
this.handleStack = [];
// Stack of active scopes where each value is represented by the size of
// the handleStack at the beginning of the scope. When an active scope
// is popped, the handleStack is restored to where it was when the
// scope was entered.
this.scopeIndices = [];
}
// Number of valid IDs. This is the number of objects (global and local)
// kept alive by this table.
ProxiedObjectTable.prototype.count = function () {
return Object.keys(this.map).length;
}
// Number of total IDs ever allocated.
ProxiedObjectTable.prototype.total = function () {
return this.count() + this._deletedCount;
}
// Adds an object to the table and return an ID for serialization.
ProxiedObjectTable.prototype.add = function (obj) {
if (this.scopeIndices.length == 0) {
throw "Cannot allocate a proxy outside of a scope.";
}
// TODO(vsm): Cache refs for each obj?
var ref = this.name + '-' + this._nextId++;
this.handleStack.push(ref);
this.map[ref] = obj;
return ref;
}
ProxiedObjectTable.prototype._initializeOnce = function () {
if (!this._initialized) {
this._initialize();
this._initialized = true;
}
}
// Enters a new scope for this table.
ProxiedObjectTable.prototype.enterScope = function() {
this._initializeOnce();
this.scopeIndices.push(this.handleStack.length);
}
// Invalidates all non-global IDs in the current scope and
// exit the current scope.
ProxiedObjectTable.prototype.exitScope = function() {
var start = this.scopeIndices.pop();
for (var i = start; i < this.handleStack.length; ++i) {
var key = this.handleStack[i];
if (!this.globalIds.hasOwnProperty(key)) {
delete this.map[this.handleStack[i]];
this._deletedCount++;
}
}
this.handleStack = this.handleStack.splice(0, start);
}
// Makes this ID globally scope. It must be explicitly invalidated.
ProxiedObjectTable.prototype.globalize = function(id) {
this.globalIds[id] = true;
}
// Invalidates this ID, potentially freeing its corresponding object.
ProxiedObjectTable.prototype.invalidate = function(id) {
var old = this.get(id);
delete this.globalIds[id];
delete this.map[id];
this._deletedCount++;
return old;
}
// Gets the object or function corresponding to this ID.
ProxiedObjectTable.prototype.get = function (id) {
if (!this.map.hasOwnProperty(id)) {
throw 'Proxy ' + id + ' has been invalidated.'
}
return this.map[id];
}
ProxiedObjectTable.prototype._initialize = function () {
// Configure this table's port to forward methods, getters, and setters
// from the remote proxy to the local object.
var table = this;
this.port.receive(function (message) {
// TODO(vsm): Support a mechanism to register a handler here.
try {
var object = table.get(message[0]);
var receiver = unbind(object);
var member = message[1];
var kind = message[2];
var args = message[3].map(deserialize);
if (kind == 'get') {
// Getter.
var field = member;
if (field in receiver && args.length == 0) {
var result = bindIfFunction(receiver[field], receiver);
return [ 'return', serialize(result) ];
}
} else if (kind == 'set') {
// Setter.
var field = member;
if (args.length == 1) {
return [ 'return', serialize(receiver[field] = args[0]) ];
}
} else if (kind == 'apply') {
// Direct function invocation.
var _this = getBoundThis(object);
return [ 'return', serialize(receiver.apply(_this, args)) ];
} else if (member == '[]' && args.length == 1) {
// Index getter.
var result = bindIfFunction(receiver[args[0]], receiver);
return [ 'return', serialize(result) ];
} else if (member == '[]=' && args.length == 2) {
// Index setter.
return [ 'return', serialize(receiver[args[0]] = args[1]) ];
} else {
// Member function invocation.
var f = receiver[member];
if (f) {
var result = f.apply(receiver, args);
return [ 'return', serialize(result) ];
}
}
return [ 'none' ];
} catch (e) {
return [ 'throws', e.toString() ];
}
});
}
// Singleton for local proxied objects.
var proxiedObjectTable = new ProxiedObjectTable();
// DOM element serialization code.
var _localNextElementId = 0;
var _DART_ID = 'data-dart_id';
var _DART_TEMPORARY_ATTACHED = 'data-dart_temporary_attached';
function serializeElement(e) {
// TODO(vsm): Use an isolate-specific id.
var id;
if (e.hasAttribute(_DART_ID)) {
id = e.getAttribute(_DART_ID);
} else {
id = (_localNextElementId++).toString();
e.setAttribute(_DART_ID, id);
}
if (e !== document.documentElement) {
// Element must be attached to DOM to be retrieve in js part.
// Attach top unattached parent to avoid detaching parent of "e" when
// appending "e" directly to document. We keep count of elements
// temporarily attached to prevent detaching top unattached parent to
// early. This count is equals to the length of _DART_TEMPORARY_ATTACHED
// attribute. There could be other elements to serialize having the same
// top unattached parent.
var top = e;
while (true) {
if (top.hasAttribute(_DART_TEMPORARY_ATTACHED)) {
var oldValue = top.getAttribute(_DART_TEMPORARY_ATTACHED);
var newValue = oldValue + "a";
top.setAttribute(_DART_TEMPORARY_ATTACHED, newValue);
break;
}
if (top.parentNode == null) {
top.setAttribute(_DART_TEMPORARY_ATTACHED, "a");
document.documentElement.appendChild(top);
break;
}
if (top.parentNode === document.documentElement) {
// e was already attached to dom
break;
}
top = top.parentNode;
}
}
return id;
}
function deserializeElement(id) {
// TODO(vsm): Clear the attribute.
var list = document.querySelectorAll('[' + _DART_ID + '="' + id + '"]');
if (list.length > 1) throw 'Non unique ID: ' + id;
if (list.length == 0) {
throw 'Element must be attached to the document: ' + id;
}
var e = list[0];
if (e !== document.documentElement) {
// detach temporary attached element
var top = e;
while (true) {
if (top.hasAttribute(_DART_TEMPORARY_ATTACHED)) {
var oldValue = top.getAttribute(_DART_TEMPORARY_ATTACHED);
var newValue = oldValue.substring(1);
top.setAttribute(_DART_TEMPORARY_ATTACHED, newValue);
// detach top only if no more elements have to be unserialized
if (top.getAttribute(_DART_TEMPORARY_ATTACHED).length === 0) {
top.removeAttribute(_DART_TEMPORARY_ATTACHED);
document.documentElement.removeChild(top);
}
break;
}
if (top.parentNode === document.documentElement) {
// e was already attached to dom
break;
}
top = top.parentNode;
}
}
return e;
}
// Type for remote proxies to Dart objects.
function DartProxy(id, sendPort) {
this.id = id;
this.port = sendPort;
}
// Serializes JS types to SendPortSync format:
// - primitives -> primitives
// - sendport -> sendport
// - DOM element -> [ 'domref', element-id ]
// - Function -> [ 'funcref', function-id, sendport ]
// - Object -> [ 'objref', object-id, sendport ]
function serialize(message) {
if (message == null) {
return null; // Convert undefined to null.
} else if (typeof(message) == 'string' ||
typeof(message) == 'number' ||
typeof(message) == 'boolean') {
// Primitives are passed directly through.
return message;
} else if (message instanceof SendPortSync) {
// Non-proxied objects are serialized.
return message;
} else if (message instanceof Element &&
(message.ownerDocument == null || message.ownerDocument == document)) {
return [ 'domref', serializeElement(message) ];
} else if (message instanceof BoundFunction &&
typeof(message.object) == 'function') {
// Local function proxy.
return [ 'funcref',
proxiedObjectTable.add(message),
proxiedObjectTable.sendPort ];
} else if (typeof(message) == 'function') {
if ('_dart_id' in message) {
// Remote function proxy.
var remoteId = message._dart_id;
var remoteSendPort = message._dart_port;
return [ 'funcref', remoteId, remoteSendPort ];
} else {
// Local function proxy.
return [ 'funcref',
proxiedObjectTable.add(message),
proxiedObjectTable.sendPort ];
}
} else if (message instanceof DartProxy) {
// Remote object proxy.
return [ 'objref', message.id, message.port ];
} else {
// Local object proxy.
return [ 'objref',
proxiedObjectTable.add(message),
proxiedObjectTable.sendPort ];
}
}
function deserialize(message) {
if (message == null) {
return null; // Convert undefined to null.
} else if (typeof(message) == 'string' ||
typeof(message) == 'number' ||
typeof(message) == 'boolean') {
// Primitives are passed directly through.
return message;
} else if (message instanceof SendPortSync) {
// Serialized type.
return message;
}
var tag = message[0];
switch (tag) {
case 'funcref': return deserializeFunction(message);
case 'objref': return deserializeObject(message);
case 'domref': return deserializeElement(message[1]);
}
throw 'Unsupported serialized data: ' + message;
}
// Create a local function that forwards to the remote function.
function deserializeFunction(message) {
var id = message[1];
var port = message[2];
// TODO(vsm): Add a more robust check for a local SendPortSync.
if ("receivePort" in port) {
// Local function.
return proxiedObjectTable.get(id);
} else {
// Remote function. Forward to its port.
var f = function () {
var depth = enterScope();
try {
var args = Array.prototype.slice.apply(arguments).map(serialize);
var result = port.callSync([id, '#call', args]);
if (result[0] == 'throws') throw deserialize(result[1]);
return deserialize(result[1]);
} finally {
exitScope(depth);
}
};
// Cache the remote id and port.
f._dart_id = id;
f._dart_port = port;
return f;
}
}
// Creates a DartProxy to forwards to the remote object.
function deserializeObject(message) {
var id = message[1];
var port = message[2];
// TODO(vsm): Add a more robust check for a local SendPortSync.
if ("receivePort" in port) {
// Local object.
return proxiedObjectTable.get(id);
} else {
// Remote object.
return new DartProxy(id, port);
}
}
// Remote handler to construct a new JavaScript object given its
// serialized constructor and arguments.
function construct(args) {
args = args.map(deserialize);
var constructor = unbind(args[0]);
args = Array.prototype.slice.call(args, 1);
// Until 10 args, the 'new' operator is used. With more arguments we use a
// generic way that may not work, particulary when the constructor does not
// have an "apply" method.
var ret = null;
if (args.length === 0) {
ret = new constructor();
} else if (args.length === 1) {
ret = new constructor(args[0]);
} else if (args.length === 2) {
ret = new constructor(args[0], args[1]);
} else if (args.length === 3) {
ret = new constructor(args[0], args[1], args[2]);
} else if (args.length === 4) {
ret = new constructor(args[0], args[1], args[2], args[3]);
} else if (args.length === 5) {
ret = new constructor(args[0], args[1], args[2], args[3], args[4]);
} else if (args.length === 6) {
ret = new constructor(args[0], args[1], args[2], args[3], args[4],
args[5]);
} else if (args.length === 7) {
ret = new constructor(args[0], args[1], args[2], args[3], args[4],
args[5], args[6]);
} else if (args.length === 8) {
ret = new constructor(args[0], args[1], args[2], args[3], args[4],
args[5], args[6]);
} else if (args.length === 9) {
ret = new constructor(args[0], args[1], args[2], args[3], args[4],
args[5], args[6]);
} else if (args.length === 10) {
ret = new constructor(args[0], args[1], args[2], args[3], args[4],
args[5], args[6], args[7], args[8], args[9]);
} else {
// Dummy Type with correct constructor.
var Type = function(){};
Type.prototype = constructor.prototype;
// Create a new instance
var instance = new Type();
// Call the original constructor.
ret = constructor.apply(instance, args);
ret = Object(ret) === ret ? ret : instance;
}
return serialize(ret);
}
// Remote handler to return the top-level JavaScript context.
function context(data) {
return serialize(globalContext);
}
// Remote handler for debugging.
function debug() {
var live = proxiedObjectTable.count();
var total = proxiedObjectTable.total();
return 'JS objects Live : ' + live +
' (out of ' + total + ' ever allocated).';
}
// Return true if two JavaScript proxies are equal (==).
function proxyEquals(args) {
return deserialize(args[0]) == deserialize(args[1]);
}
// Return true if a JavaScript proxy is instance of a given type (instanceof).
function proxyInstanceof(args) {
var obj = unbind(deserialize(args[0]));
var type = unbind(deserialize(args[1]));
return obj instanceof type;
}
// Return true if a JavaScript proxy is instance of a given type (instanceof).
function proxyDeleteProperty(args) {
var obj = unbind(deserialize(args[0]));
var member = unbind(deserialize(args[1]));
delete obj[member];
}
function proxyConvert(args) {
return serialize(deserializeDataTree(args));
}
function deserializeDataTree(data) {
var type = data[0];
var value = data[1];
if (type === 'map') {
var obj = {};
for (var i = 0; i < value.length; i++) {
obj[value[i][0]] = deserializeDataTree(value[i][1]);
}
return obj;
} else if (type === 'list') {
var list = [];
for (var i = 0; i < value.length; i++) {
list.push(deserializeDataTree(value[i]));
}
return list;
} else /* 'simple' */ {
return deserialize(value);
}
}
function makeGlobalPort(name, f) {
var port = new ReceivePortSync();
port.receive(f);
window.registerPort(name, port.toSendPort());
}
// Enters a new scope in the JavaScript context.
function enterJavaScriptScope() {
proxiedObjectTable.enterScope();
}
// Enters a new scope in both the JavaScript and Dart context.
var _dartEnterScopePort = null;
function enterScope() {
enterJavaScriptScope();
if (!_dartEnterScopePort) {
_dartEnterScopePort = window.lookupPort('js-dart-enter-scope');
}
return _dartEnterScopePort.callSync([]);
}
// Exits the current scope (and invalidate local IDs) in the JavaScript
// context.
function exitJavaScriptScope() {
proxiedObjectTable.exitScope();
}
// Exits the current scope in both the JavaScript and Dart context.
var _dartExitScopePort = null;
function exitScope(depth) {
exitJavaScriptScope();
if (!_dartExitScopePort) {
_dartExitScopePort = window.lookupPort('js-dart-exit-scope');
}
return _dartExitScopePort.callSync([ depth ]);
}
makeGlobalPort('dart-js-context', context);
makeGlobalPort('dart-js-create', construct);
makeGlobalPort('dart-js-debug', debug);
makeGlobalPort('dart-js-equals', proxyEquals);
makeGlobalPort('dart-js-instanceof', proxyInstanceof);
makeGlobalPort('dart-js-delete-property', proxyDeleteProperty);
makeGlobalPort('dart-js-convert', proxyConvert);
makeGlobalPort('dart-js-enter-scope', enterJavaScriptScope);
makeGlobalPort('dart-js-exit-scope', exitJavaScriptScope);
makeGlobalPort('dart-js-globalize', function(data) {
if (data[0] == "objref") return proxiedObjectTable.globalize(data[1]);
// TODO(vsm): Do we ever need to globalize functions?
throw 'Illegal type: ' + data[0];
});
makeGlobalPort('dart-js-invalidate', function(data) {
if (data[0] == "objref") return proxiedObjectTable.invalidate(data[1]);
// TODO(vsm): Do we ever need to globalize functions?
throw 'Illegal type: ' + data[0];
});
})();
""";
// Injects JavaScript source code onto the page.
// This is only used to load the bootstrapping code above.
void _inject(code) {
final script = new ScriptElement();
script.type = 'text/javascript';
script.innerHtml = code;
document.body.nodes.add(script);
}
// Global ports to manage communication from Dart to JS.
SendPortSync _jsPortSync = null;
SendPortSync _jsPortCreate = null;
SendPortSync _jsPortDebug = null;
SendPortSync _jsPortEquals = null;
SendPortSync _jsPortInstanceof = null;
SendPortSync _jsPortDeleteProperty = null;
SendPortSync _jsPortConvert = null;
SendPortSync _jsEnterJavaScriptScope = null;
SendPortSync _jsExitJavaScriptScope = null;
SendPortSync _jsGlobalize = null;
SendPortSync _jsInvalidate = null;
// Global ports to manage communication from JS to Dart.
ReceivePortSync _dartEnterDartScope = null;
ReceivePortSync _dartExitDartScope = null;
// Initializes bootstrap code and ports.
void _initialize() {
if (_jsPortSync != null) return;
// Test if the port is already defined.
try {
_jsPortSync = window.lookupPort('dart-js-context');
} catch (e) {
// TODO(vsm): Suppress the exception until dartbug.com/5854 is fixed.
}
// If not, try injecting the script.
if (_jsPortSync == null) {
_inject(_JS_BOOTSTRAP);
_jsPortSync = window.lookupPort('dart-js-context');
}
_jsPortCreate = window.lookupPort('dart-js-create');
_jsPortDebug = window.lookupPort('dart-js-debug');
_jsPortEquals = window.lookupPort('dart-js-equals');
_jsPortInstanceof = window.lookupPort('dart-js-instanceof');
_jsPortDeleteProperty = window.lookupPort('dart-js-delete-property');
_jsPortConvert = window.lookupPort('dart-js-convert');
_jsEnterJavaScriptScope = window.lookupPort('dart-js-enter-scope');
_jsExitJavaScriptScope = window.lookupPort('dart-js-exit-scope');
_jsGlobalize = window.lookupPort('dart-js-globalize');
_jsInvalidate = window.lookupPort('dart-js-invalidate');
_dartEnterDartScope = new ReceivePortSync()
..receive((_) => _enterScope());
_dartExitDartScope = new ReceivePortSync()
..receive((args) => _exitScope(args[0]));
window.registerPort('js-dart-enter-scope', _dartEnterDartScope.toSendPort());
window.registerPort('js-dart-exit-scope', _dartExitDartScope.toSendPort());
}
/**
* Returns a proxy to the global JavaScript context for this page.
*/
Proxy get context {
if (_depth == 0) throw 'Cannot get JavaScript context out of scope.';
return _deserialize(_jsPortSync.callSync([]));
}
// Depth of current scope. Return 0 if no scope.
get _depth => _proxiedObjectTable._scopeIndices.length;
/**
* Executes the closure [f] within a scope. Any proxies created within this
* scope are invalidated afterward unless they are converted to a global proxy.
*/
scoped(f) {
var depth = _enterScope();
try {
return f();
} finally {
_exitScope(depth);
}
}
_enterScope() {
_initialize();
_proxiedObjectTable.enterScope();
_jsEnterJavaScriptScope.callSync([]);
return _proxiedObjectTable._scopeIndices.length;
}
_exitScope(depth) {
assert(_proxiedObjectTable._scopeIndices.length == depth);
_jsExitJavaScriptScope.callSync([]);
_proxiedObjectTable.exitScope();
}
/*
* Enters a scope and returns the depth of the scope stack.
*/
/// WARNING: This API is experimental and may be removed.
int $experimentalEnterScope() {
return _enterScope();
}
/*
* Exits a scope. The [depth] must match that returned by the corresponding
* enter scope call.
*/
/// WARNING: This API is experimental and may be removed.
void $experimentalExitScope(int depth) {
_exitScope(depth);
}
/**
* Retains the given [object] beyond the current scope.
* Instead, it will need to be explicitly released.
* The given [object] is returned for convenience.
*/
// TODO(aa) : change dynamic to Serializable<Proxy> if http://dartbug.com/9023
// is fixed.
// TODO(aa) : change to "<T extends Serializable<Proxy>> T retain(T object)"
// once generic methods have landed.
dynamic retain(Serializable<Proxy> object) {
_jsGlobalize.callSync(_serialize(object.toJs()));
return object;
}
/**
* Releases a retained [object].
*/
void release(Serializable<Proxy> object) {
_jsInvalidate.callSync(_serialize(object.toJs()));
}
/**
* Check if [proxy] is instance of [type].
*/
bool instanceof(Proxy proxy, type) {
return _jsPortInstanceof.callSync([proxy, type].map(_serialize).toList());
}
/**
* Delete the [name] property of [proxy].
*/
void deleteProperty(Proxy proxy, String name) {
_jsPortDeleteProperty.callSync([proxy, name].map(_serialize).toList());
}
/**
* Converts a Dart map [data] to a JavaScript map and return a [Proxy] to it.
*/
Proxy map(Map data) => new Proxy._json(data);
/**
* Converts a Dart [list] to a JavaScript array and return a [Proxy] to it.
*/
Proxy array(List list) => new Proxy._json(list);
/**
* Converts a local Dart function to a callback that can be passed to
* JavaScript.
*
* A callback can either be:
*
* - single-fire, in which case it is automatically invalidated after the first
* invocation, or
* - multi-fire, in which case it must be explicitly disposed.
*/
class Callback {
var _manualDispose;
var _id;
var _callback;
get _serialized => [ 'funcref', _id, _proxiedObjectTable.sendPort ];
_initialize(manualDispose) {
_manualDispose = manualDispose;
_id = _proxiedObjectTable.add(_callback);
_proxiedObjectTable.globalize(_id);
}
_dispose() {
var c = _proxiedObjectTable.invalidate(_id);
}
/**
* Disposes this [Callback] so that it may be collected.
* Once a [Callback] is disposed, it is an error to invoke it from JavaScript.
*/
dispose() {
assert(_manualDispose);
_dispose();
}
/**
* Creates a single-fire [Callback] that invokes [f]. The callback is
* automatically disposed after the first invocation.
*/
Callback.once(Function f) {
_callback = (args) {
try {
return Function.apply(f, args);
} finally {
_dispose();
}
};
_initialize(false);
}
/**
* Creates a multi-fire [Callback] that invokes [f]. The callback must be
* explicitly disposed to avoid memory leaks.
*/
Callback.many(Function f) {
_callback = (args) => Function.apply(f, args);
_initialize(true);
}
}
// Detect unspecified arguments.
class _Undefined {
const _Undefined();
}
const _undefined = const _Undefined();
List _pruneUndefined(arg1, arg2, arg3, arg4, arg5, arg6) {
// This assumes no argument
final args = [arg1, arg2, arg3, arg4, arg5, arg6];
final index = args.indexOf(_undefined);
if (index < 0) return args;
return args.sublist(0, index);
}
/**
* Proxies to JavaScript objects.
*/
class Proxy implements Serializable<Proxy> {
SendPortSync _port;
final _id;
/**
* Constructs a [Proxy] to a new JavaScript object by invoking a (proxy to a)
* JavaScript [constructor]. The arguments should be either
* primitive values, DOM elements, or Proxies.
*/
factory Proxy(FunctionProxy constructor,
[arg1 = _undefined,
arg2 = _undefined,
arg3 = _undefined,
arg4 = _undefined,
arg5 = _undefined,
arg6 = _undefined]) {
var arguments = _pruneUndefined(arg1, arg2, arg3, arg4, arg5, arg6);
return new Proxy.withArgList(constructor, arguments);
}
/**
* Constructs a [Proxy] to a new JavaScript object by invoking a (proxy to a)
* JavaScript [constructor]. The [arguments] list should contain either
* primitive values, DOM elements, or Proxies.
*/
factory Proxy.withArgList(FunctionProxy constructor, List arguments) {
if (_depth == 0) throw 'Cannot create Proxy out of scope.';
final serialized = ([constructor]..addAll(arguments)).map(_serialize).
toList();
final result = _jsPortCreate.callSync(serialized);
return _deserialize(result);
}
/**
* Constructs a [Proxy] to a new JavaScript map or list created defined via
* Dart map or list.
*/
factory Proxy._json(data) {
if (_depth == 0) throw 'Cannot create Proxy out of scope.';
return _convert(data);
}
static _convert(data) {
return _deserialize(_jsPortConvert.callSync(_serializeDataTree(data)));
}
static _serializeDataTree(data) {
if (data is Map) {
final entries = new List();
for (var key in data.keys) {
entries.add([key, _serializeDataTree(data[key])]);
}
return ['map', entries];
} else if (data is List) {
return ['list', data.map((e) => _serializeDataTree(e)).toList()];
} else {
return ['simple', _serialize(data)];
}
}
Proxy._internal(this._port, this._id);
Proxy toJs() => this;
// Resolve whether this is needed.
operator[](arg) => _forward(this, '[]', 'method', [ arg ]);
// Resolve whether this is needed.
operator[]=(key, value) => _forward(this, '[]=', 'method', [ key, value ]);
// Test if this is equivalent to another Proxy. This essentially
// maps to JavaScript's == operator.
// TODO(vsm): Can we avoid forwarding to JS?
operator==(other) => identical(this, other)
? true
: (other is Proxy &&
_jsPortEquals.callSync([_serialize(this), _serialize(other)]));
// Forward member accesses to the backing JavaScript object.
noSuchMethod(InvocationMirror invocation) {
String member = invocation.memberName;
// If trying to access a JavaScript field/variable that starts with
// _ (underscore), Dart treats it a library private and member name
// it suffixed with '@internalLibraryIdentifier' which we have to
// strip before sending over to the JS side.
if (member.indexOf('@') != -1) {
member = member.substring(0, member.indexOf('@'));
}
String kind;
List args = invocation.positionalArguments;
if (args == null) args = [];
// TODO(vsm): Clean this up once InvocationMirrors settle down. The 'get:'
// and 'set:' form is still used by Dartium and the trunk version of
// Dart2JS.
if (invocation.isGetter) {
kind = 'get';
if (member.startsWith('get:')) {
member = member.substring(4);
}
} else if (invocation.isSetter) {
kind = 'set';
if (member.endsWith('=')) {
member = member.substring(0, member.length - 1);
}
if (member.startsWith('set:')) {
member = member.substring(4);
}
} else if (member.startsWith('get:')) {
kind = 'get';
member = member.substring(4);
} else if (member.startsWith('set:')) {
kind = 'set';
member = member.substring(4);