##// END OF EJS Templates
update callback structure in js commands
MinRK -
Show More
@@ -1,587 +1,573
1 1 //----------------------------------------------------------------------------
2 2 // Copyright (C) 2008-2011 The IPython Development Team
3 3 //
4 4 // Distributed under the terms of the BSD License. The full license is in
5 5 // the file COPYING, distributed as part of this software.
6 6 //----------------------------------------------------------------------------
7 7
8 8 //============================================================================
9 9 // Kernel
10 10 //============================================================================
11 11
12 12 /**
13 13 * @module IPython
14 14 * @namespace IPython
15 15 * @submodule Kernel
16 16 */
17 17
18 18 var IPython = (function (IPython) {
19 19 "use strict";
20 20
21 21 var utils = IPython.utils;
22 22
23 23 // Initialization and connection.
24 24 /**
25 25 * A Kernel Class to communicate with the Python kernel
26 26 * @Class Kernel
27 27 */
28 28 var Kernel = function (base_url) {
29 29 this.kernel_id = null;
30 30 this.shell_channel = null;
31 31 this.iopub_channel = null;
32 32 this.stdin_channel = null;
33 33 this.base_url = base_url;
34 34 this.running = false;
35 35 this.username = "username";
36 36 this.session_id = utils.uuid();
37 37 this._msg_callbacks = {};
38 38
39 39 if (typeof(WebSocket) !== 'undefined') {
40 40 this.WebSocket = WebSocket;
41 41 } else if (typeof(MozWebSocket) !== 'undefined') {
42 42 this.WebSocket = MozWebSocket;
43 43 } else {
44 44 alert('Your browser does not have WebSocket support, please try Chrome, Safari or Firefox β‰₯ 6. Firefox 4 and 5 are also supported by you have to enable WebSockets in about:config.');
45 45 }
46 46
47 47 this.bind_events();
48 48 this.init_iopub_handlers();
49 49 };
50 50
51 51
52 52 Kernel.prototype._get_msg = function (msg_type, content) {
53 53 var msg = {
54 54 header : {
55 55 msg_id : utils.uuid(),
56 56 username : this.username,
57 57 session : this.session_id,
58 58 msg_type : msg_type
59 59 },
60 60 metadata : {},
61 61 content : content,
62 62 parent_header : {}
63 63 };
64 64 return msg;
65 65 };
66 66
67 67 Kernel.prototype.bind_events = function () {
68 68 var that = this;
69 69 $([IPython.events]).on('send_input_reply.Kernel', function(evt, data) {
70 70 that.send_input_reply(data);
71 71 });
72 72 };
73 73
74 74 // Initialize the iopub handlers
75 75
76 76 Kernel.prototype.init_iopub_handlers = function () {
77 77 var output_types = ['stream', 'display_data', 'pyout', 'pyerr'];
78 78 this._iopub_handlers = {};
79 79 this.register_iopub_handler('status', $.proxy(this._handle_status_message, this));
80 80 this.register_iopub_handler('clear_output', $.proxy(this._handle_clear_output, this));
81 81
82 82 for (var i=0; i < output_types.length; i++) {
83 83 this.register_iopub_handler(output_types[i], $.proxy(this._handle_output_message, this));
84 84 }
85 85 };
86 86
87 87 /**
88 88 * Start the Python kernel
89 89 * @method start
90 90 */
91 91 Kernel.prototype.start = function (params) {
92 92 params = params || {};
93 93 if (!this.running) {
94 94 var qs = $.param(params);
95 95 var url = this.base_url + '?' + qs;
96 96 $.post(url,
97 97 $.proxy(this._kernel_started, this),
98 98 'json'
99 99 );
100 100 }
101 101 };
102 102
103 103 /**
104 104 * Restart the python kernel.
105 105 *
106 106 * Emit a 'status_restarting.Kernel' event with
107 107 * the current object as parameter
108 108 *
109 109 * @method restart
110 110 */
111 111 Kernel.prototype.restart = function () {
112 112 $([IPython.events]).trigger('status_restarting.Kernel', {kernel: this});
113 113 if (this.running) {
114 114 this.stop_channels();
115 115 var url = utils.url_path_join(this.kernel_url, "restart");
116 116 $.post(url,
117 117 $.proxy(this._kernel_started, this),
118 118 'json'
119 119 );
120 120 }
121 121 };
122 122
123 123
124 124 Kernel.prototype._kernel_started = function (json) {
125 125 console.log("Kernel started: ", json.id);
126 126 this.running = true;
127 127 this.kernel_id = json.id;
128 128 var ws_url = json.ws_url;
129 129 if (ws_url.match(/wss?:\/\//) === null) {
130 130 // trailing 's' in https will become wss for secure web sockets
131 131 var prot = location.protocol.replace('http', 'ws') + "//";
132 132 ws_url = prot + location.host + ws_url;
133 133 }
134 134 this.ws_url = ws_url;
135 135 this.kernel_url = utils.url_path_join(this.base_url, this.kernel_id);
136 136 this.start_channels();
137 137 };
138 138
139 139
140 140 Kernel.prototype._websocket_closed = function(ws_url, early) {
141 141 this.stop_channels();
142 142 $([IPython.events]).trigger('websocket_closed.Kernel',
143 143 {ws_url: ws_url, kernel: this, early: early}
144 144 );
145 145 };
146 146
147 147 /**
148 148 * Start the `shell`and `iopub` channels.
149 149 * Will stop and restart them if they already exist.
150 150 *
151 151 * @method start_channels
152 152 */
153 153 Kernel.prototype.start_channels = function () {
154 154 var that = this;
155 155 this.stop_channels();
156 156 var ws_url = this.ws_url + this.kernel_url;
157 157 console.log("Starting WebSockets:", ws_url);
158 158 this.shell_channel = new this.WebSocket(ws_url + "/shell");
159 159 this.stdin_channel = new this.WebSocket(ws_url + "/stdin");
160 160 this.iopub_channel = new this.WebSocket(ws_url + "/iopub");
161 161
162 162 var already_called_onclose = false; // only alert once
163 163 var ws_closed_early = function(evt){
164 164 if (already_called_onclose){
165 165 return;
166 166 }
167 167 already_called_onclose = true;
168 168 if ( ! evt.wasClean ){
169 169 that._websocket_closed(ws_url, true);
170 170 }
171 171 };
172 172 var ws_closed_late = function(evt){
173 173 if (already_called_onclose){
174 174 return;
175 175 }
176 176 already_called_onclose = true;
177 177 if ( ! evt.wasClean ){
178 178 that._websocket_closed(ws_url, false);
179 179 }
180 180 };
181 181 var channels = [this.shell_channel, this.iopub_channel, this.stdin_channel];
182 182 for (var i=0; i < channels.length; i++) {
183 183 channels[i].onopen = $.proxy(this._ws_opened, this);
184 184 channels[i].onclose = ws_closed_early;
185 185 }
186 186 // switch from early-close to late-close message after 1s
187 187 setTimeout(function() {
188 188 for (var i=0; i < channels.length; i++) {
189 189 if (channels[i] !== null) {
190 190 channels[i].onclose = ws_closed_late;
191 191 }
192 192 }
193 193 }, 1000);
194 194 this.shell_channel.onmessage = $.proxy(this._handle_shell_reply, this);
195 195 this.iopub_channel.onmessage = $.proxy(this._handle_iopub_message, this);
196 196 this.stdin_channel.onmessage = $.proxy(this._handle_input_request, this);
197 197 };
198 198
199 199 /**
200 200 * Handle a websocket entering the open state
201 201 * sends session and cookie authentication info as first message.
202 202 * Once all sockets are open, signal the Kernel.status_started event.
203 203 * @method _ws_opened
204 204 */
205 205 Kernel.prototype._ws_opened = function (evt) {
206 206 // send the session id so the Session object Python-side
207 207 // has the same identity
208 208 evt.target.send(this.session_id + ':' + document.cookie);
209 209
210 210 var channels = [this.shell_channel, this.iopub_channel, this.stdin_channel];
211 211 for (var i=0; i < channels.length; i++) {
212 212 // if any channel is not ready, don't trigger event.
213 213 if ( !channels[i].readyState ) return;
214 214 }
215 215 // all events ready, trigger started event.
216 216 $([IPython.events]).trigger('status_started.Kernel', {kernel: this});
217 217 };
218 218
219 219 /**
220 220 * Stop the websocket channels.
221 221 * @method stop_channels
222 222 */
223 223 Kernel.prototype.stop_channels = function () {
224 224 var channels = [this.shell_channel, this.iopub_channel, this.stdin_channel];
225 225 for (var i=0; i < channels.length; i++) {
226 226 if ( channels[i] !== null ) {
227 227 channels[i].onclose = null;
228 228 channels[i].close();
229 229 }
230 230 }
231 231 this.shell_channel = this.iopub_channel = this.stdin_channel = null;
232 232 };
233 233
234 234 // Main public methods.
235 235
236 236 // send a message on the Kernel's shell channel
237 237 Kernel.prototype.send_shell_message = function (msg_type, content, callbacks) {
238 238 var msg = this._get_msg(msg_type, content);
239 239 this.shell_channel.send(JSON.stringify(msg));
240 240 this.set_callbacks_for_msg(msg.header.msg_id, callbacks);
241 241 return msg.header.msg_id;
242 242 };
243 243
244 244 /**
245 245 * Get info on an object
246 246 *
247 * @async
248 247 * @param objname {string}
249 248 * @param callback {function}
250 249 * @method object_info
251 250 *
252 * @example
253 *
254 * When calling this method pass a callback function that expects one argument.
255 *
256 * The callback will be passed the complete `object_info_reply` message documented in
257 * [IPython dev documentation](http://ipython.org/ipython-doc/dev/development/messaging.html#object-information)
251 * When calling this method, pass a callback function that expects one argument.
252 * The callback will be passed the complete `object_info_reply` message documented
253 * [here](http://ipython.org/ipython-doc/dev/development/messaging.html#object-information)
258 254 */
259 255 Kernel.prototype.object_info = function (objname, callback) {
260 256 var callbacks;
261 257 if (callback) {
262 258 callbacks = { shell : { reply : callback } };
263 259 }
264 260
265 261 if (typeof(objname) !== null && objname !== null) {
266 262 var content = {
267 263 oname : objname.toString(),
268 264 detail_level : 0,
269 265 };
270 266 return this.send_shell_message("object_info_request", content, callbacks);
271 267 }
272 268 return;
273 269 };
274 270
275 271 /**
276 272 * Execute given code into kernel, and pass result to callback.
277 273 *
278 * TODO: document input_request in callbacks
279 *
280 274 * @async
281 275 * @method execute
282 276 * @param {string} code
283 * @param [callbacks] {Object} With the optional following keys
284 * @param callbacks.'execute_reply' {function}
285 * @param callbacks.'output' {function}
286 * @param callbacks.'clear_output' {function}
287 * @param callbacks.'set_next_input' {function}
277 * @param [callbacks] {Object} With the following keys (all optional)
278 * @param callbacks.shell.reply {function}
279 * @param callbacks.shell.payload.[payload_name] {function}
280 * @param callbacks.iopub.output {function}
281 * @param callbacks.iopub.clear_output {function}
282 * @param callbacks.input {function}
288 283 * @param {object} [options]
289 284 * @param [options.silent=false] {Boolean}
290 285 * @param [options.user_expressions=empty_dict] {Dict}
291 286 * @param [options.user_variables=empty_list] {List od Strings}
292 287 * @param [options.allow_stdin=false] {Boolean} true|false
293 288 *
294 289 * @example
295 290 *
296 291 * The options object should contain the options for the execute call. Its default
297 292 * values are:
298 293 *
299 294 * options = {
300 295 * silent : true,
301 296 * user_variables : [],
302 297 * user_expressions : {},
303 298 * allow_stdin : false
304 299 * }
305 300 *
306 301 * When calling this method pass a callbacks structure of the form:
307 302 *
308 303 * callbacks = {
309 * 'execute_reply': execute_reply_callback,
310 * 'output': output_callback,
311 * 'clear_output': clear_output_callback,
312 * 'set_next_input': set_next_input_callback
304 * shell : {
305 * reply : execute_reply_callback,
306 * payload : {
307 * set_next_input : set_next_input_callback,
308 * }
309 * },
310 * iopub : {
311 * output : output_callback,
312 * clear_output : clear_output_callback,
313 * },
314 * input : raw_input_callback
313 315 * }
314 316 *
315 * The `execute_reply_callback` will be passed the content and metadata
316 * objects of the `execute_reply` message documented
317 * [here](http://ipython.org/ipython-doc/dev/development/messaging.html#execute)
318 *
319 * The `output_callback` will be passed `msg_type` ('stream','display_data','pyout','pyerr')
320 * of the output and the content and metadata objects of the PUB/SUB channel that contains the
321 * output:
322 *
323 * http://ipython.org/ipython-doc/dev/development/messaging.html#messages-on-the-pub-sub-socket
324 *
325 * The `clear_output_callback` will be passed a content object that contains
326 * stdout, stderr and other fields that are booleans, as well as the metadata object.
327 *
328 * The `set_next_input_callback` will be passed the text that should become the next
329 * input cell.
317 * Each callback will be passed the entire message as a single arugment.
318 * Payload handlers will be passed the corresponding payload and the execute_reply message.
330 319 */
331 320 Kernel.prototype.execute = function (code, callbacks, options) {
332 321
333 322 var content = {
334 323 code : code,
335 324 silent : true,
336 325 store_history : false,
337 326 user_variables : [],
338 327 user_expressions : {},
339 328 allow_stdin : false
340 329 };
341 330 callbacks = callbacks || {};
342 331 if (callbacks.input !== undefined) {
343 332 content.allow_stdin = true;
344 333 }
345 334 $.extend(true, content, options);
346 335 $([IPython.events]).trigger('execution_request.Kernel', {kernel: this, content:content});
347 336 return this.send_shell_message("execute_request", content, callbacks);
348 337 };
349 338
350 339 /**
351 * When calling this method pass a function to be called with the `complete_reply` message
340 * When calling this method, pass a function to be called with the `complete_reply` message
352 341 * as its only argument when it arrives.
353 * callbacks = {
354 * 'complete_reply': complete_reply_callback
355 * }
356 342 *
357 343 * `complete_reply` is documented
358 344 * [here](http://ipython.org/ipython-doc/dev/development/messaging.html#complete)
359 345 *
360 346 * @method complete
361 347 * @param line {integer}
362 348 * @param cursor_pos {integer}
363 349 * @param callback {function}
364 350 *
365 351 */
366 352 Kernel.prototype.complete = function (line, cursor_pos, callback) {
367 353 var callbacks;
368 354 if (callback) {
369 355 callbacks = { shell : { reply : callback } };
370 356 }
371 357 var content = {
372 358 text : '',
373 359 line : line,
374 360 block : null,
375 361 cursor_pos : cursor_pos
376 362 };
377 363 return this.send_shell_message("complete_request", content, callbacks);
378 364 };
379 365
380 366
381 367 Kernel.prototype.interrupt = function () {
382 368 if (this.running) {
383 369 $([IPython.events]).trigger('status_interrupting.Kernel', {kernel: this});
384 370 $.post(this.kernel_url + "/interrupt");
385 371 }
386 372 };
387 373
388 374
389 375 Kernel.prototype.kill = function () {
390 376 if (this.running) {
391 377 this.running = false;
392 378 var settings = {
393 379 cache : false,
394 380 type : "DELETE"
395 381 };
396 382 $.ajax(this.kernel_url, settings);
397 383 }
398 384 };
399 385
400 386 Kernel.prototype.send_input_reply = function (input) {
401 387 var content = {
402 388 value : input,
403 389 };
404 390 $([IPython.events]).trigger('input_reply.Kernel', {kernel: this, content:content});
405 391 var msg = this._get_msg("input_reply", content);
406 392 this.stdin_channel.send(JSON.stringify(msg));
407 393 return msg.header.msg_id;
408 394 };
409 395
410 396
411 397 // Reply handlers
412 398
413 399 Kernel.prototype.register_iopub_handler = function (msg_type, callback) {
414 400 this._iopub_handlers[msg_type] = callback;
415 401 };
416 402
417 403 Kernel.prototype.get_iopub_handler = function (msg_type) {
418 404 // get iopub handler for a specific message type
419 405 return this._iopub_handlers[msg_type];
420 406 };
421 407
422 408
423 409 Kernel.prototype.get_callbacks_for_msg = function (msg_id) {
424 410 // get callbacks for a specific message
425 411 return this._msg_callbacks[msg_id];
426 412 };
427 413
428 414
429 415 Kernel.prototype.clear_callbacks_for_msg = function (msg_id) {
430 416 if (this._msg_callbacks[msg_id] !== undefined ) {
431 417 delete this._msg_callbacks[msg_id];
432 418 }
433 419 };
434 420
435 421 /* Set callbacks for a particular message.
436 422 * Callbacks should be a struct of the following form:
437 423 * shell : {
438 424 *
439 425 * }
440 426
441 427 */
442 428 Kernel.prototype.set_callbacks_for_msg = function (msg_id, callbacks) {
443 429 if (callbacks) {
444 430 // shallow-copy mapping, because we will modify it at the top level
445 431 var cbcopy = this._msg_callbacks[msg_id] = {};
446 432 cbcopy.shell = callbacks.shell;
447 433 cbcopy.iopub = callbacks.iopub;
448 434 cbcopy.input = callbacks.input;
449 435 this._msg_callbacks[msg_id] = cbcopy;
450 436 }
451 437 };
452 438
453 439
454 440 Kernel.prototype._handle_shell_reply = function (e) {
455 441 var reply = $.parseJSON(e.data);
456 442 $([IPython.events]).trigger('shell_reply.Kernel', {kernel: this, reply:reply});
457 443 var content = reply.content;
458 444 var metadata = reply.metadata;
459 445 var parent_id = reply.parent_header.msg_id;
460 446 var callbacks = this.get_callbacks_for_msg(parent_id);
461 447 if (!callbacks || !callbacks.shell) {
462 448 return;
463 449 }
464 450 var shell_callbacks = callbacks.shell;
465 451
466 452 // clear callbacks on shell
467 453 delete callbacks.shell;
468 454 delete callbacks.input;
469 455 if (!callbacks.iopub) {
470 456 this.clear_callbacks_for_msg(parent_id);
471 457 }
472 458
473 459 if (shell_callbacks.reply !== undefined) {
474 460 shell_callbacks.reply(reply);
475 461 }
476 462 if (content.payload && shell_callbacks.payload) {
477 463 this._handle_payloads(content.payload, shell_callbacks.payload, reply);
478 464 }
479 465 };
480 466
481 467
482 468 Kernel.prototype._handle_payloads = function (payloads, payload_callbacks, msg) {
483 469 var l = payloads.length;
484 470 // Payloads are handled by triggering events because we don't want the Kernel
485 471 // to depend on the Notebook or Pager classes.
486 472 for (var i=0; i<l; i++) {
487 473 var payload = payloads[i];
488 474 var callback = payload_callbacks[payload.source];
489 475 if (callback) {
490 476 callback(payload, msg);
491 477 }
492 478 }
493 479 };
494 480
495 481 Kernel.prototype._handle_status_message = function (msg) {
496 482 var execution_state = msg.content.execution_state;
497 483 if (execution_state === 'busy') {
498 484 $([IPython.events]).trigger('status_busy.Kernel', {kernel: this});
499 485 } else if (execution_state === 'idle') {
500 486 // clear callbacks
501 487 var parent_id = msg.parent_header.msg_id;
502 488 var callbacks = this.get_callbacks_for_msg(parent_id);
503 489 if (callbacks !== undefined) {
504 490 delete callbacks.iopub;
505 491 delete callbacks.input;
506 492 if (!callbacks.shell) {
507 493 this.clear_callbacks_for_msg(parent_id);
508 494 }
509 495 }
510 496
511 497 $([IPython.events]).trigger('status_idle.Kernel', {kernel: this});
512 498 } else if (execution_state === 'restarting') {
513 499 // autorestarting is distinct from restarting,
514 500 // in that it means the kernel died and the server is restarting it.
515 501 // status_restarting sets the notification widget,
516 502 // autorestart shows the more prominent dialog.
517 503 $([IPython.events]).trigger('status_autorestarting.Kernel', {kernel: this});
518 504 $([IPython.events]).trigger('status_restarting.Kernel', {kernel: this});
519 505 } else if (execution_state === 'dead') {
520 506 this.stop_channels();
521 507 $([IPython.events]).trigger('status_dead.Kernel', {kernel: this});
522 508 }
523 509 };
524 510
525 511
526 512 // handle clear_output message
527 513 Kernel.prototype._handle_clear_output = function (msg) {
528 514 var callbacks = this.get_callbacks_for_msg(msg.parent_header.msg_id);
529 515 if (!callbacks || !callbacks.iopub) {
530 516 return;
531 517 }
532 518 var callback = callbacks.clear_output;
533 519 if (callback) {
534 520 callback(msg);
535 521 }
536 522 };
537 523
538 524
539 525 // handle an output message (pyout, display_data, etc.)
540 526 Kernel.prototype._handle_output_message = function (msg) {
541 527 var callbacks = this.get_callbacks_for_msg(msg.parent_header.msg_id);
542 528 if (!callbacks || !callbacks.iopub) {
543 529 return;
544 530 }
545 531 var callback = callbacks.iopub.output;
546 532 if (callback) {
547 533 callback(msg);
548 534 }
549 535 };
550 536
551 537 // dispatch IOPub messages to respective handlers.
552 538 // each message type should have a handler.
553 539 Kernel.prototype._handle_iopub_message = function (e) {
554 540 var msg = $.parseJSON(e.data);
555 541
556 542 var handler = this.get_iopub_handler(msg.header.msg_type);
557 543 if (handler !== undefined) {
558 544 handler(msg);
559 545 }
560 546 };
561 547
562 548
563 549 Kernel.prototype._handle_input_request = function (e) {
564 550 var request = $.parseJSON(e.data);
565 551 var header = request.header;
566 552 var content = request.content;
567 553 var metadata = request.metadata;
568 554 var msg_type = header.msg_type;
569 555 if (msg_type !== 'input_request') {
570 556 console.log("Invalid input request!", request);
571 557 return;
572 558 }
573 559 var callbacks = this.get_callbacks_for_msg(request.parent_header.msg_id);
574 560 if (callbacks) {
575 561 if (callbacks.input) {
576 562 callbacks.input(request);
577 563 }
578 564 }
579 565 };
580 566
581 567
582 568 IPython.Kernel = Kernel;
583 569
584 570 return IPython;
585 571
586 572 }(IPython));
587 573
General Comments 0
You need to be logged in to leave comments. Login now