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