Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(99)

Side by Side Diff: sdk/lib/js/dartium/js_dartium.dart

Issue 15782009: RFC: introduce dart:js (Closed) Base URL: http://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: remove all scope handlings Created 7 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(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 /**
6 * The js.dart library provides simple JavaScript invocation from Dart that
7 * works on both Dartium and on other modern browsers via Dart2JS.
8 *
9 * It provides a model based on scoped [JsObject] objects. Proxies give Dart
10 * code access to JavaScript objects, fields, and functions as well as the
11 * ability to pass Dart objects and functions to JavaScript functions. Scopes
12 * enable developers to use proxies without memory leaks - a common challenge
13 * with cross-runtime interoperation.
14 *
15 * The top-level [context] getter provides a [JsObject] to the global JavaScript
16 * context for the page your Dart code is running on. In the following example:
17 *
18 * import 'dart:js';
19 *
20 * void main() {
21 * context.callMethod('alert', ['Hello from Dart via JavaScript']);
22 * }
23 *
24 * context['alert'] creates a proxy to the top-level alert function in
25 * JavaScript. It is invoked from Dart as a regular function that forwards to
26 * the underlying JavaScript one. By default, proxies are released when
27 * the currently executing event completes, e.g., when main is completes
28 * in this example.
29 *
30 * The library also enables JavaScript proxies to Dart objects and functions.
31 * For example, the following Dart code:
32 *
33 * context['dartCallback'] = new Callback.once((x) => print(x*2));
34 *
35 * defines a top-level JavaScript function 'dartCallback' that is a proxy to
36 * the corresponding Dart function. The [Callback.once] constructor allows the
37 * proxy to the Dart function to be retained across multiple events;
38 * instead it is released after the first invocation. (This is a common
39 * pattern for asychronous callbacks.)
40 *
41 * Note, parameters and return values are intuitively passed by value for
42 * primitives and by reference for non-primitives. In the latter case, the
43 * references are automatically wrapped and unwrapped as proxies by the library.
44 *
45 * This library also allows construction of JavaScripts objects given a
46 * [JsObject] to a corresponding JavaScript constructor. For example, if the
47 * following JavaScript is loaded on the page:
48 *
49 * function Foo(x) {
50 * this.x = x;
51 * }
52 *
53 * Foo.prototype.add = function(other) {
54 * return new Foo(this.x + other.x);
55 * }
56 *
57 * then, the following Dart:
58 *
59 * var foo = new JsObject(context['Foo'], [42]);
60 * var foo2 = foo.callMethod('add', [foo]);
61 * print(foo2['x']);
62 *
63 * will construct a JavaScript Foo object with the parameter 42, invoke its
64 * add method, and return a [JsObject] to a new Foo object whose x field is 84.
65 */
66
67 library dart.js;
68
69 import 'dart:html';
70 import 'dart:isolate';
71
72 // Global ports to manage communication from Dart to JS.
73 SendPortSync _jsPortSync = window.lookupPort('dart-js-context');
74 SendPortSync _jsPortCreate = window.lookupPort('dart-js-create');
75 SendPortSync _jsPortEquals = window.lookupPort('dart-js-equals');
76 SendPortSync _jsPortInstanceof = window.lookupPort('dart-js-instanceof');
77 SendPortSync _jsPortDeleteProperty = window.lookupPort('dart-js-delete-property' );
78 SendPortSync _jsPortConvert = window.lookupPort('dart-js-convert');
79
80 /**
81 * Returns a proxy to the global JavaScript context for this page.
82 */
83 JsObject get context => _deserialize(_jsPortSync.callSync([]));
84
85 /**
86 * Converts a json-like [data] to a JavaScript map or array and return a
87 * [JsObject] to it.
88 */
89 JsObject jsify(dynamic data) => data == null ? null : new JsObject._json(data);
90
91 /**
92 * Converts a local Dart function to a callback that can be passed to
93 * JavaScript.
94 */
95 class Callback implements Serializable<JsFunction> {
96 JsFunction _f;
97
98 Callback._(Function f, bool withThis) {
99 final id = _proxiedObjectTable.add((List args) {
100 final arguments = new List.from(args);
101 if (!withThis) arguments.removeAt(0);
102 return Function.apply(f, arguments);
103 });
104 _f = new JsFunction._internal(_proxiedObjectTable.sendPort, id);
105 }
106
107 factory Callback(Function f) => new Callback._(f, false);
108 factory Callback.withThis(Function f) => new Callback._(f, true);
109
110 JsFunction toJs() => _f;
111 }
112
113 /**
114 * Proxies to JavaScript objects.
115 */
116 class JsObject implements Serializable<JsObject> {
117 final SendPortSync _port;
118 final String _id;
119
120 /**
121 * Constructs a [JsObject] to a new JavaScript object by invoking a (proxy to
122 * a) JavaScript [constructor]. The [arguments] list should contain either
123 * primitive values, DOM elements, or Proxies.
124 */
125 factory JsObject(Serializable<JsFunction> constructor, [List arguments]) {
126 final params = [constructor];
127 if (arguments != null) params.addAll(arguments);
128 final serialized = params.map(_serialize).toList();
129 final result = _jsPortCreate.callSync(serialized);
130 return _deserialize(result);
131 }
132
133 /**
134 * Constructs a [JsObject] to a new JavaScript map or list created defined via
135 * Dart map or list.
136 */
137 factory JsObject._json(data) => _convert(data);
138
139 static _convert(data) =>
140 _deserialize(_jsPortConvert.callSync(_serializeDataTree(data)));
141
142 static _serializeDataTree(data) {
143 if (data is Map) {
144 final entries = new List();
145 for (var key in data.keys) {
146 entries.add([key, _serializeDataTree(data[key])]);
147 }
148 return ['map', entries];
149 } else if (data is Iterable) {
150 return ['list', data.map(_serializeDataTree).toList()];
151 } else {
152 return ['simple', _serialize(data)];
153 }
154 }
155
156 JsObject._internal(this._port, this._id);
157
158 JsObject toJs() => this;
159
160 // Resolve whether this is needed.
161 operator[](arg) => _forward(this, '[]', 'method', [ arg ]);
162
163 // Resolve whether this is needed.
164 operator[]=(key, value) => _forward(this, '[]=', 'method', [ key, value ]);
165
166 // Test if this is equivalent to another Proxy. This essentially
167 // maps to JavaScript's == operator.
168 // TODO(vsm): Can we avoid forwarding to JS?
169 operator==(other) => identical(this, other)
170 ? true
171 : (other is JsObject &&
172 _jsPortEquals.callSync([_serialize(this), _serialize(other)]));
173
174 /**
175 * Check if this [JsObject] has a [name] property.
176 */
177 bool hasProperty(String name) => _forward(this, name, 'hasProperty', []);
178
179 /**
180 * Delete the [name] property.
181 */
182 void deleteProperty(String name) {
183 _jsPortDeleteProperty.callSync([this, name].map(_serialize).toList());
184 }
185
186 /**
187 * Check if this [JsObject] is instance of [type].
188 */
189 bool instanceof(Serializable<JsFunction> type) =>
190 _jsPortInstanceof.callSync([this, type].map(_serialize).toList());
191
192 String toString() {
193 try {
194 return _forward(this, 'toString', 'method', []);
195 } catch(e) {
196 return super.toString();
197 }
198 }
199
200 callMethod(String name, [List args]) {
201 return _forward(this, name, 'method', args != null ? args : []);
202 }
203
204 // Forward member accesses to the backing JavaScript object.
205 static _forward(JsObject receiver, String member, String kind, List args) {
206 var result = receiver._port.callSync([receiver._id, member, kind,
207 args.map(_serialize).toList()]);
208 switch (result[0]) {
209 case 'return': return _deserialize(result[1]);
210 case 'throws': throw _deserialize(result[1]);
211 case 'none': throw new NoSuchMethodError(receiver, member, args, {});
212 default: throw 'Invalid return value';
213 }
214 }
215 }
216
217 /// A [JsObject] subtype to JavaScript functions.
218 class JsFunction extends JsObject implements Serializable<JsFunction> {
219 JsFunction._internal(SendPortSync port, String id)
220 : super._internal(port, id);
221
222 apply(thisArg, [List args]) {
223 return JsObject._forward(this, '', 'apply',
224 [thisArg]..addAll(args == null ? [] : args));
225 }
226 }
227
228 /// Marker class used to indicate it is serializable to js. If a class is a
229 /// [Serializable] the "toJs" method will be called and the result will be used
230 /// as value.
231 abstract class Serializable<T> {
232 T toJs();
233 }
234
235 // A table to managed local Dart objects that are proxied in JavaScript.
236 class _ProxiedObjectTable {
237 // Debugging name.
238 final String _name;
239
240 // Generator for unique IDs.
241 int _nextId;
242
243 // Table of IDs to Dart objects.
244 final Map<String, Object> _registry;
245
246 // Port to handle and forward requests to the underlying Dart objects.
247 // A remote proxy is uniquely identified by an ID and SendPortSync.
248 final ReceivePortSync _port;
249
250 _ProxiedObjectTable() :
251 _name = 'dart-ref',
252 _nextId = 0,
253 _registry = {},
254 _port = new ReceivePortSync() {
255 _port.receive((msg) {
256 try {
257 final receiver = _registry[msg[0]];
258 final method = msg[1];
259 final args = msg[2].map(_deserialize).toList();
260 if (method == '#call') {
261 final func = receiver as Function;
262 var result = _serialize(func(args));
263 return ['return', result];
264 } else {
265 // TODO(vsm): Support a mechanism to register a handler here.
266 throw 'Invocation unsupported on non-function Dart proxies';
267 }
268 } catch (e) {
269 // TODO(vsm): callSync should just handle exceptions itself.
270 return ['throws', '$e'];
271 }
272 });
273 }
274
275 // Adds a new object to the table and return a new ID for it.
276 String add(x) {
277 // TODO(vsm): Cache x and reuse id.
278 final id = '$_name-${_nextId++}';
279 _registry[id] = x;
280 return id;
281 }
282
283 // Gets an object by ID.
284 Object get(String id) {
285 return _registry[id];
286 }
287
288 // Gets the current number of objects kept alive by this table.
289 get count => _registry.length;
290
291 // Gets a send port for this table.
292 get sendPort => _port.toSendPort();
293 }
294
295 // The singleton to manage proxied Dart objects.
296 _ProxiedObjectTable _proxiedObjectTable = new _ProxiedObjectTable();
297
298 /// End of proxy implementation.
299
300 // Dart serialization support.
301
302 _serialize(var message) {
303 if (message == null) {
304 return null; // Convert undefined to null.
305 } else if (message is String ||
306 message is num ||
307 message is bool) {
308 // Primitives are passed directly through.
309 return message;
310 } else if (message is SendPortSync) {
311 // Non-proxied objects are serialized.
312 return message;
313 } else if (message is JsFunction) {
314 // Remote function proxy.
315 return [ 'funcref', message._id, message._port ];
316 } else if (message is JsObject) {
317 // Remote object proxy.
318 return [ 'objref', message._id, message._port ];
319 } else if (message is Serializable) {
320 // use of result of toJs()
321 return _serialize(message.toJs());
322 } else if (message is Function) {
323 return _serialize(new Callback(message));
324 } else {
325 // Local object proxy.
326 return [ 'objref',
327 _proxiedObjectTable.add(message),
328 _proxiedObjectTable.sendPort ];
329 }
330 }
331
332 _deserialize(var message) {
333 deserializeFunction(message) {
334 var id = message[1];
335 var port = message[2];
336 if (port == _proxiedObjectTable.sendPort) {
337 // Local function.
338 return _proxiedObjectTable.get(id);
339 } else {
340 // Remote function. Forward to its port.
341 return new JsFunction._internal(port, id);
342 }
343 }
344
345 deserializeObject(message) {
346 var id = message[1];
347 var port = message[2];
348 if (port == _proxiedObjectTable.sendPort) {
349 // Local object.
350 return _proxiedObjectTable.get(id);
351 } else {
352 // Remote object.
353 return new JsObject._internal(port, id);
354 }
355 }
356
357 if (message == null) {
358 return null; // Convert undefined to null.
359 } else if (message is String ||
360 message is num ||
361 message is bool) {
362 // Primitives are passed directly through.
363 return message;
364 } else if (message is SendPortSync) {
365 // Serialized type.
366 return message;
367 }
368 var tag = message[0];
369 switch (tag) {
370 case 'funcref': return deserializeFunction(message);
371 case 'objref': return deserializeObject(message);
372 }
373 throw 'Unsupported serialized data: $message';
374 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698