##// END OF EJS Templates
validate output types in append_output...
MinRK -
Show More
@@ -1,792 +1,819 b''
1 //----------------------------------------------------------------------------
1 //----------------------------------------------------------------------------
2 // Copyright (C) 2008 The IPython Development Team
2 // Copyright (C) 2008 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 // OutputArea
9 // OutputArea
10 //============================================================================
10 //============================================================================
11
11
12 /**
12 /**
13 * @module IPython
13 * @module IPython
14 * @namespace IPython
14 * @namespace IPython
15 * @submodule OutputArea
15 * @submodule OutputArea
16 */
16 */
17 var IPython = (function (IPython) {
17 var IPython = (function (IPython) {
18 "use strict";
18 "use strict";
19
19
20 var utils = IPython.utils;
20 var utils = IPython.utils;
21
21
22 /**
22 /**
23 * @class OutputArea
23 * @class OutputArea
24 *
24 *
25 * @constructor
25 * @constructor
26 */
26 */
27
27
28 var OutputArea = function (selector, prompt_area) {
28 var OutputArea = function (selector, prompt_area) {
29 this.selector = selector;
29 this.selector = selector;
30 this.wrapper = $(selector);
30 this.wrapper = $(selector);
31 this.outputs = [];
31 this.outputs = [];
32 this.collapsed = false;
32 this.collapsed = false;
33 this.scrolled = false;
33 this.scrolled = false;
34 this.clear_queued = null;
34 this.clear_queued = null;
35 if (prompt_area === undefined) {
35 if (prompt_area === undefined) {
36 this.prompt_area = true;
36 this.prompt_area = true;
37 } else {
37 } else {
38 this.prompt_area = prompt_area;
38 this.prompt_area = prompt_area;
39 }
39 }
40 this.create_elements();
40 this.create_elements();
41 this.style();
41 this.style();
42 this.bind_events();
42 this.bind_events();
43 };
43 };
44
44
45 OutputArea.prototype.create_elements = function () {
45 OutputArea.prototype.create_elements = function () {
46 this.element = $("<div/>");
46 this.element = $("<div/>");
47 this.collapse_button = $("<div/>");
47 this.collapse_button = $("<div/>");
48 this.prompt_overlay = $("<div/>");
48 this.prompt_overlay = $("<div/>");
49 this.wrapper.append(this.prompt_overlay);
49 this.wrapper.append(this.prompt_overlay);
50 this.wrapper.append(this.element);
50 this.wrapper.append(this.element);
51 this.wrapper.append(this.collapse_button);
51 this.wrapper.append(this.collapse_button);
52 };
52 };
53
53
54
54
55 OutputArea.prototype.style = function () {
55 OutputArea.prototype.style = function () {
56 this.collapse_button.hide();
56 this.collapse_button.hide();
57 this.prompt_overlay.hide();
57 this.prompt_overlay.hide();
58
58
59 this.wrapper.addClass('output_wrapper');
59 this.wrapper.addClass('output_wrapper');
60 this.element.addClass('output');
60 this.element.addClass('output');
61
61
62 this.collapse_button.addClass("btn output_collapsed");
62 this.collapse_button.addClass("btn output_collapsed");
63 this.collapse_button.attr('title', 'click to expand output');
63 this.collapse_button.attr('title', 'click to expand output');
64 this.collapse_button.html('. . .');
64 this.collapse_button.html('. . .');
65
65
66 this.prompt_overlay.addClass('out_prompt_overlay prompt');
66 this.prompt_overlay.addClass('out_prompt_overlay prompt');
67 this.prompt_overlay.attr('title', 'click to expand output; double click to hide output');
67 this.prompt_overlay.attr('title', 'click to expand output; double click to hide output');
68
68
69 this.collapse();
69 this.collapse();
70 };
70 };
71
71
72 /**
72 /**
73 * Should the OutputArea scroll?
73 * Should the OutputArea scroll?
74 * Returns whether the height (in lines) exceeds a threshold.
74 * Returns whether the height (in lines) exceeds a threshold.
75 *
75 *
76 * @private
76 * @private
77 * @method _should_scroll
77 * @method _should_scroll
78 * @param [lines=100]{Integer}
78 * @param [lines=100]{Integer}
79 * @return {Bool}
79 * @return {Bool}
80 *
80 *
81 */
81 */
82 OutputArea.prototype._should_scroll = function (lines) {
82 OutputArea.prototype._should_scroll = function (lines) {
83 if (lines <=0 ){ return }
83 if (lines <=0 ){ return }
84 if (!lines) {
84 if (!lines) {
85 lines = 100;
85 lines = 100;
86 }
86 }
87 // line-height from http://stackoverflow.com/questions/1185151
87 // line-height from http://stackoverflow.com/questions/1185151
88 var fontSize = this.element.css('font-size');
88 var fontSize = this.element.css('font-size');
89 var lineHeight = Math.floor(parseInt(fontSize.replace('px','')) * 1.5);
89 var lineHeight = Math.floor(parseInt(fontSize.replace('px','')) * 1.5);
90
90
91 return (this.element.height() > lines * lineHeight);
91 return (this.element.height() > lines * lineHeight);
92 };
92 };
93
93
94
94
95 OutputArea.prototype.bind_events = function () {
95 OutputArea.prototype.bind_events = function () {
96 var that = this;
96 var that = this;
97 this.prompt_overlay.dblclick(function () { that.toggle_output(); });
97 this.prompt_overlay.dblclick(function () { that.toggle_output(); });
98 this.prompt_overlay.click(function () { that.toggle_scroll(); });
98 this.prompt_overlay.click(function () { that.toggle_scroll(); });
99
99
100 this.element.resize(function () {
100 this.element.resize(function () {
101 // FIXME: Firefox on Linux misbehaves, so automatic scrolling is disabled
101 // FIXME: Firefox on Linux misbehaves, so automatic scrolling is disabled
102 if ( IPython.utils.browser[0] === "Firefox" ) {
102 if ( IPython.utils.browser[0] === "Firefox" ) {
103 return;
103 return;
104 }
104 }
105 // maybe scroll output,
105 // maybe scroll output,
106 // if it's grown large enough and hasn't already been scrolled.
106 // if it's grown large enough and hasn't already been scrolled.
107 if ( !that.scrolled && that._should_scroll(OutputArea.auto_scroll_threshold)) {
107 if ( !that.scrolled && that._should_scroll(OutputArea.auto_scroll_threshold)) {
108 that.scroll_area();
108 that.scroll_area();
109 }
109 }
110 });
110 });
111 this.collapse_button.click(function () {
111 this.collapse_button.click(function () {
112 that.expand();
112 that.expand();
113 });
113 });
114 };
114 };
115
115
116
116
117 OutputArea.prototype.collapse = function () {
117 OutputArea.prototype.collapse = function () {
118 if (!this.collapsed) {
118 if (!this.collapsed) {
119 this.element.hide();
119 this.element.hide();
120 this.prompt_overlay.hide();
120 this.prompt_overlay.hide();
121 if (this.element.html()){
121 if (this.element.html()){
122 this.collapse_button.show();
122 this.collapse_button.show();
123 }
123 }
124 this.collapsed = true;
124 this.collapsed = true;
125 }
125 }
126 };
126 };
127
127
128
128
129 OutputArea.prototype.expand = function () {
129 OutputArea.prototype.expand = function () {
130 if (this.collapsed) {
130 if (this.collapsed) {
131 this.collapse_button.hide();
131 this.collapse_button.hide();
132 this.element.show();
132 this.element.show();
133 this.prompt_overlay.show();
133 this.prompt_overlay.show();
134 this.collapsed = false;
134 this.collapsed = false;
135 }
135 }
136 };
136 };
137
137
138
138
139 OutputArea.prototype.toggle_output = function () {
139 OutputArea.prototype.toggle_output = function () {
140 if (this.collapsed) {
140 if (this.collapsed) {
141 this.expand();
141 this.expand();
142 } else {
142 } else {
143 this.collapse();
143 this.collapse();
144 }
144 }
145 };
145 };
146
146
147
147
148 OutputArea.prototype.scroll_area = function () {
148 OutputArea.prototype.scroll_area = function () {
149 this.element.addClass('output_scroll');
149 this.element.addClass('output_scroll');
150 this.prompt_overlay.attr('title', 'click to unscroll output; double click to hide');
150 this.prompt_overlay.attr('title', 'click to unscroll output; double click to hide');
151 this.scrolled = true;
151 this.scrolled = true;
152 };
152 };
153
153
154
154
155 OutputArea.prototype.unscroll_area = function () {
155 OutputArea.prototype.unscroll_area = function () {
156 this.element.removeClass('output_scroll');
156 this.element.removeClass('output_scroll');
157 this.prompt_overlay.attr('title', 'click to scroll output; double click to hide');
157 this.prompt_overlay.attr('title', 'click to scroll output; double click to hide');
158 this.scrolled = false;
158 this.scrolled = false;
159 };
159 };
160
160
161 /**
161 /**
162 * Threshold to trigger autoscroll when the OutputArea is resized,
162 * Threshold to trigger autoscroll when the OutputArea is resized,
163 * typically when new outputs are added.
163 * typically when new outputs are added.
164 *
164 *
165 * Behavior is undefined if autoscroll is lower than minimum_scroll_threshold,
165 * Behavior is undefined if autoscroll is lower than minimum_scroll_threshold,
166 * unless it is < 0, in which case autoscroll will never be triggered
166 * unless it is < 0, in which case autoscroll will never be triggered
167 *
167 *
168 * @property auto_scroll_threshold
168 * @property auto_scroll_threshold
169 * @type Number
169 * @type Number
170 * @default 100
170 * @default 100
171 *
171 *
172 **/
172 **/
173 OutputArea.auto_scroll_threshold = 100;
173 OutputArea.auto_scroll_threshold = 100;
174
174
175
175
176 /**
176 /**
177 * Lower limit (in lines) for OutputArea to be made scrollable. OutputAreas
177 * Lower limit (in lines) for OutputArea to be made scrollable. OutputAreas
178 * shorter than this are never scrolled.
178 * shorter than this are never scrolled.
179 *
179 *
180 * @property minimum_scroll_threshold
180 * @property minimum_scroll_threshold
181 * @type Number
181 * @type Number
182 * @default 20
182 * @default 20
183 *
183 *
184 **/
184 **/
185 OutputArea.minimum_scroll_threshold = 20;
185 OutputArea.minimum_scroll_threshold = 20;
186
186
187
187
188 /**
188 /**
189 *
189 *
190 * Scroll OutputArea if height supperior than a threshold (in lines).
190 * Scroll OutputArea if height supperior than a threshold (in lines).
191 *
191 *
192 * Threshold is a maximum number of lines. If unspecified, defaults to
192 * Threshold is a maximum number of lines. If unspecified, defaults to
193 * OutputArea.minimum_scroll_threshold.
193 * OutputArea.minimum_scroll_threshold.
194 *
194 *
195 * Negative threshold will prevent the OutputArea from ever scrolling.
195 * Negative threshold will prevent the OutputArea from ever scrolling.
196 *
196 *
197 * @method scroll_if_long
197 * @method scroll_if_long
198 *
198 *
199 * @param [lines=20]{Number} Default to 20 if not set,
199 * @param [lines=20]{Number} Default to 20 if not set,
200 * behavior undefined for value of `0`.
200 * behavior undefined for value of `0`.
201 *
201 *
202 **/
202 **/
203 OutputArea.prototype.scroll_if_long = function (lines) {
203 OutputArea.prototype.scroll_if_long = function (lines) {
204 var n = lines | OutputArea.minimum_scroll_threshold;
204 var n = lines | OutputArea.minimum_scroll_threshold;
205 if(n <= 0){
205 if(n <= 0){
206 return
206 return
207 }
207 }
208
208
209 if (this._should_scroll(n)) {
209 if (this._should_scroll(n)) {
210 // only allow scrolling long-enough output
210 // only allow scrolling long-enough output
211 this.scroll_area();
211 this.scroll_area();
212 }
212 }
213 };
213 };
214
214
215
215
216 OutputArea.prototype.toggle_scroll = function () {
216 OutputArea.prototype.toggle_scroll = function () {
217 if (this.scrolled) {
217 if (this.scrolled) {
218 this.unscroll_area();
218 this.unscroll_area();
219 } else {
219 } else {
220 // only allow scrolling long-enough output
220 // only allow scrolling long-enough output
221 this.scroll_if_long();
221 this.scroll_if_long();
222 }
222 }
223 };
223 };
224
224
225
225
226 // typeset with MathJax if MathJax is available
226 // typeset with MathJax if MathJax is available
227 OutputArea.prototype.typeset = function () {
227 OutputArea.prototype.typeset = function () {
228 if (window.MathJax){
228 if (window.MathJax){
229 MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
229 MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
230 }
230 }
231 };
231 };
232
232
233
233
234 OutputArea.prototype.handle_output = function (msg) {
234 OutputArea.prototype.handle_output = function (msg) {
235 var json = {};
235 var json = {};
236 var msg_type = json.output_type = msg.header.msg_type;
236 var msg_type = json.output_type = msg.header.msg_type;
237 var content = msg.content;
237 var content = msg.content;
238 if (msg_type === "stream") {
238 if (msg_type === "stream") {
239 json.text = content.data;
239 json.text = content.data;
240 json.stream = content.name;
240 json.stream = content.name;
241 } else if (msg_type === "display_data") {
241 } else if (msg_type === "display_data") {
242 json = content.data;
242 json = content.data;
243 json.output_type = msg_type;
243 json.output_type = msg_type;
244 json.metadata = content.metadata;
244 json.metadata = content.metadata;
245 } else if (msg_type === "pyout") {
245 } else if (msg_type === "pyout") {
246 json = content.data;
246 json = content.data;
247 json.output_type = msg_type;
247 json.output_type = msg_type;
248 json.metadata = content.metadata;
248 json.metadata = content.metadata;
249 json.prompt_number = content.execution_count;
249 json.prompt_number = content.execution_count;
250 } else if (msg_type === "pyerr") {
250 } else if (msg_type === "pyerr") {
251 json.ename = content.ename;
251 json.ename = content.ename;
252 json.evalue = content.evalue;
252 json.evalue = content.evalue;
253 json.traceback = content.traceback;
253 json.traceback = content.traceback;
254 }
254 }
255 this.append_output(json);
255 this.append_output(json);
256 };
256 };
257
257
258 OutputArea.mime_map = {
258 OutputArea.mime_map = {
259 "text/plain" : "text",
259 "text/plain" : "text",
260 "text/html" : "html",
260 "text/html" : "html",
261 "image/svg+xml" : "svg",
261 "image/svg+xml" : "svg",
262 "image/png" : "png",
262 "image/png" : "png",
263 "image/jpeg" : "jpeg",
263 "image/jpeg" : "jpeg",
264 "text/latex" : "latex",
264 "text/latex" : "latex",
265 "application/json" : "json",
265 "application/json" : "json",
266 "application/javascript" : "javascript",
266 "application/javascript" : "javascript",
267 };
267 };
268
268
269 OutputArea.mime_map_r = {
269 OutputArea.mime_map_r = {
270 "text" : "text/plain",
270 "text" : "text/plain",
271 "html" : "text/html",
271 "html" : "text/html",
272 "svg" : "image/svg+xml",
272 "svg" : "image/svg+xml",
273 "png" : "image/png",
273 "png" : "image/png",
274 "jpeg" : "image/jpeg",
274 "jpeg" : "image/jpeg",
275 "latex" : "text/latex",
275 "latex" : "text/latex",
276 "json" : "application/json",
276 "json" : "application/json",
277 "javascript" : "application/javascript",
277 "javascript" : "application/javascript",
278 };
278 };
279
279
280 OutputArea.prototype.rename_keys = function (data, key_map) {
280 OutputArea.prototype.rename_keys = function (data, key_map) {
281 var remapped = {};
281 var remapped = {};
282 for (var key in data) {
282 for (var key in data) {
283 var new_key = key_map[key] || key;
283 var new_key = key_map[key] || key;
284 remapped[new_key] = data[key];
284 remapped[new_key] = data[key];
285 }
285 }
286 return remapped;
286 return remapped;
287 };
287 };
288
288
289
290 OutputArea.output_types = [
291 'application/javascript',
292 'text/html',
293 'text/latex',
294 'image/svg+xml',
295 'image/png',
296 'image/jpeg',
297 'text/plain'
298 ];
299
300 OutputArea.prototype.validate_output = function (json) {
301 // scrub invalid outputs
302 // TODO: right now everything is a string, but JSON really shouldn't be.
303 // nbformat 4 will fix that.
304 $.map(OutputArea.output_types, function(key){
305 if (json[key] !== undefined && typeof json[key] !== 'string') {
306 console.log("Invalid type for " + key, json[key]);
307 delete json[key];
308 }
309 });
310 return json;
311 };
312
289 OutputArea.prototype.append_output = function (json) {
313 OutputArea.prototype.append_output = function (json) {
290 this.expand();
314 this.expand();
291 // Clear the output if clear is queued.
315 // Clear the output if clear is queued.
292 var needs_height_reset = false;
316 var needs_height_reset = false;
293 if (this.clear_queued) {
317 if (this.clear_queued) {
294 this.clear_output(false);
318 this.clear_output(false);
295 needs_height_reset = true;
319 needs_height_reset = true;
296 }
320 }
321
322 // validate output data types
323 json = this.validate_output(json);
297
324
298 if (json.output_type === 'pyout') {
325 if (json.output_type === 'pyout') {
299 this.append_pyout(json);
326 this.append_pyout(json);
300 } else if (json.output_type === 'pyerr') {
327 } else if (json.output_type === 'pyerr') {
301 this.append_pyerr(json);
328 this.append_pyerr(json);
302 } else if (json.output_type === 'display_data') {
329 } else if (json.output_type === 'display_data') {
303 this.append_display_data(json);
330 this.append_display_data(json);
304 } else if (json.output_type === 'stream') {
331 } else if (json.output_type === 'stream') {
305 this.append_stream(json);
332 this.append_stream(json);
306 }
333 }
307 this.outputs.push(json);
334 this.outputs.push(json);
308
335
309 // Only reset the height to automatic if the height is currently
336 // Only reset the height to automatic if the height is currently
310 // fixed (done by wait=True flag on clear_output).
337 // fixed (done by wait=True flag on clear_output).
311 if (needs_height_reset) {
338 if (needs_height_reset) {
312 this.element.height('');
339 this.element.height('');
313 }
340 }
314
341
315 var that = this;
342 var that = this;
316 setTimeout(function(){that.element.trigger('resize');}, 100);
343 setTimeout(function(){that.element.trigger('resize');}, 100);
317 };
344 };
318
345
319
346
320 OutputArea.prototype.create_output_area = function () {
347 OutputArea.prototype.create_output_area = function () {
321 var oa = $("<div/>").addClass("output_area");
348 var oa = $("<div/>").addClass("output_area");
322 if (this.prompt_area) {
349 if (this.prompt_area) {
323 oa.append($('<div/>').addClass('prompt'));
350 oa.append($('<div/>').addClass('prompt'));
324 }
351 }
325 return oa;
352 return oa;
326 };
353 };
327
354
328
355
329 function _get_metadata_key(metadata, key, mime) {
356 function _get_metadata_key(metadata, key, mime) {
330 var mime_md = metadata[mime];
357 var mime_md = metadata[mime];
331 // mime-specific higher priority
358 // mime-specific higher priority
332 if (mime_md && mime_md[key] !== undefined) {
359 if (mime_md && mime_md[key] !== undefined) {
333 return mime_md[key];
360 return mime_md[key];
334 }
361 }
335 // fallback on global
362 // fallback on global
336 return metadata[key];
363 return metadata[key];
337 }
364 }
338
365
339 OutputArea.prototype.create_output_subarea = function(md, classes, mime) {
366 OutputArea.prototype.create_output_subarea = function(md, classes, mime) {
340 var subarea = $('<div/>').addClass('output_subarea').addClass(classes);
367 var subarea = $('<div/>').addClass('output_subarea').addClass(classes);
341 if (_get_metadata_key(md, 'isolated', mime)) {
368 if (_get_metadata_key(md, 'isolated', mime)) {
342 // Create an iframe to isolate the subarea from the rest of the
369 // Create an iframe to isolate the subarea from the rest of the
343 // document
370 // document
344 var iframe = $('<iframe/>').addClass('box-flex1');
371 var iframe = $('<iframe/>').addClass('box-flex1');
345 iframe.css({'height':1, 'width':'100%', 'display':'block'});
372 iframe.css({'height':1, 'width':'100%', 'display':'block'});
346 iframe.attr('frameborder', 0);
373 iframe.attr('frameborder', 0);
347 iframe.attr('scrolling', 'auto');
374 iframe.attr('scrolling', 'auto');
348
375
349 // Once the iframe is loaded, the subarea is dynamically inserted
376 // Once the iframe is loaded, the subarea is dynamically inserted
350 iframe.on('load', function() {
377 iframe.on('load', function() {
351 // Workaround needed by Firefox, to properly render svg inside
378 // Workaround needed by Firefox, to properly render svg inside
352 // iframes, see http://stackoverflow.com/questions/10177190/
379 // iframes, see http://stackoverflow.com/questions/10177190/
353 // svg-dynamically-added-to-iframe-does-not-render-correctly
380 // svg-dynamically-added-to-iframe-does-not-render-correctly
354 this.contentDocument.open();
381 this.contentDocument.open();
355
382
356 // Insert the subarea into the iframe
383 // Insert the subarea into the iframe
357 // We must directly write the html. When using Jquery's append
384 // We must directly write the html. When using Jquery's append
358 // method, javascript is evaluated in the parent document and
385 // method, javascript is evaluated in the parent document and
359 // not in the iframe document.
386 // not in the iframe document.
360 this.contentDocument.write(subarea.html());
387 this.contentDocument.write(subarea.html());
361
388
362 this.contentDocument.close();
389 this.contentDocument.close();
363
390
364 var body = this.contentDocument.body;
391 var body = this.contentDocument.body;
365 // Adjust the iframe height automatically
392 // Adjust the iframe height automatically
366 iframe.height(body.scrollHeight + 'px');
393 iframe.height(body.scrollHeight + 'px');
367 });
394 });
368
395
369 // Elements should be appended to the inner subarea and not to the
396 // Elements should be appended to the inner subarea and not to the
370 // iframe
397 // iframe
371 iframe.append = function(that) {
398 iframe.append = function(that) {
372 subarea.append(that);
399 subarea.append(that);
373 };
400 };
374
401
375 return iframe;
402 return iframe;
376 } else {
403 } else {
377 return subarea;
404 return subarea;
378 }
405 }
379 }
406 }
380
407
381
408
382 OutputArea.prototype._append_javascript_error = function (err, element) {
409 OutputArea.prototype._append_javascript_error = function (err, element) {
383 // display a message when a javascript error occurs in display output
410 // display a message when a javascript error occurs in display output
384 var msg = "Javascript error adding output!"
411 var msg = "Javascript error adding output!"
385 if ( element === undefined ) return;
412 if ( element === undefined ) return;
386 element.append(
413 element.append(
387 $('<div/>').html(msg + "<br/>" +
414 $('<div/>').html(msg + "<br/>" +
388 err.toString() +
415 err.toString() +
389 '<br/>See your browser Javascript console for more details.'
416 '<br/>See your browser Javascript console for more details.'
390 ).addClass('js-error')
417 ).addClass('js-error')
391 );
418 );
392 };
419 };
393
420
394 OutputArea.prototype._safe_append = function (toinsert) {
421 OutputArea.prototype._safe_append = function (toinsert) {
395 // safely append an item to the document
422 // safely append an item to the document
396 // this is an object created by user code,
423 // this is an object created by user code,
397 // and may have errors, which should not be raised
424 // and may have errors, which should not be raised
398 // under any circumstances.
425 // under any circumstances.
399 try {
426 try {
400 this.element.append(toinsert);
427 this.element.append(toinsert);
401 } catch(err) {
428 } catch(err) {
402 console.log(err);
429 console.log(err);
403 // Create an actual output_area and output_subarea, which creates
430 // Create an actual output_area and output_subarea, which creates
404 // the prompt area and the proper indentation.
431 // the prompt area and the proper indentation.
405 var toinsert = this.create_output_area();
432 var toinsert = this.create_output_area();
406 var subarea = $('<div/>').addClass('output_subarea');
433 var subarea = $('<div/>').addClass('output_subarea');
407 toinsert.append(subarea);
434 toinsert.append(subarea);
408 this._append_javascript_error(err, subarea);
435 this._append_javascript_error(err, subarea);
409 this.element.append(toinsert);
436 this.element.append(toinsert);
410 }
437 }
411 };
438 };
412
439
413
440
414 OutputArea.prototype.append_pyout = function (json) {
441 OutputArea.prototype.append_pyout = function (json) {
415 var n = json.prompt_number || ' ';
442 var n = json.prompt_number || ' ';
416 var toinsert = this.create_output_area();
443 var toinsert = this.create_output_area();
417 if (this.prompt_area) {
444 if (this.prompt_area) {
418 toinsert.find('div.prompt').addClass('output_prompt').html('Out[' + n + ']:');
445 toinsert.find('div.prompt').addClass('output_prompt').html('Out[' + n + ']:');
419 }
446 }
420 this.append_mime_type(json, toinsert);
447 this.append_mime_type(json, toinsert);
421 this._safe_append(toinsert);
448 this._safe_append(toinsert);
422 // If we just output latex, typeset it.
449 // If we just output latex, typeset it.
423 if ((json['text/latex'] !== undefined) || (json['text/html'] !== undefined)) {
450 if ((json['text/latex'] !== undefined) || (json['text/html'] !== undefined)) {
424 this.typeset();
451 this.typeset();
425 }
452 }
426 };
453 };
427
454
428
455
429 OutputArea.prototype.append_pyerr = function (json) {
456 OutputArea.prototype.append_pyerr = function (json) {
430 var tb = json.traceback;
457 var tb = json.traceback;
431 if (tb !== undefined && tb.length > 0) {
458 if (tb !== undefined && tb.length > 0) {
432 var s = '';
459 var s = '';
433 var len = tb.length;
460 var len = tb.length;
434 for (var i=0; i<len; i++) {
461 for (var i=0; i<len; i++) {
435 s = s + tb[i] + '\n';
462 s = s + tb[i] + '\n';
436 }
463 }
437 s = s + '\n';
464 s = s + '\n';
438 var toinsert = this.create_output_area();
465 var toinsert = this.create_output_area();
439 this.append_text(s, {}, toinsert);
466 this.append_text(s, {}, toinsert);
440 this._safe_append(toinsert);
467 this._safe_append(toinsert);
441 }
468 }
442 };
469 };
443
470
444
471
445 OutputArea.prototype.append_stream = function (json) {
472 OutputArea.prototype.append_stream = function (json) {
446 // temporary fix: if stream undefined (json file written prior to this patch),
473 // temporary fix: if stream undefined (json file written prior to this patch),
447 // default to most likely stdout:
474 // default to most likely stdout:
448 if (json.stream == undefined){
475 if (json.stream == undefined){
449 json.stream = 'stdout';
476 json.stream = 'stdout';
450 }
477 }
451 var text = json.text;
478 var text = json.text;
452 var subclass = "output_"+json.stream;
479 var subclass = "output_"+json.stream;
453 if (this.outputs.length > 0){
480 if (this.outputs.length > 0){
454 // have at least one output to consider
481 // have at least one output to consider
455 var last = this.outputs[this.outputs.length-1];
482 var last = this.outputs[this.outputs.length-1];
456 if (last.output_type == 'stream' && json.stream == last.stream){
483 if (last.output_type == 'stream' && json.stream == last.stream){
457 // latest output was in the same stream,
484 // latest output was in the same stream,
458 // so append directly into its pre tag
485 // so append directly into its pre tag
459 // escape ANSI & HTML specials:
486 // escape ANSI & HTML specials:
460 var pre = this.element.find('div.'+subclass).last().find('pre');
487 var pre = this.element.find('div.'+subclass).last().find('pre');
461 var html = utils.fixCarriageReturn(
488 var html = utils.fixCarriageReturn(
462 pre.html() + utils.fixConsole(text));
489 pre.html() + utils.fixConsole(text));
463 pre.html(html);
490 pre.html(html);
464 return;
491 return;
465 }
492 }
466 }
493 }
467
494
468 if (!text.replace("\r", "")) {
495 if (!text.replace("\r", "")) {
469 // text is nothing (empty string, \r, etc.)
496 // text is nothing (empty string, \r, etc.)
470 // so don't append any elements, which might add undesirable space
497 // so don't append any elements, which might add undesirable space
471 return;
498 return;
472 }
499 }
473
500
474 // If we got here, attach a new div
501 // If we got here, attach a new div
475 var toinsert = this.create_output_area();
502 var toinsert = this.create_output_area();
476 this.append_text(text, {}, toinsert, "output_stream "+subclass);
503 this.append_text(text, {}, toinsert, "output_stream "+subclass);
477 this._safe_append(toinsert);
504 this._safe_append(toinsert);
478 };
505 };
479
506
480
507
481 OutputArea.prototype.append_display_data = function (json) {
508 OutputArea.prototype.append_display_data = function (json) {
482 var toinsert = this.create_output_area();
509 var toinsert = this.create_output_area();
483 if (this.append_mime_type(json, toinsert)) {
510 if (this.append_mime_type(json, toinsert)) {
484 this._safe_append(toinsert);
511 this._safe_append(toinsert);
485 // If we just output latex, typeset it.
512 // If we just output latex, typeset it.
486 if ((json['text/latex'] !== undefined) || (json['text/html'] !== undefined)) {
513 if ((json['text/latex'] !== undefined) || (json['text/html'] !== undefined)) {
487 this.typeset();
514 this.typeset();
488 }
515 }
489 }
516 }
490 };
517 };
491
518
492 OutputArea.display_order = [
519 OutputArea.display_order = [
493 'application/javascript',
520 'application/javascript',
494 'text/html',
521 'text/html',
495 'text/latex',
522 'text/latex',
496 'image/svg+xml',
523 'image/svg+xml',
497 'image/png',
524 'image/png',
498 'image/jpeg',
525 'image/jpeg',
499 'text/plain'
526 'text/plain'
500 ];
527 ];
501
528
502 OutputArea.prototype.append_mime_type = function (json, element) {
529 OutputArea.prototype.append_mime_type = function (json, element) {
503
530
504 for (var type_i in OutputArea.display_order) {
531 for (var type_i in OutputArea.display_order) {
505 var type = OutputArea.display_order[type_i];
532 var type = OutputArea.display_order[type_i];
506 var append = OutputArea.append_map[type];
533 var append = OutputArea.append_map[type];
507 if ((json[type] !== undefined) && append) {
534 if ((json[type] !== undefined) && append) {
508 var md = json.metadata || {};
535 var md = json.metadata || {};
509 append.apply(this, [json[type], md, element]);
536 append.apply(this, [json[type], md, element]);
510 return true;
537 return true;
511 }
538 }
512 }
539 }
513 return false;
540 return false;
514 };
541 };
515
542
516
543
517 OutputArea.prototype.append_html = function (html, md, element) {
544 OutputArea.prototype.append_html = function (html, md, element) {
518 var type = 'text/html';
545 var type = 'text/html';
519 var toinsert = this.create_output_subarea(md, "output_html rendered_html", type);
546 var toinsert = this.create_output_subarea(md, "output_html rendered_html", type);
520 IPython.keyboard_manager.register_events(toinsert);
547 IPython.keyboard_manager.register_events(toinsert);
521 toinsert.append(html);
548 toinsert.append(html);
522 element.append(toinsert);
549 element.append(toinsert);
523 };
550 };
524
551
525
552
526 OutputArea.prototype.append_javascript = function (js, md, container) {
553 OutputArea.prototype.append_javascript = function (js, md, container) {
527 // We just eval the JS code, element appears in the local scope.
554 // We just eval the JS code, element appears in the local scope.
528 var type = 'application/javascript';
555 var type = 'application/javascript';
529 var element = this.create_output_subarea(md, "output_javascript", type);
556 var element = this.create_output_subarea(md, "output_javascript", type);
530 IPython.keyboard_manager.register_events(element);
557 IPython.keyboard_manager.register_events(element);
531 container.append(element);
558 container.append(element);
532 try {
559 try {
533 eval(js);
560 eval(js);
534 } catch(err) {
561 } catch(err) {
535 console.log(err);
562 console.log(err);
536 this._append_javascript_error(err, element);
563 this._append_javascript_error(err, element);
537 }
564 }
538 };
565 };
539
566
540
567
541 OutputArea.prototype.append_text = function (data, md, element, extra_class) {
568 OutputArea.prototype.append_text = function (data, md, element, extra_class) {
542 var type = 'text/plain';
569 var type = 'text/plain';
543 var toinsert = this.create_output_subarea(md, "output_text", type);
570 var toinsert = this.create_output_subarea(md, "output_text", type);
544 // escape ANSI & HTML specials in plaintext:
571 // escape ANSI & HTML specials in plaintext:
545 data = utils.fixConsole(data);
572 data = utils.fixConsole(data);
546 data = utils.fixCarriageReturn(data);
573 data = utils.fixCarriageReturn(data);
547 data = utils.autoLinkUrls(data);
574 data = utils.autoLinkUrls(data);
548 if (extra_class){
575 if (extra_class){
549 toinsert.addClass(extra_class);
576 toinsert.addClass(extra_class);
550 }
577 }
551 toinsert.append($("<pre/>").html(data));
578 toinsert.append($("<pre/>").html(data));
552 element.append(toinsert);
579 element.append(toinsert);
553 };
580 };
554
581
555
582
556 OutputArea.prototype.append_svg = function (svg, md, element) {
583 OutputArea.prototype.append_svg = function (svg, md, element) {
557 var type = 'image/svg+xml';
584 var type = 'image/svg+xml';
558 var toinsert = this.create_output_subarea(md, "output_svg", type);
585 var toinsert = this.create_output_subarea(md, "output_svg", type);
559 toinsert.append(svg);
586 toinsert.append(svg);
560 element.append(toinsert);
587 element.append(toinsert);
561 };
588 };
562
589
563
590
564 OutputArea.prototype._dblclick_to_reset_size = function (img) {
591 OutputArea.prototype._dblclick_to_reset_size = function (img) {
565 // schedule wrapping image in resizable after a delay,
592 // schedule wrapping image in resizable after a delay,
566 // so we don't end up calling resize on a zero-size object
593 // so we don't end up calling resize on a zero-size object
567 var that = this;
594 var that = this;
568 setTimeout(function () {
595 setTimeout(function () {
569 var h0 = img.height();
596 var h0 = img.height();
570 var w0 = img.width();
597 var w0 = img.width();
571 if (!(h0 && w0)) {
598 if (!(h0 && w0)) {
572 // zero size, schedule another timeout
599 // zero size, schedule another timeout
573 that._dblclick_to_reset_size(img);
600 that._dblclick_to_reset_size(img);
574 return;
601 return;
575 }
602 }
576 img.resizable({
603 img.resizable({
577 aspectRatio: true,
604 aspectRatio: true,
578 autoHide: true
605 autoHide: true
579 });
606 });
580 img.dblclick(function () {
607 img.dblclick(function () {
581 // resize wrapper & image together for some reason:
608 // resize wrapper & image together for some reason:
582 img.parent().height(h0);
609 img.parent().height(h0);
583 img.height(h0);
610 img.height(h0);
584 img.parent().width(w0);
611 img.parent().width(w0);
585 img.width(w0);
612 img.width(w0);
586 });
613 });
587 }, 250);
614 }, 250);
588 };
615 };
589
616
590
617
591 OutputArea.prototype.append_png = function (png, md, element) {
618 OutputArea.prototype.append_png = function (png, md, element) {
592 var type = 'image/png';
619 var type = 'image/png';
593 var toinsert = this.create_output_subarea(md, "output_png", type);
620 var toinsert = this.create_output_subarea(md, "output_png", type);
594 var img = $("<img/>");
621 var img = $("<img/>");
595 img[0].setAttribute('src','data:image/png;base64,'+png);
622 img[0].setAttribute('src','data:image/png;base64,'+png);
596 if (md['height']) {
623 if (md['height']) {
597 img[0].setAttribute('height', md['height']);
624 img[0].setAttribute('height', md['height']);
598 }
625 }
599 if (md['width']) {
626 if (md['width']) {
600 img[0].setAttribute('width', md['width']);
627 img[0].setAttribute('width', md['width']);
601 }
628 }
602 this._dblclick_to_reset_size(img);
629 this._dblclick_to_reset_size(img);
603 toinsert.append(img);
630 toinsert.append(img);
604 element.append(toinsert);
631 element.append(toinsert);
605 };
632 };
606
633
607
634
608 OutputArea.prototype.append_jpeg = function (jpeg, md, element) {
635 OutputArea.prototype.append_jpeg = function (jpeg, md, element) {
609 var type = 'image/jpeg';
636 var type = 'image/jpeg';
610 var toinsert = this.create_output_subarea(md, "output_jpeg", type);
637 var toinsert = this.create_output_subarea(md, "output_jpeg", type);
611 var img = $("<img/>").attr('src','data:image/jpeg;base64,'+jpeg);
638 var img = $("<img/>").attr('src','data:image/jpeg;base64,'+jpeg);
612 if (md['height']) {
639 if (md['height']) {
613 img.attr('height', md['height']);
640 img.attr('height', md['height']);
614 }
641 }
615 if (md['width']) {
642 if (md['width']) {
616 img.attr('width', md['width']);
643 img.attr('width', md['width']);
617 }
644 }
618 this._dblclick_to_reset_size(img);
645 this._dblclick_to_reset_size(img);
619 toinsert.append(img);
646 toinsert.append(img);
620 element.append(toinsert);
647 element.append(toinsert);
621 };
648 };
622
649
623
650
624 OutputArea.prototype.append_latex = function (latex, md, element) {
651 OutputArea.prototype.append_latex = function (latex, md, element) {
625 // This method cannot do the typesetting because the latex first has to
652 // This method cannot do the typesetting because the latex first has to
626 // be on the page.
653 // be on the page.
627 var type = 'text/latex';
654 var type = 'text/latex';
628 var toinsert = this.create_output_subarea(md, "output_latex", type);
655 var toinsert = this.create_output_subarea(md, "output_latex", type);
629 toinsert.append(latex);
656 toinsert.append(latex);
630 element.append(toinsert);
657 element.append(toinsert);
631 };
658 };
632
659
633 OutputArea.append_map = {
660 OutputArea.append_map = {
634 "text/plain" : OutputArea.prototype.append_text,
661 "text/plain" : OutputArea.prototype.append_text,
635 "text/html" : OutputArea.prototype.append_html,
662 "text/html" : OutputArea.prototype.append_html,
636 "image/svg+xml" : OutputArea.prototype.append_svg,
663 "image/svg+xml" : OutputArea.prototype.append_svg,
637 "image/png" : OutputArea.prototype.append_png,
664 "image/png" : OutputArea.prototype.append_png,
638 "image/jpeg" : OutputArea.prototype.append_jpeg,
665 "image/jpeg" : OutputArea.prototype.append_jpeg,
639 "text/latex" : OutputArea.prototype.append_latex,
666 "text/latex" : OutputArea.prototype.append_latex,
640 "application/json" : OutputArea.prototype.append_json,
667 "application/json" : OutputArea.prototype.append_json,
641 "application/javascript" : OutputArea.prototype.append_javascript,
668 "application/javascript" : OutputArea.prototype.append_javascript,
642 };
669 };
643
670
644 OutputArea.prototype.append_raw_input = function (msg) {
671 OutputArea.prototype.append_raw_input = function (msg) {
645 var that = this;
672 var that = this;
646 this.expand();
673 this.expand();
647 var content = msg.content;
674 var content = msg.content;
648 var area = this.create_output_area();
675 var area = this.create_output_area();
649
676
650 // disable any other raw_inputs, if they are left around
677 // disable any other raw_inputs, if they are left around
651 $("div.output_subarea.raw_input").remove();
678 $("div.output_subarea.raw_input").remove();
652
679
653 area.append(
680 area.append(
654 $("<div/>")
681 $("<div/>")
655 .addClass("box-flex1 output_subarea raw_input")
682 .addClass("box-flex1 output_subarea raw_input")
656 .append(
683 .append(
657 $("<span/>")
684 $("<span/>")
658 .addClass("input_prompt")
685 .addClass("input_prompt")
659 .text(content.prompt)
686 .text(content.prompt)
660 )
687 )
661 .append(
688 .append(
662 $("<input/>")
689 $("<input/>")
663 .addClass("raw_input")
690 .addClass("raw_input")
664 .attr('type', 'text')
691 .attr('type', 'text')
665 .attr("size", 47)
692 .attr("size", 47)
666 .keydown(function (event, ui) {
693 .keydown(function (event, ui) {
667 // make sure we submit on enter,
694 // make sure we submit on enter,
668 // and don't re-execute the *cell* on shift-enter
695 // and don't re-execute the *cell* on shift-enter
669 if (event.which === utils.keycodes.ENTER) {
696 if (event.which === utils.keycodes.ENTER) {
670 that._submit_raw_input();
697 that._submit_raw_input();
671 return false;
698 return false;
672 }
699 }
673 })
700 })
674 )
701 )
675 );
702 );
676
703
677 this.element.append(area);
704 this.element.append(area);
678 var raw_input = area.find('input.raw_input');
705 var raw_input = area.find('input.raw_input');
679 // Register events that enable/disable the keyboard manager while raw
706 // Register events that enable/disable the keyboard manager while raw
680 // input is focused.
707 // input is focused.
681 IPython.keyboard_manager.register_events(raw_input);
708 IPython.keyboard_manager.register_events(raw_input);
682 // Note, the following line used to read raw_input.focus().focus().
709 // Note, the following line used to read raw_input.focus().focus().
683 // This seemed to be needed otherwise only the cell would be focused.
710 // This seemed to be needed otherwise only the cell would be focused.
684 // But with the modal UI, this seems to work fine with one call to focus().
711 // But with the modal UI, this seems to work fine with one call to focus().
685 raw_input.focus();
712 raw_input.focus();
686 }
713 }
687
714
688 OutputArea.prototype._submit_raw_input = function (evt) {
715 OutputArea.prototype._submit_raw_input = function (evt) {
689 var container = this.element.find("div.raw_input");
716 var container = this.element.find("div.raw_input");
690 var theprompt = container.find("span.input_prompt");
717 var theprompt = container.find("span.input_prompt");
691 var theinput = container.find("input.raw_input");
718 var theinput = container.find("input.raw_input");
692 var value = theinput.val();
719 var value = theinput.val();
693 var content = {
720 var content = {
694 output_type : 'stream',
721 output_type : 'stream',
695 name : 'stdout',
722 name : 'stdout',
696 text : theprompt.text() + value + '\n'
723 text : theprompt.text() + value + '\n'
697 }
724 }
698 // remove form container
725 // remove form container
699 container.parent().remove();
726 container.parent().remove();
700 // replace with plaintext version in stdout
727 // replace with plaintext version in stdout
701 this.append_output(content, false);
728 this.append_output(content, false);
702 $([IPython.events]).trigger('send_input_reply.Kernel', value);
729 $([IPython.events]).trigger('send_input_reply.Kernel', value);
703 }
730 }
704
731
705
732
706 OutputArea.prototype.handle_clear_output = function (msg) {
733 OutputArea.prototype.handle_clear_output = function (msg) {
707 this.clear_output(msg.content.wait);
734 this.clear_output(msg.content.wait);
708 };
735 };
709
736
710
737
711 OutputArea.prototype.clear_output = function(wait) {
738 OutputArea.prototype.clear_output = function(wait) {
712 if (wait) {
739 if (wait) {
713
740
714 // If a clear is queued, clear before adding another to the queue.
741 // If a clear is queued, clear before adding another to the queue.
715 if (this.clear_queued) {
742 if (this.clear_queued) {
716 this.clear_output(false);
743 this.clear_output(false);
717 };
744 };
718
745
719 this.clear_queued = true;
746 this.clear_queued = true;
720 } else {
747 } else {
721
748
722 // Fix the output div's height if the clear_output is waiting for
749 // Fix the output div's height if the clear_output is waiting for
723 // new output (it is being used in an animation).
750 // new output (it is being used in an animation).
724 if (this.clear_queued) {
751 if (this.clear_queued) {
725 var height = this.element.height();
752 var height = this.element.height();
726 this.element.height(height);
753 this.element.height(height);
727 this.clear_queued = false;
754 this.clear_queued = false;
728 }
755 }
729
756
730 // clear all, no need for logic
757 // clear all, no need for logic
731 this.element.html("");
758 this.element.html("");
732 this.outputs = [];
759 this.outputs = [];
733 this.unscroll_area();
760 this.unscroll_area();
734 return;
761 return;
735 };
762 };
736 };
763 };
737
764
738
765
739 // JSON serialization
766 // JSON serialization
740
767
741 OutputArea.prototype.fromJSON = function (outputs) {
768 OutputArea.prototype.fromJSON = function (outputs) {
742 var len = outputs.length;
769 var len = outputs.length;
743 var data;
770 var data;
744
771
745 // We don't want to display javascript on load, so remove it from the
772 // We don't want to display javascript on load, so remove it from the
746 // display order for the duration of this function call, but be sure to
773 // display order for the duration of this function call, but be sure to
747 // put it back in there so incoming messages that contain javascript
774 // put it back in there so incoming messages that contain javascript
748 // representations get displayed
775 // representations get displayed
749 var js_index = OutputArea.display_order.indexOf('application/javascript');
776 var js_index = OutputArea.display_order.indexOf('application/javascript');
750 OutputArea.display_order.splice(js_index, 1);
777 OutputArea.display_order.splice(js_index, 1);
751
778
752 for (var i=0; i<len; i++) {
779 for (var i=0; i<len; i++) {
753 data = outputs[i];
780 data = outputs[i];
754 var msg_type = data.output_type;
781 var msg_type = data.output_type;
755 if (msg_type === "display_data" || msg_type === "pyout") {
782 if (msg_type === "display_data" || msg_type === "pyout") {
756 // convert short keys to mime keys
783 // convert short keys to mime keys
757 // TODO: remove mapping of short keys when we update to nbformat 4
784 // TODO: remove mapping of short keys when we update to nbformat 4
758 data = this.rename_keys(data, OutputArea.mime_map_r);
785 data = this.rename_keys(data, OutputArea.mime_map_r);
759 data.metadata = this.rename_keys(data.metadata, OutputArea.mime_map_r);
786 data.metadata = this.rename_keys(data.metadata, OutputArea.mime_map_r);
760 }
787 }
761
788
762 this.append_output(data);
789 this.append_output(data);
763 }
790 }
764
791
765 // reinsert javascript into display order, see note above
792 // reinsert javascript into display order, see note above
766 OutputArea.display_order.splice(js_index, 0, 'application/javascript');
793 OutputArea.display_order.splice(js_index, 0, 'application/javascript');
767 };
794 };
768
795
769
796
770 OutputArea.prototype.toJSON = function () {
797 OutputArea.prototype.toJSON = function () {
771 var outputs = [];
798 var outputs = [];
772 var len = this.outputs.length;
799 var len = this.outputs.length;
773 var data;
800 var data;
774 for (var i=0; i<len; i++) {
801 for (var i=0; i<len; i++) {
775 data = this.outputs[i];
802 data = this.outputs[i];
776 var msg_type = data.output_type;
803 var msg_type = data.output_type;
777 if (msg_type === "display_data" || msg_type === "pyout") {
804 if (msg_type === "display_data" || msg_type === "pyout") {
778 // convert mime keys to short keys
805 // convert mime keys to short keys
779 data = this.rename_keys(data, OutputArea.mime_map);
806 data = this.rename_keys(data, OutputArea.mime_map);
780 data.metadata = this.rename_keys(data.metadata, OutputArea.mime_map);
807 data.metadata = this.rename_keys(data.metadata, OutputArea.mime_map);
781 }
808 }
782 outputs[i] = data;
809 outputs[i] = data;
783 }
810 }
784 return outputs;
811 return outputs;
785 };
812 };
786
813
787
814
788 IPython.OutputArea = OutputArea;
815 IPython.OutputArea = OutputArea;
789
816
790 return IPython;
817 return IPython;
791
818
792 }(IPython));
819 }(IPython));
General Comments 0
You need to be logged in to leave comments. Login now