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