OLD | NEW |
1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file | 1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file |
2 // for details. All rights reserved. Use of this source code is governed by a | 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. | 3 // BSD-style license that can be found in the LICENSE file. |
4 | 4 |
5 // Patch file for the dart:isolate library. | 5 // Patch file for the dart:isolate library. |
6 | 6 |
| 7 import 'dart:uri'; |
| 8 |
| 9 /** |
| 10 * Called by the compiler to support switching |
| 11 * between isolates when we get a callback from the DOM. |
| 12 */ |
| 13 void _callInIsolate(_IsolateContext isolate, Function function) { |
| 14 isolate.eval(function); |
| 15 _globalState.topEventLoop.run(); |
| 16 } |
| 17 |
| 18 /** |
| 19 * Called by the compiler to fetch the current isolate context. |
| 20 */ |
| 21 _IsolateContext _currentIsolate() => _globalState.currentContext; |
| 22 |
| 23 /******************************************************** |
| 24 Inserted from lib/isolate/dart2js/compiler_hooks.dart |
| 25 ********************************************************/ |
| 26 |
| 27 /** |
| 28 * Wrapper that takes the dart entry point and runs it within an isolate. The |
| 29 * dart2js compiler will inject a call of the form |
| 30 * [: startRootIsolate(main); :] when it determines that this wrapping |
| 31 * is needed. For single-isolate applications (e.g. hello world), this |
| 32 * call is not emitted. |
| 33 */ |
| 34 void startRootIsolate(entry) { |
| 35 _globalState = new _Manager(); |
| 36 |
| 37 // Don't start the main loop again, if we are in a worker. |
| 38 if (_globalState.isWorker) return; |
| 39 final rootContext = new _IsolateContext(); |
| 40 _globalState.rootContext = rootContext; |
| 41 _fillStatics(rootContext); |
| 42 |
| 43 // BUG(5151491): Setting currentContext should not be necessary, but |
| 44 // because closures passed to the DOM as event handlers do not bind their |
| 45 // isolate automatically we try to give them a reasonable context to live in |
| 46 // by having a "default" isolate (the first one created). |
| 47 _globalState.currentContext = rootContext; |
| 48 |
| 49 rootContext.eval(entry); |
| 50 _globalState.topEventLoop.run(); |
| 51 } |
| 52 |
| 53 /******************************************************** |
| 54 Inserted from lib/isolate/dart2js/isolateimpl.dart |
| 55 ********************************************************/ |
| 56 |
| 57 /** |
| 58 * Concepts used here: |
| 59 * |
| 60 * "manager" - A manager contains one or more isolates, schedules their |
| 61 * execution, and performs other plumbing on their behalf. The isolate |
| 62 * present at the creation of the manager is designated as its "root isolate". |
| 63 * A manager may, for example, be implemented on a web Worker. |
| 64 * |
| 65 * [_Manager] - State present within a manager (exactly once, as a global). |
| 66 * |
| 67 * [_ManagerStub] - A handle held within one manager that allows interaction |
| 68 * with another manager. A target manager may be addressed by zero or more |
| 69 * [_ManagerStub]s. |
| 70 * |
| 71 */ |
| 72 |
| 73 /** |
| 74 * A native object that is shared across isolates. This object is visible to all |
| 75 * isolates running under the same manager (either UI or background web worker). |
| 76 * |
| 77 * This is code that is intended to 'escape' the isolate boundaries in order to |
| 78 * implement the semantics of isolates in JavaScript. Without this we would have |
| 79 * been forced to implement more code (including the top-level event loop) in |
| 80 * JavaScript itself. |
| 81 */ |
| 82 // TODO(eub, sigmund): move the "manager" to be entirely in JS. |
| 83 // Running any Dart code outside the context of an isolate gives it |
| 84 // the change to break the isolate abstraction. |
| 85 _Manager get _globalState => JS("_Manager", r"$globalState"); |
| 86 set _globalState(_Manager val) { |
| 87 JS("void", r"$globalState = #", val); |
| 88 } |
| 89 |
| 90 void _fillStatics(context) { |
| 91 JS("void", r"$globals = #.isolateStatics", context); |
| 92 JS("void", r"$static_init()"); |
| 93 } |
| 94 |
| 95 ReceivePort _lazyPort; |
7 patch ReceivePort get port { | 96 patch ReceivePort get port { |
8 if (lazyPort == null) { | 97 if (_lazyPort == null) { |
9 lazyPort = new ReceivePort(); | 98 _lazyPort = new ReceivePort(); |
10 } | 99 } |
11 return lazyPort; | 100 return _lazyPort; |
12 } | 101 } |
13 | 102 |
14 patch SendPort spawnFunction(void topLevelFunction()) { | 103 patch SendPort spawnFunction(void topLevelFunction()) { |
15 return IsolateNatives.spawnFunction(topLevelFunction); | 104 final name = _IsolateNatives._getJSFunctionName(topLevelFunction); |
| 105 if (name == null) { |
| 106 throw new UnsupportedError( |
| 107 "only top-level functions can be spawned."); |
| 108 } |
| 109 return _IsolateNatives._spawn(name, null, false); |
16 } | 110 } |
17 | 111 |
18 patch SendPort spawnUri(String uri) { | 112 patch SendPort spawnUri(String uri) { |
19 return IsolateNatives.spawn(null, uri, false); | 113 return _IsolateNatives._spawn(null, uri, false); |
20 } | 114 } |
21 | 115 |
| 116 /** State associated with the current manager. See [globalState]. */ |
| 117 // TODO(sigmund): split in multiple classes: global, thread, main-worker states? |
| 118 class _Manager { |
| 119 |
| 120 /** Next available isolate id within this [_Manager]. */ |
| 121 int nextIsolateId = 0; |
| 122 |
| 123 /** id assigned to this [_Manager]. */ |
| 124 int currentManagerId = 0; |
| 125 |
| 126 /** |
| 127 * Next available manager id. Only used by the main manager to assign a unique |
| 128 * id to each manager created by it. |
| 129 */ |
| 130 int nextManagerId = 1; |
| 131 |
| 132 /** Context for the currently running [Isolate]. */ |
| 133 _IsolateContext currentContext = null; |
| 134 |
| 135 /** Context for the root [Isolate] that first run in this [_Manager]. */ |
| 136 _IsolateContext rootContext = null; |
| 137 |
| 138 /** The top-level event loop. */ |
| 139 _EventLoop topEventLoop; |
| 140 |
| 141 /** Whether this program is running from the command line. */ |
| 142 bool fromCommandLine; |
| 143 |
| 144 /** Whether this [_Manager] is running as a web worker. */ |
| 145 bool isWorker; |
| 146 |
| 147 /** Whether we support spawning web workers. */ |
| 148 bool supportsWorkers; |
| 149 |
| 150 /** |
| 151 * Whether to use web workers when implementing isolates. Set to false for |
| 152 * debugging/testing. |
| 153 */ |
| 154 bool get useWorkers => supportsWorkers; |
| 155 |
| 156 /** |
| 157 * Whether to use the web-worker JSON-based message serialization protocol. By |
| 158 * default this is only used with web workers. For debugging, you can force |
| 159 * using this protocol by changing this field value to [true]. |
| 160 */ |
| 161 bool get needSerialization => useWorkers; |
| 162 |
| 163 /** |
| 164 * Registry of isolates. Isolates must be registered if, and only if, receive |
| 165 * ports are alive. Normally no open receive-ports means that the isolate is |
| 166 * dead, but DOM callbacks could resurrect it. |
| 167 */ |
| 168 Map<int, _IsolateContext> isolates; |
| 169 |
| 170 /** Reference to the main [_Manager]. Null in the main [_Manager] itself. */ |
| 171 _ManagerStub mainManager; |
| 172 |
| 173 /** Registry of active [_ManagerStub]s. Only used in the main [_Manager]. */ |
| 174 Map<int, _ManagerStub> managers; |
| 175 |
| 176 _Manager() { |
| 177 _nativeDetectEnvironment(); |
| 178 topEventLoop = new _EventLoop(); |
| 179 isolates = new Map<int, _IsolateContext>(); |
| 180 managers = new Map<int, _ManagerStub>(); |
| 181 if (isWorker) { // "if we are not the main manager ourself" is the intent. |
| 182 mainManager = new _MainManagerStub(); |
| 183 _nativeInitWorkerMessageHandler(); |
| 184 } |
| 185 } |
| 186 |
| 187 void _nativeDetectEnvironment() { |
| 188 isWorker = JS("bool", r"$isWorker"); |
| 189 supportsWorkers = JS("bool", r"$supportsWorkers"); |
| 190 fromCommandLine = JS("bool", r"typeof(window) == 'undefined'"); |
| 191 } |
| 192 |
| 193 void _nativeInitWorkerMessageHandler() { |
| 194 JS("void", r""" |
| 195 $globalThis.onmessage = function (e) { |
| 196 _IsolateNatives._processWorkerMessage(this.mainManager, e); |
| 197 }"""); |
| 198 } |
| 199 /*: TODO: check that _processWorkerMessage is not discarded while treeshaking. |
| 200 """ { |
| 201 _IsolateNatives._processWorkerMessage(null, null); |
| 202 } |
| 203 */ |
| 204 |
| 205 |
| 206 /** Close the worker running this code if all isolates are done. */ |
| 207 void maybeCloseWorker() { |
| 208 if (isolates.isEmpty) { |
| 209 mainManager.postMessage(_serializeMessage({'command': 'close'})); |
| 210 } |
| 211 } |
| 212 } |
| 213 |
| 214 /** Context information tracked for each isolate. */ |
| 215 class _IsolateContext { |
| 216 /** Current isolate id. */ |
| 217 int id; |
| 218 |
| 219 /** Registry of receive ports currently active on this isolate. */ |
| 220 Map<int, ReceivePort> ports; |
| 221 |
| 222 /** Holds isolate globals (statics and top-level properties). */ |
| 223 var isolateStatics; // native object containing all globals of an isolate. |
| 224 |
| 225 _IsolateContext() { |
| 226 id = _globalState.nextIsolateId++; |
| 227 ports = new Map<int, ReceivePort>(); |
| 228 initGlobals(); |
| 229 } |
| 230 |
| 231 // these are filled lazily the first time the isolate starts running. |
| 232 void initGlobals() { JS("void", r'$initGlobals(#)', this); } |
| 233 |
| 234 /** |
| 235 * Run [code] in the context of the isolate represented by [this]. Note this |
| 236 * is called from JavaScript (see $wrap_call in corejs.dart). |
| 237 */ |
| 238 dynamic eval(Function code) { |
| 239 var old = _globalState.currentContext; |
| 240 _globalState.currentContext = this; |
| 241 this._setGlobals(); |
| 242 var result = null; |
| 243 try { |
| 244 result = code(); |
| 245 } finally { |
| 246 _globalState.currentContext = old; |
| 247 if (old != null) old._setGlobals(); |
| 248 } |
| 249 return result; |
| 250 } |
| 251 |
| 252 void _setGlobals() { JS("void", r'$setGlobals(#)', this); } |
| 253 |
| 254 /** Lookup a port registered for this isolate. */ |
| 255 ReceivePort lookup(int portId) => ports[portId]; |
| 256 |
| 257 /** Register a port on this isolate. */ |
| 258 void register(int portId, ReceivePort port) { |
| 259 if (ports.containsKey(portId)) { |
| 260 throw new Exception("Registry: ports must be registered only once."); |
| 261 } |
| 262 ports[portId] = port; |
| 263 _globalState.isolates[id] = this; // indicate this isolate is active |
| 264 } |
| 265 |
| 266 /** Unregister a port on this isolate. */ |
| 267 void unregister(int portId) { |
| 268 ports.remove(portId); |
| 269 if (ports.isEmpty) { |
| 270 _globalState.isolates.remove(id); // indicate this isolate is not active |
| 271 } |
| 272 } |
| 273 } |
| 274 |
| 275 /** Represent the event loop on a javascript thread (DOM or worker). */ |
| 276 class _EventLoop { |
| 277 Queue<_IsolateEvent> events; |
| 278 |
| 279 _EventLoop() : events = new Queue<_IsolateEvent>(); |
| 280 |
| 281 void enqueue(isolate, fn, msg) { |
| 282 events.addLast(new _IsolateEvent(isolate, fn, msg)); |
| 283 } |
| 284 |
| 285 _IsolateEvent dequeue() { |
| 286 if (events.isEmpty) return null; |
| 287 return events.removeFirst(); |
| 288 } |
| 289 |
| 290 /** Process a single event, if any. */ |
| 291 bool runIteration() { |
| 292 final event = dequeue(); |
| 293 if (event == null) { |
| 294 if (_globalState.isWorker) { |
| 295 _globalState.maybeCloseWorker(); |
| 296 } else if (_globalState.rootContext != null && |
| 297 _globalState.isolates.containsKey( |
| 298 _globalState.rootContext.id) && |
| 299 _globalState.fromCommandLine && |
| 300 _globalState.rootContext.ports.isEmpty) { |
| 301 // We want to reach here only on the main [_Manager] and only |
| 302 // on the command-line. In the browser the isolate might |
| 303 // still be alive due to DOM callbacks, but the presumption is |
| 304 // that on the command-line, no future events can be injected |
| 305 // into the event queue once it's empty. Node has setTimeout |
| 306 // so this presumption is incorrect there. We think(?) that |
| 307 // in d8 this assumption is valid. |
| 308 throw new Exception("Program exited with open ReceivePorts."); |
| 309 } |
| 310 return false; |
| 311 } |
| 312 event.process(); |
| 313 return true; |
| 314 } |
| 315 |
| 316 /** |
| 317 * Runs multiple iterations of the run-loop. If possible, each iteration is |
| 318 * run asynchronously. |
| 319 */ |
| 320 void _runHelper() { |
| 321 // [_window] is defined in timer_provider.dart. |
| 322 if (_window != null) { |
| 323 // Run each iteration from the browser's top event loop. |
| 324 void next() { |
| 325 if (!runIteration()) return; |
| 326 _window.setTimeout(next, 0); |
| 327 } |
| 328 next(); |
| 329 } else { |
| 330 // Run synchronously until no more iterations are available. |
| 331 while (runIteration()) {} |
| 332 } |
| 333 } |
| 334 |
| 335 /** |
| 336 * Call [_runHelper] but ensure that worker exceptions are propragated. Note |
| 337 * this is called from JavaScript (see $wrap_call in corejs.dart). |
| 338 */ |
| 339 void run() { |
| 340 if (!_globalState.isWorker) { |
| 341 _runHelper(); |
| 342 } else { |
| 343 try { |
| 344 _runHelper(); |
| 345 } catch (e, trace) { |
| 346 _globalState.mainManager.postMessage(_serializeMessage( |
| 347 {'command': 'error', 'msg': '$e\n$trace' })); |
| 348 } |
| 349 } |
| 350 } |
| 351 } |
| 352 |
| 353 /** An event in the top-level event queue. */ |
| 354 class _IsolateEvent { |
| 355 _IsolateContext isolate; |
| 356 Function fn; |
| 357 String message; |
| 358 |
| 359 _IsolateEvent(this.isolate, this.fn, this.message); |
| 360 |
| 361 void process() { |
| 362 isolate.eval(fn); |
| 363 } |
| 364 } |
| 365 |
| 366 /** An interface for a stub used to interact with a manager. */ |
| 367 abstract class _ManagerStub { |
| 368 get id; |
| 369 void set id(int i); |
| 370 void set onmessage(Function f); |
| 371 void postMessage(msg); |
| 372 void terminate(); |
| 373 } |
| 374 |
| 375 /** A stub for interacting with the main manager. */ |
| 376 class _MainManagerStub implements _ManagerStub { |
| 377 get id => 0; |
| 378 void set id(int i) { throw new UnimplementedError(); } |
| 379 void set onmessage(f) { |
| 380 throw new Exception("onmessage should not be set on MainManagerStub"); |
| 381 } |
| 382 void postMessage(msg) { JS("void", r"$globalThis.postMessage(#)", msg); } |
| 383 void terminate() {} // Nothing useful to do here. |
| 384 } |
| 385 |
| 386 /** |
| 387 * A stub for interacting with a manager built on a web worker. This |
| 388 * definition uses a 'hidden' type (* prefix on the native name) to |
| 389 * enforce that the type is defined dynamically only when web workers |
| 390 * are actually available. |
| 391 */ |
| 392 class _WorkerStub implements _ManagerStub native "*Worker" { |
| 393 get id => JS("var", "#.id", this); |
| 394 void set id(i) { JS("void", "#.id = #", this, i); } |
| 395 void set onmessage(f) { JS("void", "#.onmessage = #", this, f); } |
| 396 void postMessage(msg) => JS("void", "#.postMessage(#)", this, msg); |
| 397 // terminate() is implemented by Worker. |
| 398 void terminate(); |
| 399 } |
| 400 |
| 401 const String _SPAWNED_SIGNAL = "spawned"; |
| 402 |
| 403 class _IsolateNatives { |
| 404 |
| 405 /** |
| 406 * The src url for the script tag that loaded this code. Used to create |
| 407 * JavaScript workers. |
| 408 */ |
| 409 static String get _thisScript => JS("String", r"$thisScriptUrl"); |
| 410 |
| 411 /** Starts a new worker with the given URL. */ |
| 412 static _WorkerStub _newWorker(url) => JS("_WorkerStub", r"new Worker(#)", url)
; |
| 413 |
| 414 /** |
| 415 * Assume that [e] is a browser message event and extract its message data. |
| 416 * We don't import the dom explicitly so, when workers are disabled, this |
| 417 * library can also run on top of nodejs. |
| 418 */ |
| 419 //static _getEventData(e) => JS("Object", "#.data", e); |
| 420 static _getEventData(e) => JS("", "#.data", e); |
| 421 |
| 422 /** |
| 423 * Process messages on a worker, either to control the worker instance or to |
| 424 * pass messages along to the isolate running in the worker. |
| 425 */ |
| 426 static void _processWorkerMessage(sender, e) { |
| 427 var msg = _deserializeMessage(_getEventData(e)); |
| 428 switch (msg['command']) { |
| 429 case 'start': |
| 430 _globalState.currentManagerId = msg['id']; |
| 431 Function entryPoint = _getJSFunctionFromName(msg['functionName']); |
| 432 var replyTo = _deserializeMessage(msg['replyTo']); |
| 433 _globalState.topEventLoop.enqueue(new _IsolateContext(), function() { |
| 434 _startIsolate(entryPoint, replyTo); |
| 435 }, 'worker-start'); |
| 436 _globalState.topEventLoop.run(); |
| 437 break; |
| 438 case 'spawn-worker': |
| 439 _spawnWorker(msg['functionName'], msg['uri'], msg['replyPort']); |
| 440 break; |
| 441 case 'message': |
| 442 msg['port'].send(msg['msg'], msg['replyTo']); |
| 443 _globalState.topEventLoop.run(); |
| 444 break; |
| 445 case 'close': |
| 446 _log("Closing Worker"); |
| 447 _globalState.managers.remove(sender.id); |
| 448 sender.terminate(); |
| 449 _globalState.topEventLoop.run(); |
| 450 break; |
| 451 case 'log': |
| 452 _log(msg['msg']); |
| 453 break; |
| 454 case 'print': |
| 455 if (_globalState.isWorker) { |
| 456 _globalState.mainManager.postMessage( |
| 457 _serializeMessage({'command': 'print', 'msg': msg})); |
| 458 } else { |
| 459 print(msg['msg']); |
| 460 } |
| 461 break; |
| 462 case 'error': |
| 463 throw msg['msg']; |
| 464 } |
| 465 } |
| 466 |
| 467 /** Log a message, forwarding to the main [_Manager] if appropriate. */ |
| 468 static _log(msg) { |
| 469 if (_globalState.isWorker) { |
| 470 _globalState.mainManager.postMessage( |
| 471 _serializeMessage({'command': 'log', 'msg': msg })); |
| 472 } else { |
| 473 try { |
| 474 _consoleLog(msg); |
| 475 } catch (e, trace) { |
| 476 throw new Exception(trace); |
| 477 } |
| 478 } |
| 479 } |
| 480 |
| 481 static void _consoleLog(msg) { |
| 482 JS("void", r"$globalThis.console.log(#)", msg); |
| 483 } |
| 484 |
| 485 /** |
| 486 * Extract the constructor of runnable, so it can be allocated in another |
| 487 * isolate. |
| 488 */ |
| 489 static dynamic _getJSConstructor(Isolate runnable) { |
| 490 return JS("Object", "#.constructor", runnable); |
| 491 } |
| 492 |
| 493 /** Extract the constructor name of a runnable */ |
| 494 // TODO(sigmund): find a browser-generic way to support this. |
| 495 // TODO(floitsch): is this function still used? If yes, should we use |
| 496 // Primitives.objectTypeName instead? |
| 497 static dynamic _getJSConstructorName(Isolate runnable) { |
| 498 return JS("Object", "#.constructor.name", runnable); |
| 499 } |
| 500 |
| 501 /** Find a constructor given its name. */ |
| 502 static dynamic _getJSConstructorFromName(String factoryName) { |
| 503 return JS("Object", r"$globalThis[#]", factoryName); |
| 504 } |
| 505 |
| 506 static dynamic _getJSFunctionFromName(String functionName) { |
| 507 return JS("Object", r"$globalThis[#]", functionName); |
| 508 } |
| 509 |
| 510 /** |
| 511 * Get a string name for the function, if possible. The result for |
| 512 * anonymous functions is browser-dependent -- it may be "" or "anonymous" |
| 513 * but you should probably not count on this. |
| 514 */ |
| 515 static String _getJSFunctionName(Function f) { |
| 516 return JS("Object", r"(#.$name || #)", f, null); |
| 517 } |
| 518 |
| 519 /** Create a new JavaScript object instance given its constructor. */ |
| 520 static dynamic _allocate(var ctor) { |
| 521 return JS("Object", "new #()", ctor); |
| 522 } |
| 523 |
| 524 // TODO(sigmund): clean up above, after we make the new API the default: |
| 525 |
| 526 static _spawn(String functionName, String uri, bool isLight) { |
| 527 Completer<SendPort> completer = new Completer<SendPort>(); |
| 528 ReceivePort port = new ReceivePort(); |
| 529 port.receive((msg, SendPort replyPort) { |
| 530 port.close(); |
| 531 assert(msg == _SPAWNED_SIGNAL); |
| 532 completer.complete(replyPort); |
| 533 }); |
| 534 |
| 535 SendPort signalReply = port.toSendPort(); |
| 536 |
| 537 if (_globalState.useWorkers && !isLight) { |
| 538 _startWorker(functionName, uri, signalReply); |
| 539 } else { |
| 540 _startNonWorker(functionName, uri, signalReply); |
| 541 } |
| 542 return new _BufferingSendPort( |
| 543 _globalState.currentContext.id, completer.future); |
| 544 } |
| 545 |
| 546 static SendPort _startWorker( |
| 547 String functionName, String uri, SendPort replyPort) { |
| 548 if (_globalState.isWorker) { |
| 549 _globalState.mainManager.postMessage(_serializeMessage({ |
| 550 'command': 'spawn-worker', |
| 551 'functionName': functionName, |
| 552 'uri': uri, |
| 553 'replyPort': replyPort})); |
| 554 } else { |
| 555 _spawnWorker(functionName, uri, replyPort); |
| 556 } |
| 557 } |
| 558 |
| 559 static SendPort _startNonWorker( |
| 560 String functionName, String uri, SendPort replyPort) { |
| 561 // TODO(eub): support IE9 using an iframe -- Dart issue 1702. |
| 562 if (uri != null) throw new UnsupportedError( |
| 563 "Currently spawnUri is not supported without web workers."); |
| 564 _globalState.topEventLoop.enqueue(new _IsolateContext(), function() { |
| 565 final func = _getJSFunctionFromName(functionName); |
| 566 _startIsolate(func, replyPort); |
| 567 }, 'nonworker start'); |
| 568 } |
| 569 |
| 570 static void _startIsolate(Function topLevel, SendPort replyTo) { |
| 571 _fillStatics(_globalState.currentContext); |
| 572 _lazyPort = new ReceivePort(); |
| 573 replyTo.send(_SPAWNED_SIGNAL, port.toSendPort()); |
| 574 |
| 575 topLevel(); |
| 576 } |
| 577 |
| 578 /** |
| 579 * Spawns an isolate in a worker. [factoryName] is the Javascript constructor |
| 580 * name for the isolate entry point class. |
| 581 */ |
| 582 static void _spawnWorker(functionName, uri, replyPort) { |
| 583 if (functionName == null) functionName = 'main'; |
| 584 if (uri == null) uri = _thisScript; |
| 585 if (!(new Uri.fromString(uri).isAbsolute())) { |
| 586 // The constructor of dom workers requires an absolute URL. If we use a |
| 587 // relative path we will get a DOM exception. |
| 588 String prefix = _thisScript.substring(0, _thisScript.lastIndexOf('/')); |
| 589 uri = "$prefix/$uri"; |
| 590 } |
| 591 final worker = _newWorker(uri); |
| 592 worker.onmessage = (e) { _processWorkerMessage(worker, e); }; |
| 593 var workerId = _globalState.nextManagerId++; |
| 594 // We also store the id on the worker itself so that we can unregister it. |
| 595 worker.id = workerId; |
| 596 _globalState.managers[workerId] = worker; |
| 597 worker.postMessage(_serializeMessage({ |
| 598 'command': 'start', |
| 599 'id': workerId, |
| 600 // Note: we serialize replyPort twice because the child worker needs to |
| 601 // first deserialize the worker id, before it can correctly deserialize |
| 602 // the port (port deserialization is sensitive to what is the current |
| 603 // workerId). |
| 604 'replyTo': _serializeMessage(replyPort), |
| 605 'functionName': functionName })); |
| 606 } |
| 607 } |
| 608 |
| 609 /******************************************************** |
| 610 Inserted from lib/isolate/dart2js/ports.dart |
| 611 ********************************************************/ |
| 612 |
| 613 /** Common functionality to all send ports. */ |
| 614 class _BaseSendPort implements SendPort { |
| 615 /** Id for the destination isolate. */ |
| 616 final int _isolateId; |
| 617 |
| 618 const _BaseSendPort(this._isolateId); |
| 619 |
| 620 void _checkReplyTo(SendPort replyTo) { |
| 621 if (replyTo != null |
| 622 && replyTo is! _NativeJsSendPort |
| 623 && replyTo is! _WorkerSendPort |
| 624 && replyTo is! _BufferingSendPort) { |
| 625 throw new Exception("SendPort.send: Illegal replyTo port type"); |
| 626 } |
| 627 } |
| 628 |
| 629 Future call(var message) { |
| 630 final completer = new Completer(); |
| 631 final port = new _ReceivePortImpl(); |
| 632 send(message, port.toSendPort()); |
| 633 port.receive((value, ignoreReplyTo) { |
| 634 port.close(); |
| 635 if (value is Exception) { |
| 636 completer.completeException(value); |
| 637 } else { |
| 638 completer.complete(value); |
| 639 } |
| 640 }); |
| 641 return completer.future; |
| 642 } |
| 643 |
| 644 void send(var message, [SendPort replyTo]); |
| 645 bool operator ==(var other); |
| 646 int get hashCode; |
| 647 } |
| 648 |
| 649 /** A send port that delivers messages in-memory via native JavaScript calls. */ |
| 650 class _NativeJsSendPort extends _BaseSendPort implements SendPort { |
| 651 final _ReceivePortImpl _receivePort; |
| 652 |
| 653 const _NativeJsSendPort(this._receivePort, int isolateId) : super(isolateId); |
| 654 |
| 655 void send(var message, [SendPort replyTo = null]) { |
| 656 _waitForPendingPorts([message, replyTo], () { |
| 657 _checkReplyTo(replyTo); |
| 658 // Check that the isolate still runs and the port is still open |
| 659 final isolate = _globalState.isolates[_isolateId]; |
| 660 if (isolate == null) return; |
| 661 if (_receivePort._callback == null) return; |
| 662 |
| 663 // We force serialization/deserialization as a simple way to ensure |
| 664 // isolate communication restrictions are respected between isolates that |
| 665 // live in the same worker. [_NativeJsSendPort] delivers both messages |
| 666 // from the same worker and messages from other workers. In particular, |
| 667 // messages sent from a worker via a [_WorkerSendPort] are received at |
| 668 // [_processWorkerMessage] and forwarded to a native port. In such cases, |
| 669 // here we'll see [_globalState.currentContext == null]. |
| 670 final shouldSerialize = _globalState.currentContext != null |
| 671 && _globalState.currentContext.id != _isolateId; |
| 672 var msg = message; |
| 673 var reply = replyTo; |
| 674 if (shouldSerialize) { |
| 675 msg = _serializeMessage(msg); |
| 676 reply = _serializeMessage(reply); |
| 677 } |
| 678 _globalState.topEventLoop.enqueue(isolate, () { |
| 679 if (_receivePort._callback != null) { |
| 680 if (shouldSerialize) { |
| 681 msg = _deserializeMessage(msg); |
| 682 reply = _deserializeMessage(reply); |
| 683 } |
| 684 _receivePort._callback(msg, reply); |
| 685 } |
| 686 }, 'receive $message'); |
| 687 }); |
| 688 } |
| 689 |
| 690 bool operator ==(var other) => (other is _NativeJsSendPort) && |
| 691 (_receivePort == other._receivePort); |
| 692 |
| 693 int get hashCode => _receivePort._id; |
| 694 } |
| 695 |
| 696 /** A send port that delivers messages via worker.postMessage. */ |
| 697 // TODO(eub): abstract this for iframes. |
| 698 class _WorkerSendPort extends _BaseSendPort implements SendPort { |
| 699 final int _workerId; |
| 700 final int _receivePortId; |
| 701 |
| 702 const _WorkerSendPort(this._workerId, int isolateId, this._receivePortId) |
| 703 : super(isolateId); |
| 704 |
| 705 void send(var message, [SendPort replyTo = null]) { |
| 706 _waitForPendingPorts([message, replyTo], () { |
| 707 _checkReplyTo(replyTo); |
| 708 final workerMessage = _serializeMessage({ |
| 709 'command': 'message', |
| 710 'port': this, |
| 711 'msg': message, |
| 712 'replyTo': replyTo}); |
| 713 |
| 714 if (_globalState.isWorker) { |
| 715 // communication from one worker to another go through the main worker: |
| 716 _globalState.mainManager.postMessage(workerMessage); |
| 717 } else { |
| 718 _globalState.managers[_workerId].postMessage(workerMessage); |
| 719 } |
| 720 }); |
| 721 } |
| 722 |
| 723 bool operator ==(var other) { |
| 724 return (other is _WorkerSendPort) && |
| 725 (_workerId == other._workerId) && |
| 726 (_isolateId == other._isolateId) && |
| 727 (_receivePortId == other._receivePortId); |
| 728 } |
| 729 |
| 730 int get hashCode { |
| 731 // TODO(sigmund): use a standard hash when we get one available in corelib. |
| 732 return (_workerId << 16) ^ (_isolateId << 8) ^ _receivePortId; |
| 733 } |
| 734 } |
| 735 |
| 736 /** A port that buffers messages until an underlying port gets resolved. */ |
| 737 class _BufferingSendPort extends _BaseSendPort implements SendPort { |
| 738 /** Internal counter to assign unique ids to each port. */ |
| 739 static int _idCount = 0; |
| 740 |
| 741 /** For implementing equals and hashcode. */ |
| 742 final int _id; |
| 743 |
| 744 /** Underlying port, when resolved. */ |
| 745 SendPort _port; |
| 746 |
| 747 /** |
| 748 * Future of the underlying port, so that we can detect when this port can be |
| 749 * sent on messages. |
| 750 */ |
| 751 Future<SendPort> _futurePort; |
| 752 |
| 753 /** Pending messages (and reply ports). */ |
| 754 List pending; |
| 755 |
| 756 _BufferingSendPort(isolateId, this._futurePort) |
| 757 : super(isolateId), _id = _idCount, pending = [] { |
| 758 _idCount++; |
| 759 _futurePort.then((p) { |
| 760 _port = p; |
| 761 for (final item in pending) { |
| 762 p.send(item['message'], item['replyTo']); |
| 763 } |
| 764 pending = null; |
| 765 }); |
| 766 } |
| 767 |
| 768 _BufferingSendPort.fromPort(isolateId, this._port) |
| 769 : super(isolateId), _id = _idCount { |
| 770 _idCount++; |
| 771 } |
| 772 |
| 773 void send(var message, [SendPort replyTo]) { |
| 774 if (_port != null) { |
| 775 _port.send(message, replyTo); |
| 776 } else { |
| 777 pending.add({'message': message, 'replyTo': replyTo}); |
| 778 } |
| 779 } |
| 780 |
| 781 bool operator ==(var other) => |
| 782 other is _BufferingSendPort && _id == other._id; |
| 783 int get hashCode => _id; |
| 784 } |
22 | 785 |
23 /** Default factory for receive ports. */ | 786 /** Default factory for receive ports. */ |
24 patch class ReceivePort { | 787 patch class ReceivePort { |
25 patch factory ReceivePort() { | 788 patch factory ReceivePort() { |
26 return new ReceivePortImpl(); | 789 return new _ReceivePortImpl(); |
| 790 } |
| 791 |
| 792 } |
| 793 |
| 794 /** Implementation of a multi-use [ReceivePort] on top of JavaScript. */ |
| 795 class _ReceivePortImpl implements ReceivePort { |
| 796 int _id; |
| 797 Function _callback; |
| 798 static int _nextFreeId = 1; |
| 799 |
| 800 _ReceivePortImpl() |
| 801 : _id = _nextFreeId++ { |
| 802 _globalState.currentContext.register(_id, this); |
| 803 } |
| 804 |
| 805 void receive(void onMessage(var message, SendPort replyTo)) { |
| 806 _callback = onMessage; |
| 807 } |
| 808 |
| 809 void close() { |
| 810 _callback = null; |
| 811 _globalState.currentContext.unregister(_id); |
| 812 } |
| 813 |
| 814 SendPort toSendPort() { |
| 815 return new _NativeJsSendPort(this, _globalState.currentContext.id); |
| 816 } |
| 817 } |
| 818 |
| 819 /** Wait until all ports in a message are resolved. */ |
| 820 _waitForPendingPorts(var message, void callback()) { |
| 821 final finder = new _PendingSendPortFinder(); |
| 822 finder.traverse(message); |
| 823 Futures.wait(finder.ports).then((_) => callback()); |
| 824 } |
| 825 |
| 826 |
| 827 /** Visitor that finds all unresolved [SendPort]s in a message. */ |
| 828 class _PendingSendPortFinder extends _MessageTraverser { |
| 829 List<Future<SendPort>> ports; |
| 830 _PendingSendPortFinder() : super(), ports = [] { |
| 831 _visited = new _JsVisitedMap(); |
| 832 } |
| 833 |
| 834 visitPrimitive(x) {} |
| 835 |
| 836 visitList(List list) { |
| 837 final seen = _visited[list]; |
| 838 if (seen != null) return; |
| 839 _visited[list] = true; |
| 840 // TODO(sigmund): replace with the following: (bug #1660) |
| 841 // list.forEach(_dispatch); |
| 842 list.forEach((e) => _dispatch(e)); |
| 843 } |
| 844 |
| 845 visitMap(Map map) { |
| 846 final seen = _visited[map]; |
| 847 if (seen != null) return; |
| 848 |
| 849 _visited[map] = true; |
| 850 // TODO(sigmund): replace with the following: (bug #1660) |
| 851 // map.values.forEach(_dispatch); |
| 852 map.values.forEach((e) => _dispatch(e)); |
| 853 } |
| 854 |
| 855 visitSendPort(SendPort port) { |
| 856 if (port is _BufferingSendPort && port._port == null) { |
| 857 ports.add(port._futurePort); |
| 858 } |
| 859 } |
| 860 } |
| 861 |
| 862 /******************************************************** |
| 863 Inserted from lib/isolate/dart2js/messages.dart |
| 864 ********************************************************/ |
| 865 |
| 866 // Defines message visitors, serialization, and deserialization. |
| 867 |
| 868 /** Serialize [message] (or simulate serialization). */ |
| 869 _serializeMessage(message) { |
| 870 if (_globalState.needSerialization) { |
| 871 return new _JsSerializer().traverse(message); |
| 872 } else { |
| 873 return new _JsCopier().traverse(message); |
| 874 } |
| 875 } |
| 876 |
| 877 /** Deserialize [message] (or simulate deserialization). */ |
| 878 _deserializeMessage(message) { |
| 879 if (_globalState.needSerialization) { |
| 880 return new _JsDeserializer().deserialize(message); |
| 881 } else { |
| 882 // Nothing more to do. |
| 883 return message; |
| 884 } |
| 885 } |
| 886 |
| 887 class _JsSerializer extends _Serializer { |
| 888 |
| 889 _JsSerializer() : super() { _visited = new _JsVisitedMap(); } |
| 890 |
| 891 visitSendPort(SendPort x) { |
| 892 if (x is _NativeJsSendPort) return visitNativeJsSendPort(x); |
| 893 if (x is _WorkerSendPort) return visitWorkerSendPort(x); |
| 894 if (x is _BufferingSendPort) return visitBufferingSendPort(x); |
| 895 throw "Illegal underlying port $x"; |
| 896 } |
| 897 |
| 898 visitNativeJsSendPort(_NativeJsSendPort port) { |
| 899 return ['sendport', _globalState.currentManagerId, |
| 900 port._isolateId, port._receivePort._id]; |
| 901 } |
| 902 |
| 903 visitWorkerSendPort(_WorkerSendPort port) { |
| 904 return ['sendport', port._workerId, port._isolateId, port._receivePortId]; |
| 905 } |
| 906 |
| 907 visitBufferingSendPort(_BufferingSendPort port) { |
| 908 if (port._port != null) { |
| 909 return visitSendPort(port._port); |
| 910 } else { |
| 911 // TODO(floitsch): Use real exception (which one?). |
| 912 throw |
| 913 "internal error: must call _waitForPendingPorts to ensure all" |
| 914 " ports are resolved at this point."; |
| 915 } |
| 916 } |
| 917 |
| 918 } |
| 919 |
| 920 |
| 921 class _JsCopier extends _Copier { |
| 922 |
| 923 _JsCopier() : super() { _visited = new _JsVisitedMap(); } |
| 924 |
| 925 visitSendPort(SendPort x) { |
| 926 if (x is _NativeJsSendPort) return visitNativeJsSendPort(x); |
| 927 if (x is _WorkerSendPort) return visitWorkerSendPort(x); |
| 928 if (x is _BufferingSendPort) return visitBufferingSendPort(x); |
| 929 throw "Illegal underlying port $p"; |
| 930 } |
| 931 |
| 932 SendPort visitNativeJsSendPort(_NativeJsSendPort port) { |
| 933 return new _NativeJsSendPort(port._receivePort, port._isolateId); |
| 934 } |
| 935 |
| 936 SendPort visitWorkerSendPort(_WorkerSendPort port) { |
| 937 return new _WorkerSendPort( |
| 938 port._workerId, port._isolateId, port._receivePortId); |
| 939 } |
| 940 |
| 941 SendPort visitBufferingSendPort(_BufferingSendPort port) { |
| 942 if (port._port != null) { |
| 943 return visitSendPort(port._port); |
| 944 } else { |
| 945 // TODO(floitsch): Use real exception (which one?). |
| 946 throw |
| 947 "internal error: must call _waitForPendingPorts to ensure all" |
| 948 " ports are resolved at this point."; |
| 949 } |
| 950 } |
| 951 |
| 952 } |
| 953 |
| 954 class _JsDeserializer extends _Deserializer { |
| 955 |
| 956 SendPort deserializeSendPort(List x) { |
| 957 int managerId = x[1]; |
| 958 int isolateId = x[2]; |
| 959 int receivePortId = x[3]; |
| 960 // If two isolates are in the same manager, we use NativeJsSendPorts to |
| 961 // deliver messages directly without using postMessage. |
| 962 if (managerId == _globalState.currentManagerId) { |
| 963 var isolate = _globalState.isolates[isolateId]; |
| 964 if (isolate == null) return null; // Isolate has been closed. |
| 965 var receivePort = isolate.lookup(receivePortId); |
| 966 return new _NativeJsSendPort(receivePort, isolateId); |
| 967 } else { |
| 968 return new _WorkerSendPort(managerId, isolateId, receivePortId); |
| 969 } |
| 970 } |
| 971 |
| 972 } |
| 973 |
| 974 class _JsVisitedMap implements _MessageTraverserVisitedMap { |
| 975 List tagged; |
| 976 |
| 977 /** Retrieves any information stored in the native object [object]. */ |
| 978 operator[](var object) { |
| 979 return _getAttachedInfo(object); |
| 980 } |
| 981 |
| 982 /** Injects some information into the native [object]. */ |
| 983 void operator[]=(var object, var info) { |
| 984 tagged.add(object); |
| 985 _setAttachedInfo(object, info); |
| 986 } |
| 987 |
| 988 /** Get ready to rumble. */ |
| 989 void reset() { |
| 990 assert(tagged == null); |
| 991 tagged = new List(); |
| 992 } |
| 993 |
| 994 /** Remove all information injected in the native objects. */ |
| 995 void cleanup() { |
| 996 for (int i = 0, length = tagged.length; i < length; i++) { |
| 997 _clearAttachedInfo(tagged[i]); |
| 998 } |
| 999 tagged = null; |
| 1000 } |
| 1001 |
| 1002 void _clearAttachedInfo(var o) { |
| 1003 JS("void", "#['__MessageTraverser__attached_info__'] = #", o, null); |
| 1004 } |
| 1005 |
| 1006 void _setAttachedInfo(var o, var info) { |
| 1007 JS("void", "#['__MessageTraverser__attached_info__'] = #", o, info); |
| 1008 } |
| 1009 |
| 1010 _getAttachedInfo(var o) { |
| 1011 return JS("", "#['__MessageTraverser__attached_info__']", o); |
| 1012 } |
| 1013 } |
| 1014 |
| 1015 // only visible for testing purposes |
| 1016 // TODO(sigmund): remove once we can disable privacy for testing (bug #1882) |
| 1017 class TestingOnly { |
| 1018 static copy(x) { |
| 1019 return new _JsCopier().traverse(x); |
| 1020 } |
| 1021 |
| 1022 // only visible for testing purposes |
| 1023 static serialize(x) { |
| 1024 _Serializer serializer = new _JsSerializer(); |
| 1025 _Deserializer deserializer = new _JsDeserializer(); |
| 1026 return deserializer.deserialize(serializer.traverse(x)); |
| 1027 } |
| 1028 } |
| 1029 |
| 1030 /******************************************************** |
| 1031 Inserted from lib/isolate/serialization.dart |
| 1032 ********************************************************/ |
| 1033 |
| 1034 class _MessageTraverserVisitedMap { |
| 1035 |
| 1036 operator[](var object) => null; |
| 1037 void operator[]=(var object, var info) { } |
| 1038 |
| 1039 void reset() { } |
| 1040 void cleanup() { } |
| 1041 |
| 1042 } |
| 1043 |
| 1044 /** Abstract visitor for dart objects that can be sent as isolate messages. */ |
| 1045 class _MessageTraverser { |
| 1046 |
| 1047 _MessageTraverserVisitedMap _visited; |
| 1048 _MessageTraverser() : _visited = new _MessageTraverserVisitedMap(); |
| 1049 |
| 1050 /** Visitor's entry point. */ |
| 1051 traverse(var x) { |
| 1052 if (isPrimitive(x)) return visitPrimitive(x); |
| 1053 _visited.reset(); |
| 1054 var result; |
| 1055 try { |
| 1056 result = _dispatch(x); |
| 1057 } finally { |
| 1058 _visited.cleanup(); |
| 1059 } |
| 1060 return result; |
| 1061 } |
| 1062 |
| 1063 _dispatch(var x) { |
| 1064 if (isPrimitive(x)) return visitPrimitive(x); |
| 1065 if (x is List) return visitList(x); |
| 1066 if (x is Map) return visitMap(x); |
| 1067 if (x is SendPort) return visitSendPort(x); |
| 1068 if (x is SendPortSync) return visitSendPortSync(x); |
| 1069 |
| 1070 // Overridable fallback. |
| 1071 return visitObject(x); |
| 1072 } |
| 1073 |
| 1074 visitPrimitive(x); |
| 1075 visitList(List x); |
| 1076 visitMap(Map x); |
| 1077 visitSendPort(SendPort x); |
| 1078 visitSendPortSync(SendPortSync x); |
| 1079 |
| 1080 visitObject(Object x) { |
| 1081 // TODO(floitsch): make this a real exception. (which one)? |
| 1082 throw "Message serialization: Illegal value $x passed"; |
| 1083 } |
| 1084 |
| 1085 static bool isPrimitive(x) { |
| 1086 return (x == null) || (x is String) || (x is num) || (x is bool); |
| 1087 } |
| 1088 } |
| 1089 |
| 1090 |
| 1091 /** A visitor that recursively copies a message. */ |
| 1092 class _Copier extends _MessageTraverser { |
| 1093 |
| 1094 visitPrimitive(x) => x; |
| 1095 |
| 1096 List visitList(List list) { |
| 1097 List copy = _visited[list]; |
| 1098 if (copy != null) return copy; |
| 1099 |
| 1100 int len = list.length; |
| 1101 |
| 1102 // TODO(floitsch): we loose the generic type of the List. |
| 1103 copy = new List(len); |
| 1104 _visited[list] = copy; |
| 1105 for (int i = 0; i < len; i++) { |
| 1106 copy[i] = _dispatch(list[i]); |
| 1107 } |
| 1108 return copy; |
| 1109 } |
| 1110 |
| 1111 Map visitMap(Map map) { |
| 1112 Map copy = _visited[map]; |
| 1113 if (copy != null) return copy; |
| 1114 |
| 1115 // TODO(floitsch): we loose the generic type of the map. |
| 1116 copy = new Map(); |
| 1117 _visited[map] = copy; |
| 1118 map.forEach((key, val) { |
| 1119 copy[_dispatch(key)] = _dispatch(val); |
| 1120 }); |
| 1121 return copy; |
| 1122 } |
| 1123 |
| 1124 } |
| 1125 |
| 1126 /** Visitor that serializes a message as a JSON array. */ |
| 1127 class _Serializer extends _MessageTraverser { |
| 1128 int _nextFreeRefId = 0; |
| 1129 |
| 1130 visitPrimitive(x) => x; |
| 1131 |
| 1132 visitList(List list) { |
| 1133 int copyId = _visited[list]; |
| 1134 if (copyId != null) return ['ref', copyId]; |
| 1135 |
| 1136 int id = _nextFreeRefId++; |
| 1137 _visited[list] = id; |
| 1138 var jsArray = _serializeList(list); |
| 1139 // TODO(floitsch): we are losing the generic type. |
| 1140 return ['list', id, jsArray]; |
| 1141 } |
| 1142 |
| 1143 visitMap(Map map) { |
| 1144 int copyId = _visited[map]; |
| 1145 if (copyId != null) return ['ref', copyId]; |
| 1146 |
| 1147 int id = _nextFreeRefId++; |
| 1148 _visited[map] = id; |
| 1149 var keys = _serializeList(map.keys); |
| 1150 var values = _serializeList(map.values); |
| 1151 // TODO(floitsch): we are losing the generic type. |
| 1152 return ['map', id, keys, values]; |
| 1153 } |
| 1154 |
| 1155 _serializeList(List list) { |
| 1156 int len = list.length; |
| 1157 var result = new List(len); |
| 1158 for (int i = 0; i < len; i++) { |
| 1159 result[i] = _dispatch(list[i]); |
| 1160 } |
| 1161 return result; |
| 1162 } |
| 1163 } |
| 1164 |
| 1165 /** Deserializes arrays created with [_Serializer]. */ |
| 1166 class _Deserializer { |
| 1167 Map<int, dynamic> _deserialized; |
| 1168 |
| 1169 _Deserializer(); |
| 1170 |
| 1171 static bool isPrimitive(x) { |
| 1172 return (x == null) || (x is String) || (x is num) || (x is bool); |
| 1173 } |
| 1174 |
| 1175 deserialize(x) { |
| 1176 if (isPrimitive(x)) return x; |
| 1177 // TODO(floitsch): this should be new HashMap<int, var|Dynamic>() |
| 1178 _deserialized = new HashMap(); |
| 1179 return _deserializeHelper(x); |
| 1180 } |
| 1181 |
| 1182 _deserializeHelper(x) { |
| 1183 if (isPrimitive(x)) return x; |
| 1184 assert(x is List); |
| 1185 switch (x[0]) { |
| 1186 case 'ref': return _deserializeRef(x); |
| 1187 case 'list': return _deserializeList(x); |
| 1188 case 'map': return _deserializeMap(x); |
| 1189 case 'sendport': return deserializeSendPort(x); |
| 1190 default: return deserializeObject(x); |
| 1191 } |
| 1192 } |
| 1193 |
| 1194 _deserializeRef(List x) { |
| 1195 int id = x[1]; |
| 1196 var result = _deserialized[id]; |
| 1197 assert(result != null); |
| 1198 return result; |
| 1199 } |
| 1200 |
| 1201 List _deserializeList(List x) { |
| 1202 int id = x[1]; |
| 1203 // We rely on the fact that Dart-lists are directly mapped to Js-arrays. |
| 1204 List dartList = x[2]; |
| 1205 _deserialized[id] = dartList; |
| 1206 int len = dartList.length; |
| 1207 for (int i = 0; i < len; i++) { |
| 1208 dartList[i] = _deserializeHelper(dartList[i]); |
| 1209 } |
| 1210 return dartList; |
| 1211 } |
| 1212 |
| 1213 Map _deserializeMap(List x) { |
| 1214 Map result = new Map(); |
| 1215 int id = x[1]; |
| 1216 _deserialized[id] = result; |
| 1217 List keys = x[2]; |
| 1218 List values = x[3]; |
| 1219 int len = keys.length; |
| 1220 assert(len == values.length); |
| 1221 for (int i = 0; i < len; i++) { |
| 1222 var key = _deserializeHelper(keys[i]); |
| 1223 var value = _deserializeHelper(values[i]); |
| 1224 result[key] = value; |
| 1225 } |
| 1226 return result; |
| 1227 } |
| 1228 |
| 1229 deserializeSendPort(List x); |
| 1230 |
| 1231 deserializeObject(List x) { |
| 1232 // TODO(floitsch): Use real exception (which one?). |
| 1233 throw "Unexpected serialized object"; |
| 1234 } |
| 1235 } |
| 1236 |
| 1237 /******************************************************** |
| 1238 Inserted from lib/isolate/dart2js/timer_provider.dart |
| 1239 ********************************************************/ |
| 1240 |
| 1241 // We don't want to import the DOM library just because of window.setTimeout, |
| 1242 // so we reconstruct the Window class here. The only conflict that could happen |
| 1243 // with the other DOMWindow class would be because of subclasses. |
| 1244 // Currently, none of the two Dart classes have subclasses. |
| 1245 typedef void _TimeoutHandler(); |
| 1246 |
| 1247 class _Window native "@*DOMWindow" { |
| 1248 int setTimeout(_TimeoutHandler handler, int timeout) native; |
| 1249 int setInterval(_TimeoutHandler handler, int timeout) native; |
| 1250 void clearTimeout(int handle) native; |
| 1251 void clearInterval(int handle) native; |
| 1252 } |
| 1253 |
| 1254 _Window get _window => |
| 1255 JS('bool', 'typeof window != "undefined"') ? JS('_Window', 'window') : null; |
| 1256 |
| 1257 class _Timer implements Timer { |
| 1258 final bool _once; |
| 1259 int _handle; |
| 1260 |
| 1261 _Timer(int milliSeconds, void callback(Timer timer)) |
| 1262 : _once = true { |
| 1263 _handle = _window.setTimeout(() => callback(this), milliSeconds); |
| 1264 } |
| 1265 |
| 1266 _Timer.repeating(int milliSeconds, void callback(Timer timer)) |
| 1267 : _once = false { |
| 1268 _handle = _window.setInterval(() => callback(this), milliSeconds); |
| 1269 } |
| 1270 |
| 1271 void cancel() { |
| 1272 if (_once) { |
| 1273 _window.clearTimeout(_handle); |
| 1274 } else { |
| 1275 _window.clearInterval(_handle); |
| 1276 } |
27 } | 1277 } |
28 } | 1278 } |
29 | 1279 |
30 patch class Timer { | 1280 patch class Timer { |
31 patch factory Timer(int milliseconds, void callback(Timer timer)) { | 1281 patch factory Timer(int milliSeconds, void callback(Timer timer)) { |
32 if (!hasWindow()) { | 1282 if (_window == null) { |
33 throw new UnsupportedError("Timer interface not supported."); | 1283 throw new UnsupportedError("Timer interface not supported."); |
34 } | 1284 } |
35 return new TimerImpl(milliseconds, callback); | 1285 return new _Timer(milliSeconds, callback); |
36 } | 1286 } |
37 | 1287 |
38 /** | 1288 /** |
39 * Creates a new repeating timer. The [callback] is invoked every | 1289 * Creates a new repeating timer. The [callback] is invoked every |
40 * [milliseconds] millisecond until cancelled. | 1290 * [milliSeconds] millisecond until cancelled. |
41 */ | 1291 */ |
42 patch factory Timer.repeating(int milliseconds, void callback(Timer timer)) { | 1292 patch factory Timer.repeating(int milliSeconds, void callback(Timer timer)) { |
43 if (!hasWindow()) { | 1293 if (_window == null) { |
44 throw new UnsupportedError("Timer interface not supported."); | 1294 throw new UnsupportedError("Timer interface not supported."); |
45 } | 1295 } |
46 return new TimerImpl.repeating(milliseconds, callback); | 1296 return new _Timer.repeating(milliSeconds, callback); |
47 } | 1297 } |
48 } | 1298 } |
OLD | NEW |