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