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