##// END OF EJS Templates
All aboard the promise train
Thomas Kluyver -
Show More
@@ -1,357 +1,356 b''
1 1 // Copyright (c) IPython Development Team.
2 2 // Distributed under the terms of the Modified BSD License.
3 3
4 4 define([
5 5 'jquery',
6 6 'base/js/namespace',
7 7 'base/js/dialog',
8 8 'base/js/utils',
9 9 'notebook/js/tour',
10 10 'bootstrap',
11 11 'moment',
12 12 ], function($, IPython, dialog, utils, tour, bootstrap, moment) {
13 13 "use strict";
14 14
15 15 var MenuBar = function (selector, options) {
16 16 // Constructor
17 17 //
18 18 // A MenuBar Class to generate the menubar of IPython notebook
19 19 //
20 20 // Parameters:
21 21 // selector: string
22 22 // options: dictionary
23 23 // Dictionary of keyword arguments.
24 24 // notebook: Notebook instance
25 25 // contents: ContentManager instance
26 26 // layout_manager: LayoutManager instance
27 27 // events: $(Events) instance
28 28 // save_widget: SaveWidget instance
29 29 // quick_help: QuickHelp instance
30 30 // base_url : string
31 31 // notebook_path : string
32 32 // notebook_name : string
33 33 options = options || {};
34 34 this.base_url = options.base_url || utils.get_body_data("baseUrl");
35 35 this.selector = selector;
36 36 this.notebook = options.notebook;
37 37 this.contents = options.contents;
38 38 this.layout_manager = options.layout_manager;
39 39 this.events = options.events;
40 40 this.save_widget = options.save_widget;
41 41 this.quick_help = options.quick_help;
42 42
43 43 try {
44 44 this.tour = new tour.Tour(this.notebook, this.events);
45 45 } catch (e) {
46 46 this.tour = undefined;
47 47 console.log("Failed to instantiate Notebook Tour", e);
48 48 }
49 49
50 50 if (this.selector !== undefined) {
51 51 this.element = $(selector);
52 52 this.style();
53 53 this.bind_events();
54 54 }
55 55 };
56 56
57 57 // TODO: This has definitively nothing to do with style ...
58 58 MenuBar.prototype.style = function () {
59 59 var that = this;
60 60 this.element.find("li").click(function (event, ui) {
61 61 // The selected cell loses focus when the menu is entered, so we
62 62 // re-select it upon selection.
63 63 var i = that.notebook.get_selected_index();
64 64 that.notebook.select(i);
65 65 }
66 66 );
67 67 };
68 68
69 69 MenuBar.prototype._nbconvert = function (format, download) {
70 70 download = download || false;
71 71 var notebook_path = this.notebook.notebook_path;
72 72 var notebook_name = this.notebook.notebook_name;
73 73 if (this.notebook.dirty) {
74 74 this.notebook.save_notebook({async : false});
75 75 }
76 76 var url = utils.url_join_encode(
77 77 this.base_url,
78 78 'nbconvert',
79 79 format,
80 80 notebook_path,
81 81 notebook_name
82 82 ) + "?download=" + download.toString();
83 83
84 84 window.open(url);
85 85 };
86 86
87 87 MenuBar.prototype.bind_events = function () {
88 88 // File
89 89 var that = this;
90 90 this.element.find('#new_notebook').click(function () {
91 91 var w = window.open();
92 92 // Create a new notebook in the same path as the current
93 93 // notebook's path.
94 94 var parent = utils.url_path_split(that.notebook.notebook_path)[0];
95 that.contents.new_untitled(parent, {
96 type: "notebook",
97 success: function (data) {
95 that.contents.new_untitled(parent, {type: "notebook"}).then(
96 function (data) {
98 97 w.location = utils.url_join_encode(
99 98 that.base_url, 'notebooks', data.path
100 99 );
101 100 },
102 error: function(error) {
101 function(error) {
103 102 w.close();
104 103 dialog.modal({
105 104 title : 'Creating Notebook Failed',
106 105 body : "The error was: " + error.message,
107 106 buttons : {'OK' : {'class' : 'btn-primary'}}
108 107 });
109 108 }
110 });
109 );
111 110 });
112 111 this.element.find('#open_notebook').click(function () {
113 112 var parent = utils.url_path_split(that.notebook.notebook_path)[0];
114 113 window.open(utils.url_join_encode(that.base_url, 'tree', parent));
115 114 });
116 115 this.element.find('#copy_notebook').click(function () {
117 116 that.notebook.copy_notebook();
118 117 return false;
119 118 });
120 119 this.element.find('#download_ipynb').click(function () {
121 120 var base_url = that.notebook.base_url;
122 121 var notebook_path = that.notebook.notebook_path;
123 122 var notebook_name = that.notebook.notebook_name;
124 123 if (that.notebook.dirty) {
125 124 that.notebook.save_notebook({async : false});
126 125 }
127 126
128 127 var url = utils.url_join_encode(
129 128 base_url,
130 129 'files',
131 130 notebook_path,
132 131 notebook_name
133 132 );
134 133 window.open(url + '?download=1');
135 134 });
136 135
137 136 this.element.find('#print_preview').click(function () {
138 137 that._nbconvert('html', false);
139 138 });
140 139
141 140 this.element.find('#download_py').click(function () {
142 141 that._nbconvert('python', true);
143 142 });
144 143
145 144 this.element.find('#download_html').click(function () {
146 145 that._nbconvert('html', true);
147 146 });
148 147
149 148 this.element.find('#download_rst').click(function () {
150 149 that._nbconvert('rst', true);
151 150 });
152 151
153 152 this.element.find('#download_pdf').click(function () {
154 153 that._nbconvert('pdf', true);
155 154 });
156 155
157 156 this.element.find('#rename_notebook').click(function () {
158 157 that.save_widget.rename_notebook({notebook: that.notebook});
159 158 });
160 159 this.element.find('#save_checkpoint').click(function () {
161 160 that.notebook.save_checkpoint();
162 161 });
163 162 this.element.find('#restore_checkpoint').click(function () {
164 163 });
165 164 this.element.find('#trust_notebook').click(function () {
166 165 that.notebook.trust_notebook();
167 166 });
168 167 this.events.on('trust_changed.Notebook', function (event, trusted) {
169 168 if (trusted) {
170 169 that.element.find('#trust_notebook')
171 170 .addClass("disabled")
172 171 .find("a").text("Trusted Notebook");
173 172 } else {
174 173 that.element.find('#trust_notebook')
175 174 .removeClass("disabled")
176 175 .find("a").text("Trust Notebook");
177 176 }
178 177 });
179 178 this.element.find('#kill_and_exit').click(function () {
180 179 var close_window = function () {
181 180 // allow closing of new tabs in Chromium, impossible in FF
182 181 window.open('', '_self', '');
183 182 window.close();
184 183 };
185 184 // finish with close on success or failure
186 185 that.notebook.session.delete(close_window, close_window);
187 186 });
188 187 // Edit
189 188 this.element.find('#cut_cell').click(function () {
190 189 that.notebook.cut_cell();
191 190 });
192 191 this.element.find('#copy_cell').click(function () {
193 192 that.notebook.copy_cell();
194 193 });
195 194 this.element.find('#delete_cell').click(function () {
196 195 that.notebook.delete_cell();
197 196 });
198 197 this.element.find('#undelete_cell').click(function () {
199 198 that.notebook.undelete_cell();
200 199 });
201 200 this.element.find('#split_cell').click(function () {
202 201 that.notebook.split_cell();
203 202 });
204 203 this.element.find('#merge_cell_above').click(function () {
205 204 that.notebook.merge_cell_above();
206 205 });
207 206 this.element.find('#merge_cell_below').click(function () {
208 207 that.notebook.merge_cell_below();
209 208 });
210 209 this.element.find('#move_cell_up').click(function () {
211 210 that.notebook.move_cell_up();
212 211 });
213 212 this.element.find('#move_cell_down').click(function () {
214 213 that.notebook.move_cell_down();
215 214 });
216 215 this.element.find('#edit_nb_metadata').click(function () {
217 216 that.notebook.edit_metadata({
218 217 notebook: that.notebook,
219 218 keyboard_manager: that.notebook.keyboard_manager});
220 219 });
221 220
222 221 // View
223 222 this.element.find('#toggle_header').click(function () {
224 223 $('div#header').toggle();
225 224 that.layout_manager.do_resize();
226 225 });
227 226 this.element.find('#toggle_toolbar').click(function () {
228 227 $('div#maintoolbar').toggle();
229 228 that.layout_manager.do_resize();
230 229 });
231 230 // Insert
232 231 this.element.find('#insert_cell_above').click(function () {
233 232 that.notebook.insert_cell_above('code');
234 233 that.notebook.select_prev();
235 234 });
236 235 this.element.find('#insert_cell_below').click(function () {
237 236 that.notebook.insert_cell_below('code');
238 237 that.notebook.select_next();
239 238 });
240 239 // Cell
241 240 this.element.find('#run_cell').click(function () {
242 241 that.notebook.execute_cell();
243 242 });
244 243 this.element.find('#run_cell_select_below').click(function () {
245 244 that.notebook.execute_cell_and_select_below();
246 245 });
247 246 this.element.find('#run_cell_insert_below').click(function () {
248 247 that.notebook.execute_cell_and_insert_below();
249 248 });
250 249 this.element.find('#run_all_cells').click(function () {
251 250 that.notebook.execute_all_cells();
252 251 });
253 252 this.element.find('#run_all_cells_above').click(function () {
254 253 that.notebook.execute_cells_above();
255 254 });
256 255 this.element.find('#run_all_cells_below').click(function () {
257 256 that.notebook.execute_cells_below();
258 257 });
259 258 this.element.find('#to_code').click(function () {
260 259 that.notebook.to_code();
261 260 });
262 261 this.element.find('#to_markdown').click(function () {
263 262 that.notebook.to_markdown();
264 263 });
265 264 this.element.find('#to_raw').click(function () {
266 265 that.notebook.to_raw();
267 266 });
268 267
269 268 this.element.find('#toggle_current_output').click(function () {
270 269 that.notebook.toggle_output();
271 270 });
272 271 this.element.find('#toggle_current_output_scroll').click(function () {
273 272 that.notebook.toggle_output_scroll();
274 273 });
275 274 this.element.find('#clear_current_output').click(function () {
276 275 that.notebook.clear_output();
277 276 });
278 277
279 278 this.element.find('#toggle_all_output').click(function () {
280 279 that.notebook.toggle_all_output();
281 280 });
282 281 this.element.find('#toggle_all_output_scroll').click(function () {
283 282 that.notebook.toggle_all_output_scroll();
284 283 });
285 284 this.element.find('#clear_all_output').click(function () {
286 285 that.notebook.clear_all_output();
287 286 });
288 287
289 288 // Kernel
290 289 this.element.find('#int_kernel').click(function () {
291 290 that.notebook.kernel.interrupt();
292 291 });
293 292 this.element.find('#restart_kernel').click(function () {
294 293 that.notebook.restart_kernel();
295 294 });
296 295 this.element.find('#reconnect_kernel').click(function () {
297 296 that.notebook.kernel.reconnect();
298 297 });
299 298 // Help
300 299 if (this.tour) {
301 300 this.element.find('#notebook_tour').click(function () {
302 301 that.tour.start();
303 302 });
304 303 } else {
305 304 this.element.find('#notebook_tour').addClass("disabled");
306 305 }
307 306 this.element.find('#keyboard_shortcuts').click(function () {
308 307 that.quick_help.show_keyboard_shortcuts();
309 308 });
310 309
311 310 this.update_restore_checkpoint(null);
312 311
313 312 this.events.on('checkpoints_listed.Notebook', function (event, data) {
314 313 that.update_restore_checkpoint(that.notebook.checkpoints);
315 314 });
316 315
317 316 this.events.on('checkpoint_created.Notebook', function (event, data) {
318 317 that.update_restore_checkpoint(that.notebook.checkpoints);
319 318 });
320 319 };
321 320
322 321 MenuBar.prototype.update_restore_checkpoint = function(checkpoints) {
323 322 var ul = this.element.find("#restore_checkpoint").find("ul");
324 323 ul.empty();
325 324 if (!checkpoints || checkpoints.length === 0) {
326 325 ul.append(
327 326 $("<li/>")
328 327 .addClass("disabled")
329 328 .append(
330 329 $("<a/>")
331 330 .text("No checkpoints")
332 331 )
333 332 );
334 333 return;
335 334 }
336 335
337 336 var that = this;
338 337 checkpoints.map(function (checkpoint) {
339 338 var d = new Date(checkpoint.last_modified);
340 339 ul.append(
341 340 $("<li/>").append(
342 341 $("<a/>")
343 342 .attr("href", "#")
344 343 .text(moment(d).format("LLLL"))
345 344 .click(function () {
346 345 that.notebook.restore_checkpoint_dialog(checkpoint);
347 346 })
348 347 )
349 348 );
350 349 });
351 350 };
352 351
353 352 // Backwards compatability.
354 353 IPython.MenuBar = MenuBar;
355 354
356 355 return {'MenuBar': MenuBar};
357 356 });
@@ -1,2483 +1,2481 b''
1 1 // Copyright (c) IPython Development Team.
2 2 // Distributed under the terms of the Modified BSD License.
3 3
4 4 define([
5 5 'base/js/namespace',
6 6 'jquery',
7 7 'base/js/utils',
8 8 'base/js/dialog',
9 9 'notebook/js/textcell',
10 10 'notebook/js/codecell',
11 11 'services/sessions/session',
12 12 'notebook/js/celltoolbar',
13 13 'components/marked/lib/marked',
14 14 'highlight',
15 15 'notebook/js/mathjaxutils',
16 16 'base/js/keyboard',
17 17 'notebook/js/tooltip',
18 18 'notebook/js/celltoolbarpresets/default',
19 19 'notebook/js/celltoolbarpresets/rawcell',
20 20 'notebook/js/celltoolbarpresets/slideshow',
21 21 'notebook/js/scrollmanager'
22 22 ], function (
23 23 IPython,
24 24 $,
25 25 utils,
26 26 dialog,
27 27 textcell,
28 28 codecell,
29 29 session,
30 30 celltoolbar,
31 31 marked,
32 32 hljs,
33 33 mathjaxutils,
34 34 keyboard,
35 35 tooltip,
36 36 default_celltoolbar,
37 37 rawcell_celltoolbar,
38 38 slideshow_celltoolbar,
39 39 scrollmanager
40 40 ) {
41 41
42 42 var Notebook = function (selector, options) {
43 43 // Constructor
44 44 //
45 45 // A notebook contains and manages cells.
46 46 //
47 47 // Parameters:
48 48 // selector: string
49 49 // options: dictionary
50 50 // Dictionary of keyword arguments.
51 51 // events: $(Events) instance
52 52 // keyboard_manager: KeyboardManager instance
53 53 // contents: Contents instance
54 54 // save_widget: SaveWidget instance
55 55 // config: dictionary
56 56 // base_url : string
57 57 // notebook_path : string
58 58 // notebook_name : string
59 59 this.config = utils.mergeopt(Notebook, options.config);
60 60 this.base_url = options.base_url;
61 61 this.notebook_path = options.notebook_path;
62 62 this.notebook_name = options.notebook_name;
63 63 this.events = options.events;
64 64 this.keyboard_manager = options.keyboard_manager;
65 65 this.contents = options.contents;
66 66 this.save_widget = options.save_widget;
67 67 this.tooltip = new tooltip.Tooltip(this.events);
68 68 this.ws_url = options.ws_url;
69 69 this._session_starting = false;
70 70 this.default_cell_type = this.config.default_cell_type || 'code';
71 71
72 72 // Create default scroll manager.
73 73 this.scroll_manager = new scrollmanager.ScrollManager(this);
74 74
75 75 // TODO: This code smells (and the other `= this` line a couple lines down)
76 76 // We need a better way to deal with circular instance references.
77 77 this.keyboard_manager.notebook = this;
78 78 this.save_widget.notebook = this;
79 79
80 80 mathjaxutils.init();
81 81
82 82 if (marked) {
83 83 marked.setOptions({
84 84 gfm : true,
85 85 tables: true,
86 86 langPrefix: "language-",
87 87 highlight: function(code, lang) {
88 88 if (!lang) {
89 89 // no language, no highlight
90 90 return code;
91 91 }
92 92 var highlighted;
93 93 try {
94 94 highlighted = hljs.highlight(lang, code, false);
95 95 } catch(err) {
96 96 highlighted = hljs.highlightAuto(code);
97 97 }
98 98 return highlighted.value;
99 99 }
100 100 });
101 101 }
102 102
103 103 this.element = $(selector);
104 104 this.element.scroll();
105 105 this.element.data("notebook", this);
106 106 this.next_prompt_number = 1;
107 107 this.session = null;
108 108 this.kernel = null;
109 109 this.clipboard = null;
110 110 this.undelete_backup = null;
111 111 this.undelete_index = null;
112 112 this.undelete_below = false;
113 113 this.paste_enabled = false;
114 114 // It is important to start out in command mode to match the intial mode
115 115 // of the KeyboardManager.
116 116 this.mode = 'command';
117 117 this.set_dirty(false);
118 118 this.metadata = {};
119 119 this._checkpoint_after_save = false;
120 120 this.last_checkpoint = null;
121 121 this.checkpoints = [];
122 122 this.autosave_interval = 0;
123 123 this.autosave_timer = null;
124 124 // autosave *at most* every two minutes
125 125 this.minimum_autosave_interval = 120000;
126 126 this.notebook_name_blacklist_re = /[\/\\:]/;
127 127 this.nbformat = 4; // Increment this when changing the nbformat
128 128 this.nbformat_minor = 0; // Increment this when changing the nbformat
129 129 this.codemirror_mode = 'ipython';
130 130 this.create_elements();
131 131 this.bind_events();
132 132 this.save_notebook = function() { // don't allow save until notebook_loaded
133 133 this.save_notebook_error(null, null, "Load failed, save is disabled");
134 134 };
135 135
136 136 // Trigger cell toolbar registration.
137 137 default_celltoolbar.register(this);
138 138 rawcell_celltoolbar.register(this);
139 139 slideshow_celltoolbar.register(this);
140 140 };
141 141
142 142 Notebook.options_default = {
143 143 // can be any cell type, or the special values of
144 144 // 'above', 'below', or 'selected' to get the value from another cell.
145 145 Notebook: {
146 146 default_cell_type: 'code',
147 147 }
148 148 };
149 149
150 150
151 151 /**
152 152 * Create an HTML and CSS representation of the notebook.
153 153 *
154 154 * @method create_elements
155 155 */
156 156 Notebook.prototype.create_elements = function () {
157 157 var that = this;
158 158 this.element.attr('tabindex','-1');
159 159 this.container = $("<div/>").addClass("container").attr("id", "notebook-container");
160 160 // We add this end_space div to the end of the notebook div to:
161 161 // i) provide a margin between the last cell and the end of the notebook
162 162 // ii) to prevent the div from scrolling up when the last cell is being
163 163 // edited, but is too low on the page, which browsers will do automatically.
164 164 var end_space = $('<div/>').addClass('end_space');
165 165 end_space.dblclick(function (e) {
166 166 var ncells = that.ncells();
167 167 that.insert_cell_below('code',ncells-1);
168 168 });
169 169 this.element.append(this.container);
170 170 this.container.append(end_space);
171 171 };
172 172
173 173 /**
174 174 * Bind JavaScript events: key presses and custom IPython events.
175 175 *
176 176 * @method bind_events
177 177 */
178 178 Notebook.prototype.bind_events = function () {
179 179 var that = this;
180 180
181 181 this.events.on('set_next_input.Notebook', function (event, data) {
182 182 var index = that.find_cell_index(data.cell);
183 183 var new_cell = that.insert_cell_below('code',index);
184 184 new_cell.set_text(data.text);
185 185 that.dirty = true;
186 186 });
187 187
188 188 this.events.on('set_dirty.Notebook', function (event, data) {
189 189 that.dirty = data.value;
190 190 });
191 191
192 192 this.events.on('trust_changed.Notebook', function (event, trusted) {
193 193 that.trusted = trusted;
194 194 });
195 195
196 196 this.events.on('select.Cell', function (event, data) {
197 197 var index = that.find_cell_index(data.cell);
198 198 that.select(index);
199 199 });
200 200
201 201 this.events.on('edit_mode.Cell', function (event, data) {
202 202 that.handle_edit_mode(data.cell);
203 203 });
204 204
205 205 this.events.on('command_mode.Cell', function (event, data) {
206 206 that.handle_command_mode(data.cell);
207 207 });
208 208
209 209 this.events.on('spec_changed.Kernel', function(event, data) {
210 210 that.metadata.kernelspec =
211 211 {name: data.name, display_name: data.display_name};
212 212 });
213 213
214 214 this.events.on('kernel_ready.Kernel', function(event, data) {
215 215 var kinfo = data.kernel.info_reply;
216 216 var langinfo = kinfo.language_info || {};
217 217 if (!langinfo.name) langinfo.name = kinfo.language;
218 218
219 219 that.metadata.language_info = langinfo;
220 220 // Mode 'null' should be plain, unhighlighted text.
221 221 var cm_mode = langinfo.codemirror_mode || langinfo.language || 'null';
222 222 that.set_codemirror_mode(cm_mode);
223 223 });
224 224
225 225 var collapse_time = function (time) {
226 226 var app_height = $('#ipython-main-app').height(); // content height
227 227 var splitter_height = $('div#pager_splitter').outerHeight(true);
228 228 var new_height = app_height - splitter_height;
229 229 that.element.animate({height : new_height + 'px'}, time);
230 230 };
231 231
232 232 this.element.bind('collapse_pager', function (event, extrap) {
233 233 var time = (extrap !== undefined) ? ((extrap.duration !== undefined ) ? extrap.duration : 'fast') : 'fast';
234 234 collapse_time(time);
235 235 });
236 236
237 237 var expand_time = function (time) {
238 238 var app_height = $('#ipython-main-app').height(); // content height
239 239 var splitter_height = $('div#pager_splitter').outerHeight(true);
240 240 var pager_height = $('div#pager').outerHeight(true);
241 241 var new_height = app_height - pager_height - splitter_height;
242 242 that.element.animate({height : new_height + 'px'}, time);
243 243 };
244 244
245 245 this.element.bind('expand_pager', function (event, extrap) {
246 246 var time = (extrap !== undefined) ? ((extrap.duration !== undefined ) ? extrap.duration : 'fast') : 'fast';
247 247 expand_time(time);
248 248 });
249 249
250 250 // Firefox 22 broke $(window).on("beforeunload")
251 251 // I'm not sure why or how.
252 252 window.onbeforeunload = function (e) {
253 253 // TODO: Make killing the kernel configurable.
254 254 var kill_kernel = false;
255 255 if (kill_kernel) {
256 256 that.session.delete();
257 257 }
258 258 // if we are autosaving, trigger an autosave on nav-away.
259 259 // still warn, because if we don't the autosave may fail.
260 260 if (that.dirty) {
261 261 if ( that.autosave_interval ) {
262 262 // schedule autosave in a timeout
263 263 // this gives you a chance to forcefully discard changes
264 264 // by reloading the page if you *really* want to.
265 265 // the timer doesn't start until you *dismiss* the dialog.
266 266 setTimeout(function () {
267 267 if (that.dirty) {
268 268 that.save_notebook();
269 269 }
270 270 }, 1000);
271 271 return "Autosave in progress, latest changes may be lost.";
272 272 } else {
273 273 return "Unsaved changes will be lost.";
274 274 }
275 275 }
276 276 // Null is the *only* return value that will make the browser not
277 277 // pop up the "don't leave" dialog.
278 278 return null;
279 279 };
280 280 };
281 281
282 282 /**
283 283 * Set the dirty flag, and trigger the set_dirty.Notebook event
284 284 *
285 285 * @method set_dirty
286 286 */
287 287 Notebook.prototype.set_dirty = function (value) {
288 288 if (value === undefined) {
289 289 value = true;
290 290 }
291 291 if (this.dirty == value) {
292 292 return;
293 293 }
294 294 this.events.trigger('set_dirty.Notebook', {value: value});
295 295 };
296 296
297 297 /**
298 298 * Scroll the top of the page to a given cell.
299 299 *
300 300 * @method scroll_to_cell
301 301 * @param {Number} cell_number An index of the cell to view
302 302 * @param {Number} time Animation time in milliseconds
303 303 * @return {Number} Pixel offset from the top of the container
304 304 */
305 305 Notebook.prototype.scroll_to_cell = function (cell_number, time) {
306 306 var cells = this.get_cells();
307 307 time = time || 0;
308 308 cell_number = Math.min(cells.length-1,cell_number);
309 309 cell_number = Math.max(0 ,cell_number);
310 310 var scroll_value = cells[cell_number].element.position().top-cells[0].element.position().top ;
311 311 this.element.animate({scrollTop:scroll_value}, time);
312 312 return scroll_value;
313 313 };
314 314
315 315 /**
316 316 * Scroll to the bottom of the page.
317 317 *
318 318 * @method scroll_to_bottom
319 319 */
320 320 Notebook.prototype.scroll_to_bottom = function () {
321 321 this.element.animate({scrollTop:this.element.get(0).scrollHeight}, 0);
322 322 };
323 323
324 324 /**
325 325 * Scroll to the top of the page.
326 326 *
327 327 * @method scroll_to_top
328 328 */
329 329 Notebook.prototype.scroll_to_top = function () {
330 330 this.element.animate({scrollTop:0}, 0);
331 331 };
332 332
333 333 // Edit Notebook metadata
334 334
335 335 Notebook.prototype.edit_metadata = function () {
336 336 var that = this;
337 337 dialog.edit_metadata({
338 338 md: this.metadata,
339 339 callback: function (md) {
340 340 that.metadata = md;
341 341 },
342 342 name: 'Notebook',
343 343 notebook: this,
344 344 keyboard_manager: this.keyboard_manager});
345 345 };
346 346
347 347 // Cell indexing, retrieval, etc.
348 348
349 349 /**
350 350 * Get all cell elements in the notebook.
351 351 *
352 352 * @method get_cell_elements
353 353 * @return {jQuery} A selector of all cell elements
354 354 */
355 355 Notebook.prototype.get_cell_elements = function () {
356 356 return this.container.children("div.cell");
357 357 };
358 358
359 359 /**
360 360 * Get a particular cell element.
361 361 *
362 362 * @method get_cell_element
363 363 * @param {Number} index An index of a cell to select
364 364 * @return {jQuery} A selector of the given cell.
365 365 */
366 366 Notebook.prototype.get_cell_element = function (index) {
367 367 var result = null;
368 368 var e = this.get_cell_elements().eq(index);
369 369 if (e.length !== 0) {
370 370 result = e;
371 371 }
372 372 return result;
373 373 };
374 374
375 375 /**
376 376 * Try to get a particular cell by msg_id.
377 377 *
378 378 * @method get_msg_cell
379 379 * @param {String} msg_id A message UUID
380 380 * @return {Cell} Cell or null if no cell was found.
381 381 */
382 382 Notebook.prototype.get_msg_cell = function (msg_id) {
383 383 return codecell.CodeCell.msg_cells[msg_id] || null;
384 384 };
385 385
386 386 /**
387 387 * Count the cells in this notebook.
388 388 *
389 389 * @method ncells
390 390 * @return {Number} The number of cells in this notebook
391 391 */
392 392 Notebook.prototype.ncells = function () {
393 393 return this.get_cell_elements().length;
394 394 };
395 395
396 396 /**
397 397 * Get all Cell objects in this notebook.
398 398 *
399 399 * @method get_cells
400 400 * @return {Array} This notebook's Cell objects
401 401 */
402 402 // TODO: we are often calling cells as cells()[i], which we should optimize
403 403 // to cells(i) or a new method.
404 404 Notebook.prototype.get_cells = function () {
405 405 return this.get_cell_elements().toArray().map(function (e) {
406 406 return $(e).data("cell");
407 407 });
408 408 };
409 409
410 410 /**
411 411 * Get a Cell object from this notebook.
412 412 *
413 413 * @method get_cell
414 414 * @param {Number} index An index of a cell to retrieve
415 415 * @return {Cell} Cell or null if no cell was found.
416 416 */
417 417 Notebook.prototype.get_cell = function (index) {
418 418 var result = null;
419 419 var ce = this.get_cell_element(index);
420 420 if (ce !== null) {
421 421 result = ce.data('cell');
422 422 }
423 423 return result;
424 424 };
425 425
426 426 /**
427 427 * Get the cell below a given cell.
428 428 *
429 429 * @method get_next_cell
430 430 * @param {Cell} cell The provided cell
431 431 * @return {Cell} the next cell or null if no cell was found.
432 432 */
433 433 Notebook.prototype.get_next_cell = function (cell) {
434 434 var result = null;
435 435 var index = this.find_cell_index(cell);
436 436 if (this.is_valid_cell_index(index+1)) {
437 437 result = this.get_cell(index+1);
438 438 }
439 439 return result;
440 440 };
441 441
442 442 /**
443 443 * Get the cell above a given cell.
444 444 *
445 445 * @method get_prev_cell
446 446 * @param {Cell} cell The provided cell
447 447 * @return {Cell} The previous cell or null if no cell was found.
448 448 */
449 449 Notebook.prototype.get_prev_cell = function (cell) {
450 450 var result = null;
451 451 var index = this.find_cell_index(cell);
452 452 if (index !== null && index > 0) {
453 453 result = this.get_cell(index-1);
454 454 }
455 455 return result;
456 456 };
457 457
458 458 /**
459 459 * Get the numeric index of a given cell.
460 460 *
461 461 * @method find_cell_index
462 462 * @param {Cell} cell The provided cell
463 463 * @return {Number} The cell's numeric index or null if no cell was found.
464 464 */
465 465 Notebook.prototype.find_cell_index = function (cell) {
466 466 var result = null;
467 467 this.get_cell_elements().filter(function (index) {
468 468 if ($(this).data("cell") === cell) {
469 469 result = index;
470 470 }
471 471 });
472 472 return result;
473 473 };
474 474
475 475 /**
476 476 * Get a given index , or the selected index if none is provided.
477 477 *
478 478 * @method index_or_selected
479 479 * @param {Number} index A cell's index
480 480 * @return {Number} The given index, or selected index if none is provided.
481 481 */
482 482 Notebook.prototype.index_or_selected = function (index) {
483 483 var i;
484 484 if (index === undefined || index === null) {
485 485 i = this.get_selected_index();
486 486 if (i === null) {
487 487 i = 0;
488 488 }
489 489 } else {
490 490 i = index;
491 491 }
492 492 return i;
493 493 };
494 494
495 495 /**
496 496 * Get the currently selected cell.
497 497 * @method get_selected_cell
498 498 * @return {Cell} The selected cell
499 499 */
500 500 Notebook.prototype.get_selected_cell = function () {
501 501 var index = this.get_selected_index();
502 502 return this.get_cell(index);
503 503 };
504 504
505 505 /**
506 506 * Check whether a cell index is valid.
507 507 *
508 508 * @method is_valid_cell_index
509 509 * @param {Number} index A cell index
510 510 * @return True if the index is valid, false otherwise
511 511 */
512 512 Notebook.prototype.is_valid_cell_index = function (index) {
513 513 if (index !== null && index >= 0 && index < this.ncells()) {
514 514 return true;
515 515 } else {
516 516 return false;
517 517 }
518 518 };
519 519
520 520 /**
521 521 * Get the index of the currently selected cell.
522 522
523 523 * @method get_selected_index
524 524 * @return {Number} The selected cell's numeric index
525 525 */
526 526 Notebook.prototype.get_selected_index = function () {
527 527 var result = null;
528 528 this.get_cell_elements().filter(function (index) {
529 529 if ($(this).data("cell").selected === true) {
530 530 result = index;
531 531 }
532 532 });
533 533 return result;
534 534 };
535 535
536 536
537 537 // Cell selection.
538 538
539 539 /**
540 540 * Programmatically select a cell.
541 541 *
542 542 * @method select
543 543 * @param {Number} index A cell's index
544 544 * @return {Notebook} This notebook
545 545 */
546 546 Notebook.prototype.select = function (index) {
547 547 if (this.is_valid_cell_index(index)) {
548 548 var sindex = this.get_selected_index();
549 549 if (sindex !== null && index !== sindex) {
550 550 // If we are about to select a different cell, make sure we are
551 551 // first in command mode.
552 552 if (this.mode !== 'command') {
553 553 this.command_mode();
554 554 }
555 555 this.get_cell(sindex).unselect();
556 556 }
557 557 var cell = this.get_cell(index);
558 558 cell.select();
559 559 if (cell.cell_type === 'heading') {
560 560 this.events.trigger('selected_cell_type_changed.Notebook',
561 561 {'cell_type':cell.cell_type,level:cell.level}
562 562 );
563 563 } else {
564 564 this.events.trigger('selected_cell_type_changed.Notebook',
565 565 {'cell_type':cell.cell_type}
566 566 );
567 567 }
568 568 }
569 569 return this;
570 570 };
571 571
572 572 /**
573 573 * Programmatically select the next cell.
574 574 *
575 575 * @method select_next
576 576 * @return {Notebook} This notebook
577 577 */
578 578 Notebook.prototype.select_next = function () {
579 579 var index = this.get_selected_index();
580 580 this.select(index+1);
581 581 return this;
582 582 };
583 583
584 584 /**
585 585 * Programmatically select the previous cell.
586 586 *
587 587 * @method select_prev
588 588 * @return {Notebook} This notebook
589 589 */
590 590 Notebook.prototype.select_prev = function () {
591 591 var index = this.get_selected_index();
592 592 this.select(index-1);
593 593 return this;
594 594 };
595 595
596 596
597 597 // Edit/Command mode
598 598
599 599 /**
600 600 * Gets the index of the cell that is in edit mode.
601 601 *
602 602 * @method get_edit_index
603 603 *
604 604 * @return index {int}
605 605 **/
606 606 Notebook.prototype.get_edit_index = function () {
607 607 var result = null;
608 608 this.get_cell_elements().filter(function (index) {
609 609 if ($(this).data("cell").mode === 'edit') {
610 610 result = index;
611 611 }
612 612 });
613 613 return result;
614 614 };
615 615
616 616 /**
617 617 * Handle when a a cell blurs and the notebook should enter command mode.
618 618 *
619 619 * @method handle_command_mode
620 620 * @param [cell] {Cell} Cell to enter command mode on.
621 621 **/
622 622 Notebook.prototype.handle_command_mode = function (cell) {
623 623 if (this.mode !== 'command') {
624 624 cell.command_mode();
625 625 this.mode = 'command';
626 626 this.events.trigger('command_mode.Notebook');
627 627 this.keyboard_manager.command_mode();
628 628 }
629 629 };
630 630
631 631 /**
632 632 * Make the notebook enter command mode.
633 633 *
634 634 * @method command_mode
635 635 **/
636 636 Notebook.prototype.command_mode = function () {
637 637 var cell = this.get_cell(this.get_edit_index());
638 638 if (cell && this.mode !== 'command') {
639 639 // We don't call cell.command_mode, but rather call cell.focus_cell()
640 640 // which will blur and CM editor and trigger the call to
641 641 // handle_command_mode.
642 642 cell.focus_cell();
643 643 }
644 644 };
645 645
646 646 /**
647 647 * Handle when a cell fires it's edit_mode event.
648 648 *
649 649 * @method handle_edit_mode
650 650 * @param [cell] {Cell} Cell to enter edit mode on.
651 651 **/
652 652 Notebook.prototype.handle_edit_mode = function (cell) {
653 653 if (cell && this.mode !== 'edit') {
654 654 cell.edit_mode();
655 655 this.mode = 'edit';
656 656 this.events.trigger('edit_mode.Notebook');
657 657 this.keyboard_manager.edit_mode();
658 658 }
659 659 };
660 660
661 661 /**
662 662 * Make a cell enter edit mode.
663 663 *
664 664 * @method edit_mode
665 665 **/
666 666 Notebook.prototype.edit_mode = function () {
667 667 var cell = this.get_selected_cell();
668 668 if (cell && this.mode !== 'edit') {
669 669 cell.unrender();
670 670 cell.focus_editor();
671 671 }
672 672 };
673 673
674 674 /**
675 675 * Focus the currently selected cell.
676 676 *
677 677 * @method focus_cell
678 678 **/
679 679 Notebook.prototype.focus_cell = function () {
680 680 var cell = this.get_selected_cell();
681 681 if (cell === null) {return;} // No cell is selected
682 682 cell.focus_cell();
683 683 };
684 684
685 685 // Cell movement
686 686
687 687 /**
688 688 * Move given (or selected) cell up and select it.
689 689 *
690 690 * @method move_cell_up
691 691 * @param [index] {integer} cell index
692 692 * @return {Notebook} This notebook
693 693 **/
694 694 Notebook.prototype.move_cell_up = function (index) {
695 695 var i = this.index_or_selected(index);
696 696 if (this.is_valid_cell_index(i) && i > 0) {
697 697 var pivot = this.get_cell_element(i-1);
698 698 var tomove = this.get_cell_element(i);
699 699 if (pivot !== null && tomove !== null) {
700 700 tomove.detach();
701 701 pivot.before(tomove);
702 702 this.select(i-1);
703 703 var cell = this.get_selected_cell();
704 704 cell.focus_cell();
705 705 }
706 706 this.set_dirty(true);
707 707 }
708 708 return this;
709 709 };
710 710
711 711
712 712 /**
713 713 * Move given (or selected) cell down and select it
714 714 *
715 715 * @method move_cell_down
716 716 * @param [index] {integer} cell index
717 717 * @return {Notebook} This notebook
718 718 **/
719 719 Notebook.prototype.move_cell_down = function (index) {
720 720 var i = this.index_or_selected(index);
721 721 if (this.is_valid_cell_index(i) && this.is_valid_cell_index(i+1)) {
722 722 var pivot = this.get_cell_element(i+1);
723 723 var tomove = this.get_cell_element(i);
724 724 if (pivot !== null && tomove !== null) {
725 725 tomove.detach();
726 726 pivot.after(tomove);
727 727 this.select(i+1);
728 728 var cell = this.get_selected_cell();
729 729 cell.focus_cell();
730 730 }
731 731 }
732 732 this.set_dirty();
733 733 return this;
734 734 };
735 735
736 736
737 737 // Insertion, deletion.
738 738
739 739 /**
740 740 * Delete a cell from the notebook.
741 741 *
742 742 * @method delete_cell
743 743 * @param [index] A cell's numeric index
744 744 * @return {Notebook} This notebook
745 745 */
746 746 Notebook.prototype.delete_cell = function (index) {
747 747 var i = this.index_or_selected(index);
748 748 var cell = this.get_cell(i);
749 749 if (!cell.is_deletable()) {
750 750 return this;
751 751 }
752 752
753 753 this.undelete_backup = cell.toJSON();
754 754 $('#undelete_cell').removeClass('disabled');
755 755 if (this.is_valid_cell_index(i)) {
756 756 var old_ncells = this.ncells();
757 757 var ce = this.get_cell_element(i);
758 758 ce.remove();
759 759 if (i === 0) {
760 760 // Always make sure we have at least one cell.
761 761 if (old_ncells === 1) {
762 762 this.insert_cell_below('code');
763 763 }
764 764 this.select(0);
765 765 this.undelete_index = 0;
766 766 this.undelete_below = false;
767 767 } else if (i === old_ncells-1 && i !== 0) {
768 768 this.select(i-1);
769 769 this.undelete_index = i - 1;
770 770 this.undelete_below = true;
771 771 } else {
772 772 this.select(i);
773 773 this.undelete_index = i;
774 774 this.undelete_below = false;
775 775 }
776 776 this.events.trigger('delete.Cell', {'cell': cell, 'index': i});
777 777 this.set_dirty(true);
778 778 }
779 779 return this;
780 780 };
781 781
782 782 /**
783 783 * Restore the most recently deleted cell.
784 784 *
785 785 * @method undelete
786 786 */
787 787 Notebook.prototype.undelete_cell = function() {
788 788 if (this.undelete_backup !== null && this.undelete_index !== null) {
789 789 var current_index = this.get_selected_index();
790 790 if (this.undelete_index < current_index) {
791 791 current_index = current_index + 1;
792 792 }
793 793 if (this.undelete_index >= this.ncells()) {
794 794 this.select(this.ncells() - 1);
795 795 }
796 796 else {
797 797 this.select(this.undelete_index);
798 798 }
799 799 var cell_data = this.undelete_backup;
800 800 var new_cell = null;
801 801 if (this.undelete_below) {
802 802 new_cell = this.insert_cell_below(cell_data.cell_type);
803 803 } else {
804 804 new_cell = this.insert_cell_above(cell_data.cell_type);
805 805 }
806 806 new_cell.fromJSON(cell_data);
807 807 if (this.undelete_below) {
808 808 this.select(current_index+1);
809 809 } else {
810 810 this.select(current_index);
811 811 }
812 812 this.undelete_backup = null;
813 813 this.undelete_index = null;
814 814 }
815 815 $('#undelete_cell').addClass('disabled');
816 816 };
817 817
818 818 /**
819 819 * Insert a cell so that after insertion the cell is at given index.
820 820 *
821 821 * If cell type is not provided, it will default to the type of the
822 822 * currently active cell.
823 823 *
824 824 * Similar to insert_above, but index parameter is mandatory
825 825 *
826 826 * Index will be brought back into the accessible range [0,n]
827 827 *
828 828 * @method insert_cell_at_index
829 829 * @param [type] {string} in ['code','markdown', 'raw'], defaults to 'code'
830 830 * @param [index] {int} a valid index where to insert cell
831 831 *
832 832 * @return cell {cell|null} created cell or null
833 833 **/
834 834 Notebook.prototype.insert_cell_at_index = function(type, index){
835 835
836 836 var ncells = this.ncells();
837 837 index = Math.min(index, ncells);
838 838 index = Math.max(index, 0);
839 839 var cell = null;
840 840 type = type || this.default_cell_type;
841 841 if (type === 'above') {
842 842 if (index > 0) {
843 843 type = this.get_cell(index-1).cell_type;
844 844 } else {
845 845 type = 'code';
846 846 }
847 847 } else if (type === 'below') {
848 848 if (index < ncells) {
849 849 type = this.get_cell(index).cell_type;
850 850 } else {
851 851 type = 'code';
852 852 }
853 853 } else if (type === 'selected') {
854 854 type = this.get_selected_cell().cell_type;
855 855 }
856 856
857 857 if (ncells === 0 || this.is_valid_cell_index(index) || index === ncells) {
858 858 var cell_options = {
859 859 events: this.events,
860 860 config: this.config,
861 861 keyboard_manager: this.keyboard_manager,
862 862 notebook: this,
863 863 tooltip: this.tooltip,
864 864 };
865 865 switch(type) {
866 866 case 'code':
867 867 cell = new codecell.CodeCell(this.kernel, cell_options);
868 868 cell.set_input_prompt();
869 869 break;
870 870 case 'markdown':
871 871 cell = new textcell.MarkdownCell(cell_options);
872 872 break;
873 873 case 'raw':
874 874 cell = new textcell.RawCell(cell_options);
875 875 break;
876 876 default:
877 877 console.log("invalid cell type: ", type);
878 878 }
879 879
880 880 if(this._insert_element_at_index(cell.element,index)) {
881 881 cell.render();
882 882 this.events.trigger('create.Cell', {'cell': cell, 'index': index});
883 883 cell.refresh();
884 884 // We used to select the cell after we refresh it, but there
885 885 // are now cases were this method is called where select is
886 886 // not appropriate. The selection logic should be handled by the
887 887 // caller of the the top level insert_cell methods.
888 888 this.set_dirty(true);
889 889 }
890 890 }
891 891 return cell;
892 892
893 893 };
894 894
895 895 /**
896 896 * Insert an element at given cell index.
897 897 *
898 898 * @method _insert_element_at_index
899 899 * @param element {dom_element} a cell element
900 900 * @param [index] {int} a valid index where to inser cell
901 901 * @private
902 902 *
903 903 * return true if everything whent fine.
904 904 **/
905 905 Notebook.prototype._insert_element_at_index = function(element, index){
906 906 if (element === undefined){
907 907 return false;
908 908 }
909 909
910 910 var ncells = this.ncells();
911 911
912 912 if (ncells === 0) {
913 913 // special case append if empty
914 914 this.element.find('div.end_space').before(element);
915 915 } else if ( ncells === index ) {
916 916 // special case append it the end, but not empty
917 917 this.get_cell_element(index-1).after(element);
918 918 } else if (this.is_valid_cell_index(index)) {
919 919 // otherwise always somewhere to append to
920 920 this.get_cell_element(index).before(element);
921 921 } else {
922 922 return false;
923 923 }
924 924
925 925 if (this.undelete_index !== null && index <= this.undelete_index) {
926 926 this.undelete_index = this.undelete_index + 1;
927 927 this.set_dirty(true);
928 928 }
929 929 return true;
930 930 };
931 931
932 932 /**
933 933 * Insert a cell of given type above given index, or at top
934 934 * of notebook if index smaller than 0.
935 935 *
936 936 * default index value is the one of currently selected cell
937 937 *
938 938 * @method insert_cell_above
939 939 * @param [type] {string} cell type
940 940 * @param [index] {integer}
941 941 *
942 942 * @return handle to created cell or null
943 943 **/
944 944 Notebook.prototype.insert_cell_above = function (type, index) {
945 945 index = this.index_or_selected(index);
946 946 return this.insert_cell_at_index(type, index);
947 947 };
948 948
949 949 /**
950 950 * Insert a cell of given type below given index, or at bottom
951 951 * of notebook if index greater than number of cells
952 952 *
953 953 * default index value is the one of currently selected cell
954 954 *
955 955 * @method insert_cell_below
956 956 * @param [type] {string} cell type
957 957 * @param [index] {integer}
958 958 *
959 959 * @return handle to created cell or null
960 960 *
961 961 **/
962 962 Notebook.prototype.insert_cell_below = function (type, index) {
963 963 index = this.index_or_selected(index);
964 964 return this.insert_cell_at_index(type, index+1);
965 965 };
966 966
967 967
968 968 /**
969 969 * Insert cell at end of notebook
970 970 *
971 971 * @method insert_cell_at_bottom
972 972 * @param {String} type cell type
973 973 *
974 974 * @return the added cell; or null
975 975 **/
976 976 Notebook.prototype.insert_cell_at_bottom = function (type){
977 977 var len = this.ncells();
978 978 return this.insert_cell_below(type,len-1);
979 979 };
980 980
981 981 /**
982 982 * Turn a cell into a code cell.
983 983 *
984 984 * @method to_code
985 985 * @param {Number} [index] A cell's index
986 986 */
987 987 Notebook.prototype.to_code = function (index) {
988 988 var i = this.index_or_selected(index);
989 989 if (this.is_valid_cell_index(i)) {
990 990 var source_cell = this.get_cell(i);
991 991 if (!(source_cell instanceof codecell.CodeCell)) {
992 992 var target_cell = this.insert_cell_below('code',i);
993 993 var text = source_cell.get_text();
994 994 if (text === source_cell.placeholder) {
995 995 text = '';
996 996 }
997 997 //metadata
998 998 target_cell.metadata = source_cell.metadata;
999 999
1000 1000 target_cell.set_text(text);
1001 1001 // make this value the starting point, so that we can only undo
1002 1002 // to this state, instead of a blank cell
1003 1003 target_cell.code_mirror.clearHistory();
1004 1004 source_cell.element.remove();
1005 1005 this.select(i);
1006 1006 var cursor = source_cell.code_mirror.getCursor();
1007 1007 target_cell.code_mirror.setCursor(cursor);
1008 1008 this.set_dirty(true);
1009 1009 }
1010 1010 }
1011 1011 };
1012 1012
1013 1013 /**
1014 1014 * Turn a cell into a Markdown cell.
1015 1015 *
1016 1016 * @method to_markdown
1017 1017 * @param {Number} [index] A cell's index
1018 1018 */
1019 1019 Notebook.prototype.to_markdown = function (index) {
1020 1020 var i = this.index_or_selected(index);
1021 1021 if (this.is_valid_cell_index(i)) {
1022 1022 var source_cell = this.get_cell(i);
1023 1023
1024 1024 if (!(source_cell instanceof textcell.MarkdownCell)) {
1025 1025 var target_cell = this.insert_cell_below('markdown',i);
1026 1026 var text = source_cell.get_text();
1027 1027
1028 1028 if (text === source_cell.placeholder) {
1029 1029 text = '';
1030 1030 }
1031 1031 // metadata
1032 1032 target_cell.metadata = source_cell.metadata;
1033 1033 // We must show the editor before setting its contents
1034 1034 target_cell.unrender();
1035 1035 target_cell.set_text(text);
1036 1036 // make this value the starting point, so that we can only undo
1037 1037 // to this state, instead of a blank cell
1038 1038 target_cell.code_mirror.clearHistory();
1039 1039 source_cell.element.remove();
1040 1040 this.select(i);
1041 1041 if ((source_cell instanceof textcell.TextCell) && source_cell.rendered) {
1042 1042 target_cell.render();
1043 1043 }
1044 1044 var cursor = source_cell.code_mirror.getCursor();
1045 1045 target_cell.code_mirror.setCursor(cursor);
1046 1046 this.set_dirty(true);
1047 1047 }
1048 1048 }
1049 1049 };
1050 1050
1051 1051 /**
1052 1052 * Turn a cell into a raw text cell.
1053 1053 *
1054 1054 * @method to_raw
1055 1055 * @param {Number} [index] A cell's index
1056 1056 */
1057 1057 Notebook.prototype.to_raw = function (index) {
1058 1058 var i = this.index_or_selected(index);
1059 1059 if (this.is_valid_cell_index(i)) {
1060 1060 var target_cell = null;
1061 1061 var source_cell = this.get_cell(i);
1062 1062
1063 1063 if (!(source_cell instanceof textcell.RawCell)) {
1064 1064 target_cell = this.insert_cell_below('raw',i);
1065 1065 var text = source_cell.get_text();
1066 1066 if (text === source_cell.placeholder) {
1067 1067 text = '';
1068 1068 }
1069 1069 //metadata
1070 1070 target_cell.metadata = source_cell.metadata;
1071 1071 // We must show the editor before setting its contents
1072 1072 target_cell.unrender();
1073 1073 target_cell.set_text(text);
1074 1074 // make this value the starting point, so that we can only undo
1075 1075 // to this state, instead of a blank cell
1076 1076 target_cell.code_mirror.clearHistory();
1077 1077 source_cell.element.remove();
1078 1078 this.select(i);
1079 1079 var cursor = source_cell.code_mirror.getCursor();
1080 1080 target_cell.code_mirror.setCursor(cursor);
1081 1081 this.set_dirty(true);
1082 1082 }
1083 1083 }
1084 1084 };
1085 1085
1086 1086 Notebook.prototype._warn_heading = function () {
1087 1087 // warn about heading cells being removed
1088 1088 dialog.modal({
1089 1089 notebook: this,
1090 1090 keyboard_manager: this.keyboard_manager,
1091 1091 title : "Use markdown headings",
1092 1092 body : $("<p/>").text(
1093 1093 'IPython no longer uses special heading cells. ' +
1094 1094 'Instead, write your headings in Markdown cells using # characters:'
1095 1095 ).append($('<pre/>').text(
1096 1096 '## This is a level 2 heading'
1097 1097 )),
1098 1098 buttons : {
1099 1099 "OK" : {},
1100 1100 }
1101 1101 });
1102 1102 };
1103 1103
1104 1104 /**
1105 1105 * Turn a cell into a markdown cell with a heading.
1106 1106 *
1107 1107 * @method to_heading
1108 1108 * @param {Number} [index] A cell's index
1109 1109 * @param {Number} [level] A heading level (e.g., 1 for h1)
1110 1110 */
1111 1111 Notebook.prototype.to_heading = function (index, level) {
1112 1112 this.to_markdown(index);
1113 1113 level = level || 1;
1114 1114 var i = this.index_or_selected(index);
1115 1115 if (this.is_valid_cell_index(i)) {
1116 1116 var cell = this.get_cell(i);
1117 1117 cell.set_heading_level(level);
1118 1118 this.set_dirty(true);
1119 1119 }
1120 1120 };
1121 1121
1122 1122
1123 1123 // Cut/Copy/Paste
1124 1124
1125 1125 /**
1126 1126 * Enable UI elements for pasting cells.
1127 1127 *
1128 1128 * @method enable_paste
1129 1129 */
1130 1130 Notebook.prototype.enable_paste = function () {
1131 1131 var that = this;
1132 1132 if (!this.paste_enabled) {
1133 1133 $('#paste_cell_replace').removeClass('disabled')
1134 1134 .on('click', function () {that.paste_cell_replace();});
1135 1135 $('#paste_cell_above').removeClass('disabled')
1136 1136 .on('click', function () {that.paste_cell_above();});
1137 1137 $('#paste_cell_below').removeClass('disabled')
1138 1138 .on('click', function () {that.paste_cell_below();});
1139 1139 this.paste_enabled = true;
1140 1140 }
1141 1141 };
1142 1142
1143 1143 /**
1144 1144 * Disable UI elements for pasting cells.
1145 1145 *
1146 1146 * @method disable_paste
1147 1147 */
1148 1148 Notebook.prototype.disable_paste = function () {
1149 1149 if (this.paste_enabled) {
1150 1150 $('#paste_cell_replace').addClass('disabled').off('click');
1151 1151 $('#paste_cell_above').addClass('disabled').off('click');
1152 1152 $('#paste_cell_below').addClass('disabled').off('click');
1153 1153 this.paste_enabled = false;
1154 1154 }
1155 1155 };
1156 1156
1157 1157 /**
1158 1158 * Cut a cell.
1159 1159 *
1160 1160 * @method cut_cell
1161 1161 */
1162 1162 Notebook.prototype.cut_cell = function () {
1163 1163 this.copy_cell();
1164 1164 this.delete_cell();
1165 1165 };
1166 1166
1167 1167 /**
1168 1168 * Copy a cell.
1169 1169 *
1170 1170 * @method copy_cell
1171 1171 */
1172 1172 Notebook.prototype.copy_cell = function () {
1173 1173 var cell = this.get_selected_cell();
1174 1174 this.clipboard = cell.toJSON();
1175 1175 // remove undeletable status from the copied cell
1176 1176 if (this.clipboard.metadata.deletable !== undefined) {
1177 1177 delete this.clipboard.metadata.deletable;
1178 1178 }
1179 1179 this.enable_paste();
1180 1180 };
1181 1181
1182 1182 /**
1183 1183 * Replace the selected cell with a cell in the clipboard.
1184 1184 *
1185 1185 * @method paste_cell_replace
1186 1186 */
1187 1187 Notebook.prototype.paste_cell_replace = function () {
1188 1188 if (this.clipboard !== null && this.paste_enabled) {
1189 1189 var cell_data = this.clipboard;
1190 1190 var new_cell = this.insert_cell_above(cell_data.cell_type);
1191 1191 new_cell.fromJSON(cell_data);
1192 1192 var old_cell = this.get_next_cell(new_cell);
1193 1193 this.delete_cell(this.find_cell_index(old_cell));
1194 1194 this.select(this.find_cell_index(new_cell));
1195 1195 }
1196 1196 };
1197 1197
1198 1198 /**
1199 1199 * Paste a cell from the clipboard above the selected cell.
1200 1200 *
1201 1201 * @method paste_cell_above
1202 1202 */
1203 1203 Notebook.prototype.paste_cell_above = function () {
1204 1204 if (this.clipboard !== null && this.paste_enabled) {
1205 1205 var cell_data = this.clipboard;
1206 1206 var new_cell = this.insert_cell_above(cell_data.cell_type);
1207 1207 new_cell.fromJSON(cell_data);
1208 1208 new_cell.focus_cell();
1209 1209 }
1210 1210 };
1211 1211
1212 1212 /**
1213 1213 * Paste a cell from the clipboard below the selected cell.
1214 1214 *
1215 1215 * @method paste_cell_below
1216 1216 */
1217 1217 Notebook.prototype.paste_cell_below = function () {
1218 1218 if (this.clipboard !== null && this.paste_enabled) {
1219 1219 var cell_data = this.clipboard;
1220 1220 var new_cell = this.insert_cell_below(cell_data.cell_type);
1221 1221 new_cell.fromJSON(cell_data);
1222 1222 new_cell.focus_cell();
1223 1223 }
1224 1224 };
1225 1225
1226 1226 // Split/merge
1227 1227
1228 1228 /**
1229 1229 * Split the selected cell into two, at the cursor.
1230 1230 *
1231 1231 * @method split_cell
1232 1232 */
1233 1233 Notebook.prototype.split_cell = function () {
1234 1234 var cell = this.get_selected_cell();
1235 1235 if (cell.is_splittable()) {
1236 1236 var texta = cell.get_pre_cursor();
1237 1237 var textb = cell.get_post_cursor();
1238 1238 cell.set_text(textb);
1239 1239 var new_cell = this.insert_cell_above(cell.cell_type);
1240 1240 // Unrender the new cell so we can call set_text.
1241 1241 new_cell.unrender();
1242 1242 new_cell.set_text(texta);
1243 1243 }
1244 1244 };
1245 1245
1246 1246 /**
1247 1247 * Combine the selected cell into the cell above it.
1248 1248 *
1249 1249 * @method merge_cell_above
1250 1250 */
1251 1251 Notebook.prototype.merge_cell_above = function () {
1252 1252 var index = this.get_selected_index();
1253 1253 var cell = this.get_cell(index);
1254 1254 var render = cell.rendered;
1255 1255 if (!cell.is_mergeable()) {
1256 1256 return;
1257 1257 }
1258 1258 if (index > 0) {
1259 1259 var upper_cell = this.get_cell(index-1);
1260 1260 if (!upper_cell.is_mergeable()) {
1261 1261 return;
1262 1262 }
1263 1263 var upper_text = upper_cell.get_text();
1264 1264 var text = cell.get_text();
1265 1265 if (cell instanceof codecell.CodeCell) {
1266 1266 cell.set_text(upper_text+'\n'+text);
1267 1267 } else {
1268 1268 cell.unrender(); // Must unrender before we set_text.
1269 1269 cell.set_text(upper_text+'\n\n'+text);
1270 1270 if (render) {
1271 1271 // The rendered state of the final cell should match
1272 1272 // that of the original selected cell;
1273 1273 cell.render();
1274 1274 }
1275 1275 }
1276 1276 this.delete_cell(index-1);
1277 1277 this.select(this.find_cell_index(cell));
1278 1278 }
1279 1279 };
1280 1280
1281 1281 /**
1282 1282 * Combine the selected cell into the cell below it.
1283 1283 *
1284 1284 * @method merge_cell_below
1285 1285 */
1286 1286 Notebook.prototype.merge_cell_below = function () {
1287 1287 var index = this.get_selected_index();
1288 1288 var cell = this.get_cell(index);
1289 1289 var render = cell.rendered;
1290 1290 if (!cell.is_mergeable()) {
1291 1291 return;
1292 1292 }
1293 1293 if (index < this.ncells()-1) {
1294 1294 var lower_cell = this.get_cell(index+1);
1295 1295 if (!lower_cell.is_mergeable()) {
1296 1296 return;
1297 1297 }
1298 1298 var lower_text = lower_cell.get_text();
1299 1299 var text = cell.get_text();
1300 1300 if (cell instanceof codecell.CodeCell) {
1301 1301 cell.set_text(text+'\n'+lower_text);
1302 1302 } else {
1303 1303 cell.unrender(); // Must unrender before we set_text.
1304 1304 cell.set_text(text+'\n\n'+lower_text);
1305 1305 if (render) {
1306 1306 // The rendered state of the final cell should match
1307 1307 // that of the original selected cell;
1308 1308 cell.render();
1309 1309 }
1310 1310 }
1311 1311 this.delete_cell(index+1);
1312 1312 this.select(this.find_cell_index(cell));
1313 1313 }
1314 1314 };
1315 1315
1316 1316
1317 1317 // Cell collapsing and output clearing
1318 1318
1319 1319 /**
1320 1320 * Hide a cell's output.
1321 1321 *
1322 1322 * @method collapse_output
1323 1323 * @param {Number} index A cell's numeric index
1324 1324 */
1325 1325 Notebook.prototype.collapse_output = function (index) {
1326 1326 var i = this.index_or_selected(index);
1327 1327 var cell = this.get_cell(i);
1328 1328 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1329 1329 cell.collapse_output();
1330 1330 this.set_dirty(true);
1331 1331 }
1332 1332 };
1333 1333
1334 1334 /**
1335 1335 * Hide each code cell's output area.
1336 1336 *
1337 1337 * @method collapse_all_output
1338 1338 */
1339 1339 Notebook.prototype.collapse_all_output = function () {
1340 1340 this.get_cells().map(function (cell, i) {
1341 1341 if (cell instanceof codecell.CodeCell) {
1342 1342 cell.collapse_output();
1343 1343 }
1344 1344 });
1345 1345 // this should not be set if the `collapse` key is removed from nbformat
1346 1346 this.set_dirty(true);
1347 1347 };
1348 1348
1349 1349 /**
1350 1350 * Show a cell's output.
1351 1351 *
1352 1352 * @method expand_output
1353 1353 * @param {Number} index A cell's numeric index
1354 1354 */
1355 1355 Notebook.prototype.expand_output = function (index) {
1356 1356 var i = this.index_or_selected(index);
1357 1357 var cell = this.get_cell(i);
1358 1358 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1359 1359 cell.expand_output();
1360 1360 this.set_dirty(true);
1361 1361 }
1362 1362 };
1363 1363
1364 1364 /**
1365 1365 * Expand each code cell's output area, and remove scrollbars.
1366 1366 *
1367 1367 * @method expand_all_output
1368 1368 */
1369 1369 Notebook.prototype.expand_all_output = function () {
1370 1370 this.get_cells().map(function (cell, i) {
1371 1371 if (cell instanceof codecell.CodeCell) {
1372 1372 cell.expand_output();
1373 1373 }
1374 1374 });
1375 1375 // this should not be set if the `collapse` key is removed from nbformat
1376 1376 this.set_dirty(true);
1377 1377 };
1378 1378
1379 1379 /**
1380 1380 * Clear the selected CodeCell's output area.
1381 1381 *
1382 1382 * @method clear_output
1383 1383 * @param {Number} index A cell's numeric index
1384 1384 */
1385 1385 Notebook.prototype.clear_output = function (index) {
1386 1386 var i = this.index_or_selected(index);
1387 1387 var cell = this.get_cell(i);
1388 1388 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1389 1389 cell.clear_output();
1390 1390 this.set_dirty(true);
1391 1391 }
1392 1392 };
1393 1393
1394 1394 /**
1395 1395 * Clear each code cell's output area.
1396 1396 *
1397 1397 * @method clear_all_output
1398 1398 */
1399 1399 Notebook.prototype.clear_all_output = function () {
1400 1400 this.get_cells().map(function (cell, i) {
1401 1401 if (cell instanceof codecell.CodeCell) {
1402 1402 cell.clear_output();
1403 1403 }
1404 1404 });
1405 1405 this.set_dirty(true);
1406 1406 };
1407 1407
1408 1408 /**
1409 1409 * Scroll the selected CodeCell's output area.
1410 1410 *
1411 1411 * @method scroll_output
1412 1412 * @param {Number} index A cell's numeric index
1413 1413 */
1414 1414 Notebook.prototype.scroll_output = function (index) {
1415 1415 var i = this.index_or_selected(index);
1416 1416 var cell = this.get_cell(i);
1417 1417 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1418 1418 cell.scroll_output();
1419 1419 this.set_dirty(true);
1420 1420 }
1421 1421 };
1422 1422
1423 1423 /**
1424 1424 * Expand each code cell's output area, and add a scrollbar for long output.
1425 1425 *
1426 1426 * @method scroll_all_output
1427 1427 */
1428 1428 Notebook.prototype.scroll_all_output = function () {
1429 1429 this.get_cells().map(function (cell, i) {
1430 1430 if (cell instanceof codecell.CodeCell) {
1431 1431 cell.scroll_output();
1432 1432 }
1433 1433 });
1434 1434 // this should not be set if the `collapse` key is removed from nbformat
1435 1435 this.set_dirty(true);
1436 1436 };
1437 1437
1438 1438 /** Toggle whether a cell's output is collapsed or expanded.
1439 1439 *
1440 1440 * @method toggle_output
1441 1441 * @param {Number} index A cell's numeric index
1442 1442 */
1443 1443 Notebook.prototype.toggle_output = function (index) {
1444 1444 var i = this.index_or_selected(index);
1445 1445 var cell = this.get_cell(i);
1446 1446 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1447 1447 cell.toggle_output();
1448 1448 this.set_dirty(true);
1449 1449 }
1450 1450 };
1451 1451
1452 1452 /**
1453 1453 * Hide/show the output of all cells.
1454 1454 *
1455 1455 * @method toggle_all_output
1456 1456 */
1457 1457 Notebook.prototype.toggle_all_output = function () {
1458 1458 this.get_cells().map(function (cell, i) {
1459 1459 if (cell instanceof codecell.CodeCell) {
1460 1460 cell.toggle_output();
1461 1461 }
1462 1462 });
1463 1463 // this should not be set if the `collapse` key is removed from nbformat
1464 1464 this.set_dirty(true);
1465 1465 };
1466 1466
1467 1467 /**
1468 1468 * Toggle a scrollbar for long cell outputs.
1469 1469 *
1470 1470 * @method toggle_output_scroll
1471 1471 * @param {Number} index A cell's numeric index
1472 1472 */
1473 1473 Notebook.prototype.toggle_output_scroll = function (index) {
1474 1474 var i = this.index_or_selected(index);
1475 1475 var cell = this.get_cell(i);
1476 1476 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1477 1477 cell.toggle_output_scroll();
1478 1478 this.set_dirty(true);
1479 1479 }
1480 1480 };
1481 1481
1482 1482 /**
1483 1483 * Toggle the scrolling of long output on all cells.
1484 1484 *
1485 1485 * @method toggle_all_output_scrolling
1486 1486 */
1487 1487 Notebook.prototype.toggle_all_output_scroll = function () {
1488 1488 this.get_cells().map(function (cell, i) {
1489 1489 if (cell instanceof codecell.CodeCell) {
1490 1490 cell.toggle_output_scroll();
1491 1491 }
1492 1492 });
1493 1493 // this should not be set if the `collapse` key is removed from nbformat
1494 1494 this.set_dirty(true);
1495 1495 };
1496 1496
1497 1497 // Other cell functions: line numbers, ...
1498 1498
1499 1499 /**
1500 1500 * Toggle line numbers in the selected cell's input area.
1501 1501 *
1502 1502 * @method cell_toggle_line_numbers
1503 1503 */
1504 1504 Notebook.prototype.cell_toggle_line_numbers = function() {
1505 1505 this.get_selected_cell().toggle_line_numbers();
1506 1506 };
1507 1507
1508 1508 /**
1509 1509 * Set the codemirror mode for all code cells, including the default for
1510 1510 * new code cells.
1511 1511 *
1512 1512 * @method set_codemirror_mode
1513 1513 */
1514 1514 Notebook.prototype.set_codemirror_mode = function(newmode){
1515 1515 if (newmode === this.codemirror_mode) {
1516 1516 return;
1517 1517 }
1518 1518 this.codemirror_mode = newmode;
1519 1519 codecell.CodeCell.options_default.cm_config.mode = newmode;
1520 1520 var modename = newmode.mode || newmode.name || newmode;
1521 1521
1522 1522 var that = this;
1523 1523 utils.requireCodeMirrorMode(modename, function () {
1524 1524 that.get_cells().map(function(cell, i) {
1525 1525 if (cell.cell_type === 'code'){
1526 1526 cell.code_mirror.setOption('mode', newmode);
1527 1527 // This is currently redundant, because cm_config ends up as
1528 1528 // codemirror's own .options object, but I don't want to
1529 1529 // rely on that.
1530 1530 cell.cm_config.mode = newmode;
1531 1531 }
1532 1532 });
1533 1533 });
1534 1534 };
1535 1535
1536 1536 // Session related things
1537 1537
1538 1538 /**
1539 1539 * Start a new session and set it on each code cell.
1540 1540 *
1541 1541 * @method start_session
1542 1542 */
1543 1543 Notebook.prototype.start_session = function (kernel_name) {
1544 1544 if (this._session_starting) {
1545 1545 throw new session.SessionAlreadyStarting();
1546 1546 }
1547 1547 this._session_starting = true;
1548 1548
1549 1549 var options = {
1550 1550 base_url: this.base_url,
1551 1551 ws_url: this.ws_url,
1552 1552 notebook_path: this.notebook_path,
1553 1553 notebook_name: this.notebook_name,
1554 1554 kernel_name: kernel_name,
1555 1555 notebook: this
1556 1556 };
1557 1557
1558 1558 var success = $.proxy(this._session_started, this);
1559 1559 var failure = $.proxy(this._session_start_failed, this);
1560 1560
1561 1561 if (this.session !== null) {
1562 1562 this.session.restart(options, success, failure);
1563 1563 } else {
1564 1564 this.session = new session.Session(options);
1565 1565 this.session.start(success, failure);
1566 1566 }
1567 1567 };
1568 1568
1569 1569
1570 1570 /**
1571 1571 * Once a session is started, link the code cells to the kernel and pass the
1572 1572 * comm manager to the widget manager
1573 1573 *
1574 1574 */
1575 1575 Notebook.prototype._session_started = function (){
1576 1576 this._session_starting = false;
1577 1577 this.kernel = this.session.kernel;
1578 1578 var ncells = this.ncells();
1579 1579 for (var i=0; i<ncells; i++) {
1580 1580 var cell = this.get_cell(i);
1581 1581 if (cell instanceof codecell.CodeCell) {
1582 1582 cell.set_kernel(this.session.kernel);
1583 1583 }
1584 1584 }
1585 1585 };
1586 1586 Notebook.prototype._session_start_failed = function (jqxhr, status, error){
1587 1587 this._session_starting = false;
1588 1588 utils.log_ajax_error(jqxhr, status, error);
1589 1589 };
1590 1590
1591 1591 /**
1592 1592 * Prompt the user to restart the IPython kernel.
1593 1593 *
1594 1594 * @method restart_kernel
1595 1595 */
1596 1596 Notebook.prototype.restart_kernel = function () {
1597 1597 var that = this;
1598 1598 dialog.modal({
1599 1599 notebook: this,
1600 1600 keyboard_manager: this.keyboard_manager,
1601 1601 title : "Restart kernel or continue running?",
1602 1602 body : $("<p/>").text(
1603 1603 'Do you want to restart the current kernel? You will lose all variables defined in it.'
1604 1604 ),
1605 1605 buttons : {
1606 1606 "Continue running" : {},
1607 1607 "Restart" : {
1608 1608 "class" : "btn-danger",
1609 1609 "click" : function() {
1610 1610 that.kernel.restart();
1611 1611 }
1612 1612 }
1613 1613 }
1614 1614 });
1615 1615 };
1616 1616
1617 1617 /**
1618 1618 * Execute or render cell outputs and go into command mode.
1619 1619 *
1620 1620 * @method execute_cell
1621 1621 */
1622 1622 Notebook.prototype.execute_cell = function () {
1623 1623 // mode = shift, ctrl, alt
1624 1624 var cell = this.get_selected_cell();
1625 1625
1626 1626 cell.execute();
1627 1627 this.command_mode();
1628 1628 this.set_dirty(true);
1629 1629 };
1630 1630
1631 1631 /**
1632 1632 * Execute or render cell outputs and insert a new cell below.
1633 1633 *
1634 1634 * @method execute_cell_and_insert_below
1635 1635 */
1636 1636 Notebook.prototype.execute_cell_and_insert_below = function () {
1637 1637 var cell = this.get_selected_cell();
1638 1638 var cell_index = this.find_cell_index(cell);
1639 1639
1640 1640 cell.execute();
1641 1641
1642 1642 // If we are at the end always insert a new cell and return
1643 1643 if (cell_index === (this.ncells()-1)) {
1644 1644 this.command_mode();
1645 1645 this.insert_cell_below();
1646 1646 this.select(cell_index+1);
1647 1647 this.edit_mode();
1648 1648 this.scroll_to_bottom();
1649 1649 this.set_dirty(true);
1650 1650 return;
1651 1651 }
1652 1652
1653 1653 this.command_mode();
1654 1654 this.insert_cell_below();
1655 1655 this.select(cell_index+1);
1656 1656 this.edit_mode();
1657 1657 this.set_dirty(true);
1658 1658 };
1659 1659
1660 1660 /**
1661 1661 * Execute or render cell outputs and select the next cell.
1662 1662 *
1663 1663 * @method execute_cell_and_select_below
1664 1664 */
1665 1665 Notebook.prototype.execute_cell_and_select_below = function () {
1666 1666
1667 1667 var cell = this.get_selected_cell();
1668 1668 var cell_index = this.find_cell_index(cell);
1669 1669
1670 1670 cell.execute();
1671 1671
1672 1672 // If we are at the end always insert a new cell and return
1673 1673 if (cell_index === (this.ncells()-1)) {
1674 1674 this.command_mode();
1675 1675 this.insert_cell_below();
1676 1676 this.select(cell_index+1);
1677 1677 this.edit_mode();
1678 1678 this.scroll_to_bottom();
1679 1679 this.set_dirty(true);
1680 1680 return;
1681 1681 }
1682 1682
1683 1683 this.command_mode();
1684 1684 this.select(cell_index+1);
1685 1685 this.focus_cell();
1686 1686 this.set_dirty(true);
1687 1687 };
1688 1688
1689 1689 /**
1690 1690 * Execute all cells below the selected cell.
1691 1691 *
1692 1692 * @method execute_cells_below
1693 1693 */
1694 1694 Notebook.prototype.execute_cells_below = function () {
1695 1695 this.execute_cell_range(this.get_selected_index(), this.ncells());
1696 1696 this.scroll_to_bottom();
1697 1697 };
1698 1698
1699 1699 /**
1700 1700 * Execute all cells above the selected cell.
1701 1701 *
1702 1702 * @method execute_cells_above
1703 1703 */
1704 1704 Notebook.prototype.execute_cells_above = function () {
1705 1705 this.execute_cell_range(0, this.get_selected_index());
1706 1706 };
1707 1707
1708 1708 /**
1709 1709 * Execute all cells.
1710 1710 *
1711 1711 * @method execute_all_cells
1712 1712 */
1713 1713 Notebook.prototype.execute_all_cells = function () {
1714 1714 this.execute_cell_range(0, this.ncells());
1715 1715 this.scroll_to_bottom();
1716 1716 };
1717 1717
1718 1718 /**
1719 1719 * Execute a contiguous range of cells.
1720 1720 *
1721 1721 * @method execute_cell_range
1722 1722 * @param {Number} start Index of the first cell to execute (inclusive)
1723 1723 * @param {Number} end Index of the last cell to execute (exclusive)
1724 1724 */
1725 1725 Notebook.prototype.execute_cell_range = function (start, end) {
1726 1726 this.command_mode();
1727 1727 for (var i=start; i<end; i++) {
1728 1728 this.select(i);
1729 1729 this.execute_cell();
1730 1730 }
1731 1731 };
1732 1732
1733 1733 // Persistance and loading
1734 1734
1735 1735 /**
1736 1736 * Getter method for this notebook's name.
1737 1737 *
1738 1738 * @method get_notebook_name
1739 1739 * @return {String} This notebook's name (excluding file extension)
1740 1740 */
1741 1741 Notebook.prototype.get_notebook_name = function () {
1742 1742 var nbname = this.notebook_name.substring(0,this.notebook_name.length-6);
1743 1743 return nbname;
1744 1744 };
1745 1745
1746 1746 /**
1747 1747 * Setter method for this notebook's name.
1748 1748 *
1749 1749 * @method set_notebook_name
1750 1750 * @param {String} name A new name for this notebook
1751 1751 */
1752 1752 Notebook.prototype.set_notebook_name = function (name) {
1753 1753 var parent = utils.url_path_split(this.notebook_path)[0];
1754 1754 this.notebook_name = name;
1755 1755 this.notebook_path = utils.url_path_join(parent, name);
1756 1756 };
1757 1757
1758 1758 /**
1759 1759 * Check that a notebook's name is valid.
1760 1760 *
1761 1761 * @method test_notebook_name
1762 1762 * @param {String} nbname A name for this notebook
1763 1763 * @return {Boolean} True if the name is valid, false if invalid
1764 1764 */
1765 1765 Notebook.prototype.test_notebook_name = function (nbname) {
1766 1766 nbname = nbname || '';
1767 1767 if (nbname.length>0 && !this.notebook_name_blacklist_re.test(nbname)) {
1768 1768 return true;
1769 1769 } else {
1770 1770 return false;
1771 1771 }
1772 1772 };
1773 1773
1774 1774 /**
1775 1775 * Load a notebook from JSON (.ipynb).
1776 1776 *
1777 1777 * @method fromJSON
1778 1778 * @param {Object} data JSON representation of a notebook
1779 1779 */
1780 1780 Notebook.prototype.fromJSON = function (data) {
1781 1781
1782 1782 var content = data.content;
1783 1783 var ncells = this.ncells();
1784 1784 var i;
1785 1785 for (i=0; i<ncells; i++) {
1786 1786 // Always delete cell 0 as they get renumbered as they are deleted.
1787 1787 this.delete_cell(0);
1788 1788 }
1789 1789 // Save the metadata and name.
1790 1790 this.metadata = content.metadata;
1791 1791 this.notebook_name = data.name;
1792 1792 this.notebook_path = data.path;
1793 1793 var trusted = true;
1794 1794
1795 1795 // Trigger an event changing the kernel spec - this will set the default
1796 1796 // codemirror mode
1797 1797 if (this.metadata.kernelspec !== undefined) {
1798 1798 this.events.trigger('spec_changed.Kernel', this.metadata.kernelspec);
1799 1799 }
1800 1800
1801 1801 // Set the codemirror mode from language_info metadata
1802 1802 if (this.metadata.language_info !== undefined) {
1803 1803 var langinfo = this.metadata.language_info;
1804 1804 // Mode 'null' should be plain, unhighlighted text.
1805 1805 var cm_mode = langinfo.codemirror_mode || langinfo.language || 'null';
1806 1806 this.set_codemirror_mode(cm_mode);
1807 1807 }
1808 1808
1809 1809 var new_cells = content.cells;
1810 1810 ncells = new_cells.length;
1811 1811 var cell_data = null;
1812 1812 var new_cell = null;
1813 1813 for (i=0; i<ncells; i++) {
1814 1814 cell_data = new_cells[i];
1815 1815 new_cell = this.insert_cell_at_index(cell_data.cell_type, i);
1816 1816 new_cell.fromJSON(cell_data);
1817 1817 if (new_cell.cell_type == 'code' && !new_cell.output_area.trusted) {
1818 1818 trusted = false;
1819 1819 }
1820 1820 }
1821 1821 if (trusted !== this.trusted) {
1822 1822 this.trusted = trusted;
1823 1823 this.events.trigger("trust_changed.Notebook", trusted);
1824 1824 }
1825 1825 };
1826 1826
1827 1827 /**
1828 1828 * Dump this notebook into a JSON-friendly object.
1829 1829 *
1830 1830 * @method toJSON
1831 1831 * @return {Object} A JSON-friendly representation of this notebook.
1832 1832 */
1833 1833 Notebook.prototype.toJSON = function () {
1834 1834 // remove the conversion indicator, which only belongs in-memory
1835 1835 delete this.metadata.orig_nbformat;
1836 1836 delete this.metadata.orig_nbformat_minor;
1837 1837
1838 1838 var cells = this.get_cells();
1839 1839 var ncells = cells.length;
1840 1840 var cell_array = new Array(ncells);
1841 1841 var trusted = true;
1842 1842 for (var i=0; i<ncells; i++) {
1843 1843 var cell = cells[i];
1844 1844 if (cell.cell_type == 'code' && !cell.output_area.trusted) {
1845 1845 trusted = false;
1846 1846 }
1847 1847 cell_array[i] = cell.toJSON();
1848 1848 }
1849 1849 var data = {
1850 1850 cells: cell_array,
1851 1851 metadata: this.metadata,
1852 1852 nbformat: this.nbformat,
1853 1853 nbformat_minor: this.nbformat_minor
1854 1854 };
1855 1855 if (trusted != this.trusted) {
1856 1856 this.trusted = trusted;
1857 1857 this.events.trigger("trust_changed.Notebook", trusted);
1858 1858 }
1859 1859 return data;
1860 1860 };
1861 1861
1862 1862 /**
1863 1863 * Start an autosave timer, for periodically saving the notebook.
1864 1864 *
1865 1865 * @method set_autosave_interval
1866 1866 * @param {Integer} interval the autosave interval in milliseconds
1867 1867 */
1868 1868 Notebook.prototype.set_autosave_interval = function (interval) {
1869 1869 var that = this;
1870 1870 // clear previous interval, so we don't get simultaneous timers
1871 1871 if (this.autosave_timer) {
1872 1872 clearInterval(this.autosave_timer);
1873 1873 }
1874 1874
1875 1875 this.autosave_interval = this.minimum_autosave_interval = interval;
1876 1876 if (interval) {
1877 1877 this.autosave_timer = setInterval(function() {
1878 1878 if (that.dirty) {
1879 1879 that.save_notebook();
1880 1880 }
1881 1881 }, interval);
1882 1882 this.events.trigger("autosave_enabled.Notebook", interval);
1883 1883 } else {
1884 1884 this.autosave_timer = null;
1885 1885 this.events.trigger("autosave_disabled.Notebook");
1886 1886 }
1887 1887 };
1888 1888
1889 1889 /**
1890 1890 * Save this notebook on the server. This becomes a notebook instance's
1891 1891 * .save_notebook method *after* the entire notebook has been loaded.
1892 1892 *
1893 1893 * @method save_notebook
1894 1894 */
1895 1895 Notebook.prototype.save_notebook = function () {
1896 1896 // Create a JSON model to be sent to the server.
1897 1897 var model = {
1898 1898 type : "notebook",
1899 1899 content : this.toJSON()
1900 1900 };
1901 1901 // time the ajax call for autosave tuning purposes.
1902 1902 var start = new Date().getTime();
1903 1903
1904 1904 var that = this;
1905 this.contents.save(this.notebook_path, model, {
1906 success: $.proxy(this.save_notebook_success, this, start),
1907 error: function (error) {
1905 this.contents.save(this.notebook_path, model).then(
1906 $.proxy(this.save_notebook_success, this, start),
1907 function (error) {
1908 1908 that.events.trigger('notebook_save_failed.Notebook', error);
1909 1909 }
1910 });
1910 );
1911 1911 };
1912 1912
1913 1913 /**
1914 1914 * Success callback for saving a notebook.
1915 1915 *
1916 1916 * @method save_notebook_success
1917 1917 * @param {Integer} start Time when the save request start
1918 1918 * @param {Object} data JSON representation of a notebook
1919 1919 */
1920 1920 Notebook.prototype.save_notebook_success = function (start, data) {
1921 1921 this.set_dirty(false);
1922 1922 if (data.message) {
1923 1923 // save succeeded, but validation failed.
1924 1924 var body = $("<div>");
1925 1925 var title = "Notebook validation failed";
1926 1926
1927 1927 body.append($("<p>").text(
1928 1928 "The save operation succeeded," +
1929 1929 " but the notebook does not appear to be valid." +
1930 1930 " The validation error was:"
1931 1931 )).append($("<div>").addClass("validation-error").append(
1932 1932 $("<pre>").text(data.message)
1933 1933 ));
1934 1934 dialog.modal({
1935 1935 notebook: this,
1936 1936 keyboard_manager: this.keyboard_manager,
1937 1937 title: title,
1938 1938 body: body,
1939 1939 buttons : {
1940 1940 OK : {
1941 1941 "class" : "btn-primary"
1942 1942 }
1943 1943 }
1944 1944 });
1945 1945 }
1946 1946 this.events.trigger('notebook_saved.Notebook');
1947 1947 this._update_autosave_interval(start);
1948 1948 if (this._checkpoint_after_save) {
1949 1949 this.create_checkpoint();
1950 1950 this._checkpoint_after_save = false;
1951 1951 }
1952 1952 };
1953 1953
1954 1954 /**
1955 1955 * update the autosave interval based on how long the last save took
1956 1956 *
1957 1957 * @method _update_autosave_interval
1958 1958 * @param {Integer} timestamp when the save request started
1959 1959 */
1960 1960 Notebook.prototype._update_autosave_interval = function (start) {
1961 1961 var duration = (new Date().getTime() - start);
1962 1962 if (this.autosave_interval) {
1963 1963 // new save interval: higher of 10x save duration or parameter (default 30 seconds)
1964 1964 var interval = Math.max(10 * duration, this.minimum_autosave_interval);
1965 1965 // round to 10 seconds, otherwise we will be setting a new interval too often
1966 1966 interval = 10000 * Math.round(interval / 10000);
1967 1967 // set new interval, if it's changed
1968 1968 if (interval != this.autosave_interval) {
1969 1969 this.set_autosave_interval(interval);
1970 1970 }
1971 1971 }
1972 1972 };
1973 1973
1974 1974 /**
1975 1975 * Explicitly trust the output of this notebook.
1976 1976 *
1977 1977 * @method trust_notebook
1978 1978 */
1979 1979 Notebook.prototype.trust_notebook = function () {
1980 1980 var body = $("<div>").append($("<p>")
1981 1981 .text("A trusted IPython notebook may execute hidden malicious code ")
1982 1982 .append($("<strong>")
1983 1983 .append(
1984 1984 $("<em>").text("when you open it")
1985 1985 )
1986 1986 ).append(".").append(
1987 1987 " Selecting trust will immediately reload this notebook in a trusted state."
1988 1988 ).append(
1989 1989 " For more information, see the "
1990 1990 ).append($("<a>").attr("href", "http://ipython.org/ipython-doc/2/notebook/security.html")
1991 1991 .text("IPython security documentation")
1992 1992 ).append(".")
1993 1993 );
1994 1994
1995 1995 var nb = this;
1996 1996 dialog.modal({
1997 1997 notebook: this,
1998 1998 keyboard_manager: this.keyboard_manager,
1999 1999 title: "Trust this notebook?",
2000 2000 body: body,
2001 2001
2002 2002 buttons: {
2003 2003 Cancel : {},
2004 2004 Trust : {
2005 2005 class : "btn-danger",
2006 2006 click : function () {
2007 2007 var cells = nb.get_cells();
2008 2008 for (var i = 0; i < cells.length; i++) {
2009 2009 var cell = cells[i];
2010 2010 if (cell.cell_type == 'code') {
2011 2011 cell.output_area.trusted = true;
2012 2012 }
2013 2013 }
2014 2014 nb.events.on('notebook_saved.Notebook', function () {
2015 2015 window.location.reload();
2016 2016 });
2017 2017 nb.save_notebook();
2018 2018 }
2019 2019 }
2020 2020 }
2021 2021 });
2022 2022 };
2023 2023
2024 2024 Notebook.prototype.copy_notebook = function(){
2025 2025 var base_url = this.base_url;
2026 2026 var w = window.open();
2027 2027 var parent = utils.url_path_split(this.notebook_path)[0];
2028 this.contents.copy(this.notebook_path, parent, {
2029 success: function (data) {
2028 this.contents.copy(this.notebook_path, parent).then(
2029 function (data) {
2030 2030 w.location = utils.url_join_encode(
2031 2031 base_url, 'notebooks', data.path
2032 2032 );
2033 2033 },
2034 error : function(error) {
2034 function(error) {
2035 2035 w.close();
2036 2036 console.log(error);
2037 },
2038 });
2037 }
2038 );
2039 2039 };
2040 2040
2041 2041 Notebook.prototype.rename = function (new_name) {
2042 2042 if (!new_name.match(/\.ipynb$/)) {
2043 2043 new_name = new_name + ".ipynb";
2044 2044 }
2045 2045
2046 2046 var that = this;
2047 2047 var parent = utils.url_path_split(this.notebook_path)[0];
2048 2048 var new_path = utils.url_path_join(parent, new_name);
2049 this.contents.rename(this.notebook_path, new_path, {
2050 success: function (json) {
2049 this.contents.rename(this.notebook_path, new_path).then(
2050 function (json) {
2051 2051 that.notebook_name = json.name;
2052 2052 that.notebook_path = json.path;
2053 2053 that.session.rename_notebook(json.path);
2054 2054 that.events.trigger('notebook_renamed.Notebook', json);
2055 2055 },
2056 error: $.proxy(this.rename_error, this)
2057 });
2056 $.proxy(this.rename_error, this)
2057 );
2058 2058 };
2059 2059
2060 2060 Notebook.prototype.delete = function () {
2061 2061 this.contents.delete(this.notebook_path);
2062 2062 };
2063 2063
2064 2064 Notebook.prototype.rename_error = function (error) {
2065 2065 var that = this;
2066 2066 var dialog_body = $('<div/>').append(
2067 2067 $("<p/>").text('This notebook name already exists.')
2068 2068 );
2069 2069 this.events.trigger('notebook_rename_failed.Notebook', error);
2070 2070 dialog.modal({
2071 2071 notebook: this,
2072 2072 keyboard_manager: this.keyboard_manager,
2073 2073 title: "Notebook Rename Error!",
2074 2074 body: dialog_body,
2075 2075 buttons : {
2076 2076 "Cancel": {},
2077 2077 "OK": {
2078 2078 class: "btn-primary",
2079 2079 click: function () {
2080 2080 that.save_widget.rename_notebook({notebook:that});
2081 2081 }}
2082 2082 },
2083 2083 open : function (event, ui) {
2084 2084 var that = $(this);
2085 2085 // Upon ENTER, click the OK button.
2086 2086 that.find('input[type="text"]').keydown(function (event, ui) {
2087 2087 if (event.which === this.keyboard.keycodes.enter) {
2088 2088 that.find('.btn-primary').first().click();
2089 2089 }
2090 2090 });
2091 2091 that.find('input[type="text"]').focus();
2092 2092 }
2093 2093 });
2094 2094 };
2095 2095
2096 2096 /**
2097 2097 * Request a notebook's data from the server.
2098 2098 *
2099 2099 * @method load_notebook
2100 2100 * @param {String} notebook_path A notebook to load
2101 2101 */
2102 2102 Notebook.prototype.load_notebook = function (notebook_path) {
2103 2103 this.notebook_path = notebook_path;
2104 2104 this.notebook_name = utils.url_path_split(this.notebook_path)[1];
2105 2105 this.events.trigger('notebook_loading.Notebook');
2106 2106 this.contents.get(notebook_path, {type: 'notebook'}).then(
2107 2107 $.proxy(this.load_notebook_success, this),
2108 2108 $.proxy(this.load_notebook_error, this)
2109 2109 );
2110 2110 };
2111 2111
2112 2112 /**
2113 2113 * Success callback for loading a notebook from the server.
2114 2114 *
2115 2115 * Load notebook data from the JSON response.
2116 2116 *
2117 2117 * @method load_notebook_success
2118 2118 * @param {Object} data JSON representation of a notebook
2119 2119 */
2120 2120 Notebook.prototype.load_notebook_success = function (data) {
2121 2121 var failed, msg;
2122 2122 try {
2123 2123 this.fromJSON(data);
2124 2124 } catch (e) {
2125 2125 failed = e;
2126 2126 console.log("Notebook failed to load from JSON:", e);
2127 2127 }
2128 2128 if (failed || data.message) {
2129 2129 // *either* fromJSON failed or validation failed
2130 2130 var body = $("<div>");
2131 2131 var title;
2132 2132 if (failed) {
2133 2133 title = "Notebook failed to load";
2134 2134 body.append($("<p>").text(
2135 2135 "The error was: "
2136 2136 )).append($("<div>").addClass("js-error").text(
2137 2137 failed.toString()
2138 2138 )).append($("<p>").text(
2139 2139 "See the error console for details."
2140 2140 ));
2141 2141 } else {
2142 2142 title = "Notebook validation failed";
2143 2143 }
2144 2144
2145 2145 if (data.message) {
2146 2146 if (failed) {
2147 2147 msg = "The notebook also failed validation:";
2148 2148 } else {
2149 2149 msg = "An invalid notebook may not function properly." +
2150 2150 " The validation error was:";
2151 2151 }
2152 2152 body.append($("<p>").text(
2153 2153 msg
2154 2154 )).append($("<div>").addClass("validation-error").append(
2155 2155 $("<pre>").text(data.message)
2156 2156 ));
2157 2157 }
2158 2158
2159 2159 dialog.modal({
2160 2160 notebook: this,
2161 2161 keyboard_manager: this.keyboard_manager,
2162 2162 title: title,
2163 2163 body: body,
2164 2164 buttons : {
2165 2165 OK : {
2166 2166 "class" : "btn-primary"
2167 2167 }
2168 2168 }
2169 2169 });
2170 2170 }
2171 2171 if (this.ncells() === 0) {
2172 2172 this.insert_cell_below('code');
2173 2173 this.edit_mode(0);
2174 2174 } else {
2175 2175 this.select(0);
2176 2176 this.handle_command_mode(this.get_cell(0));
2177 2177 }
2178 2178 this.set_dirty(false);
2179 2179 this.scroll_to_top();
2180 2180 var nbmodel = data.content;
2181 2181 var orig_nbformat = nbmodel.metadata.orig_nbformat;
2182 2182 var orig_nbformat_minor = nbmodel.metadata.orig_nbformat_minor;
2183 2183 if (orig_nbformat !== undefined && nbmodel.nbformat !== orig_nbformat) {
2184 2184 var src;
2185 2185 if (nbmodel.nbformat > orig_nbformat) {
2186 2186 src = " an older notebook format ";
2187 2187 } else {
2188 2188 src = " a newer notebook format ";
2189 2189 }
2190 2190
2191 2191 msg = "This notebook has been converted from" + src +
2192 2192 "(v"+orig_nbformat+") to the current notebook " +
2193 2193 "format (v"+nbmodel.nbformat+"). The next time you save this notebook, the " +
2194 2194 "current notebook format will be used.";
2195 2195
2196 2196 if (nbmodel.nbformat > orig_nbformat) {
2197 2197 msg += " Older versions of IPython may not be able to read the new format.";
2198 2198 } else {
2199 2199 msg += " Some features of the original notebook may not be available.";
2200 2200 }
2201 2201 msg += " To preserve the original version, close the " +
2202 2202 "notebook without saving it.";
2203 2203 dialog.modal({
2204 2204 notebook: this,
2205 2205 keyboard_manager: this.keyboard_manager,
2206 2206 title : "Notebook converted",
2207 2207 body : msg,
2208 2208 buttons : {
2209 2209 OK : {
2210 2210 class : "btn-primary"
2211 2211 }
2212 2212 }
2213 2213 });
2214 2214 } else if (orig_nbformat_minor !== undefined && nbmodel.nbformat_minor < orig_nbformat_minor) {
2215 2215 var that = this;
2216 2216 var orig_vs = 'v' + nbmodel.nbformat + '.' + orig_nbformat_minor;
2217 2217 var this_vs = 'v' + nbmodel.nbformat + '.' + this.nbformat_minor;
2218 2218 msg = "This notebook is version " + orig_vs + ", but we only fully support up to " +
2219 2219 this_vs + ". You can still work with this notebook, but some features " +
2220 2220 "introduced in later notebook versions may not be available.";
2221 2221
2222 2222 dialog.modal({
2223 2223 notebook: this,
2224 2224 keyboard_manager: this.keyboard_manager,
2225 2225 title : "Newer Notebook",
2226 2226 body : msg,
2227 2227 buttons : {
2228 2228 OK : {
2229 2229 class : "btn-danger"
2230 2230 }
2231 2231 }
2232 2232 });
2233 2233
2234 2234 }
2235 2235
2236 2236 // Create the session after the notebook is completely loaded to prevent
2237 2237 // code execution upon loading, which is a security risk.
2238 2238 if (this.session === null) {
2239 2239 var kernelspec = this.metadata.kernelspec || {};
2240 2240 var kernel_name = kernelspec.name;
2241 2241
2242 2242 this.start_session(kernel_name);
2243 2243 }
2244 2244 // load our checkpoint list
2245 2245 this.list_checkpoints();
2246 2246
2247 2247 // load toolbar state
2248 2248 if (this.metadata.celltoolbar) {
2249 2249 celltoolbar.CellToolbar.global_show();
2250 2250 celltoolbar.CellToolbar.activate_preset(this.metadata.celltoolbar);
2251 2251 } else {
2252 2252 celltoolbar.CellToolbar.global_hide();
2253 2253 }
2254 2254
2255 2255 // now that we're fully loaded, it is safe to restore save functionality
2256 2256 delete(this.save_notebook);
2257 2257 this.events.trigger('notebook_loaded.Notebook');
2258 2258 };
2259 2259
2260 2260 /**
2261 2261 * Failure callback for loading a notebook from the server.
2262 2262 *
2263 2263 * @method load_notebook_error
2264 2264 * @param {Error} error
2265 2265 */
2266 2266 Notebook.prototype.load_notebook_error = function (error) {
2267 2267 this.events.trigger('notebook_load_failed.Notebook', error);
2268 2268 var msg;
2269 2269 if (error.name === utils.XHR_ERROR && error.xhr.status === 500) {
2270 2270 utils.log_ajax_error(error.xhr, error.xhr_status, error.xhr_error);
2271 2271 msg = "An unknown error occurred while loading this notebook. " +
2272 2272 "This version can load notebook formats " +
2273 2273 "v" + this.nbformat + " or earlier. See the server log for details.";
2274 2274 } else {
2275 2275 msg = error.message;
2276 2276 }
2277 2277 dialog.modal({
2278 2278 notebook: this,
2279 2279 keyboard_manager: this.keyboard_manager,
2280 2280 title: "Error loading notebook",
2281 2281 body : msg,
2282 2282 buttons : {
2283 2283 "OK": {}
2284 2284 }
2285 2285 });
2286 2286 };
2287 2287
2288 2288 /********************* checkpoint-related *********************/
2289 2289
2290 2290 /**
2291 2291 * Save the notebook then immediately create a checkpoint.
2292 2292 *
2293 2293 * @method save_checkpoint
2294 2294 */
2295 2295 Notebook.prototype.save_checkpoint = function () {
2296 2296 this._checkpoint_after_save = true;
2297 2297 this.save_notebook();
2298 2298 };
2299 2299
2300 2300 /**
2301 2301 * Add a checkpoint for this notebook.
2302 2302 * for use as a callback from checkpoint creation.
2303 2303 *
2304 2304 * @method add_checkpoint
2305 2305 */
2306 2306 Notebook.prototype.add_checkpoint = function (checkpoint) {
2307 2307 var found = false;
2308 2308 for (var i = 0; i < this.checkpoints.length; i++) {
2309 2309 var existing = this.checkpoints[i];
2310 2310 if (existing.id == checkpoint.id) {
2311 2311 found = true;
2312 2312 this.checkpoints[i] = checkpoint;
2313 2313 break;
2314 2314 }
2315 2315 }
2316 2316 if (!found) {
2317 2317 this.checkpoints.push(checkpoint);
2318 2318 }
2319 2319 this.last_checkpoint = this.checkpoints[this.checkpoints.length - 1];
2320 2320 };
2321 2321
2322 2322 /**
2323 2323 * List checkpoints for this notebook.
2324 2324 *
2325 2325 * @method list_checkpoints
2326 2326 */
2327 2327 Notebook.prototype.list_checkpoints = function () {
2328 2328 var that = this;
2329 this.contents.list_checkpoints(this.notebook_path, {
2330 success: $.proxy(this.list_checkpoints_success, this),
2331 error: function(error) {
2329 this.contents.list_checkpoints(this.notebook_path).then(
2330 $.proxy(this.list_checkpoints_success, this),
2331 function(error) {
2332 2332 that.events.trigger('list_checkpoints_failed.Notebook', error);
2333 2333 }
2334 });
2334 );
2335 2335 };
2336 2336
2337 2337 /**
2338 2338 * Success callback for listing checkpoints.
2339 2339 *
2340 2340 * @method list_checkpoint_success
2341 2341 * @param {Object} data JSON representation of a checkpoint
2342 2342 */
2343 2343 Notebook.prototype.list_checkpoints_success = function (data) {
2344 2344 data = $.parseJSON(data);
2345 2345 this.checkpoints = data;
2346 2346 if (data.length) {
2347 2347 this.last_checkpoint = data[data.length - 1];
2348 2348 } else {
2349 2349 this.last_checkpoint = null;
2350 2350 }
2351 2351 this.events.trigger('checkpoints_listed.Notebook', [data]);
2352 2352 };
2353 2353
2354 2354 /**
2355 2355 * Create a checkpoint of this notebook on the server from the most recent save.
2356 2356 *
2357 2357 * @method create_checkpoint
2358 2358 */
2359 2359 Notebook.prototype.create_checkpoint = function () {
2360 2360 var that = this;
2361 this.contents.create_checkpoint(this.notebook_path, {
2362 success: $.proxy(this.create_checkpoint_success, this),
2363 error: function (error) {
2361 this.contents.create_checkpoint(this.notebook_path).then(
2362 $.proxy(this.create_checkpoint_success, this),
2363 function (error) {
2364 2364 that.events.trigger('checkpoint_failed.Notebook', error);
2365 2365 }
2366 });
2366 );
2367 2367 };
2368 2368
2369 2369 /**
2370 2370 * Success callback for creating a checkpoint.
2371 2371 *
2372 2372 * @method create_checkpoint_success
2373 2373 * @param {Object} data JSON representation of a checkpoint
2374 2374 */
2375 2375 Notebook.prototype.create_checkpoint_success = function (data) {
2376 2376 data = $.parseJSON(data);
2377 2377 this.add_checkpoint(data);
2378 2378 this.events.trigger('checkpoint_created.Notebook', data);
2379 2379 };
2380 2380
2381 2381 Notebook.prototype.restore_checkpoint_dialog = function (checkpoint) {
2382 2382 var that = this;
2383 2383 checkpoint = checkpoint || this.last_checkpoint;
2384 2384 if ( ! checkpoint ) {
2385 2385 console.log("restore dialog, but no checkpoint to restore to!");
2386 2386 return;
2387 2387 }
2388 2388 var body = $('<div/>').append(
2389 2389 $('<p/>').addClass("p-space").text(
2390 2390 "Are you sure you want to revert the notebook to " +
2391 2391 "the latest checkpoint?"
2392 2392 ).append(
2393 2393 $("<strong/>").text(
2394 2394 " This cannot be undone."
2395 2395 )
2396 2396 )
2397 2397 ).append(
2398 2398 $('<p/>').addClass("p-space").text("The checkpoint was last updated at:")
2399 2399 ).append(
2400 2400 $('<p/>').addClass("p-space").text(
2401 2401 Date(checkpoint.last_modified)
2402 2402 ).css("text-align", "center")
2403 2403 );
2404 2404
2405 2405 dialog.modal({
2406 2406 notebook: this,
2407 2407 keyboard_manager: this.keyboard_manager,
2408 2408 title : "Revert notebook to checkpoint",
2409 2409 body : body,
2410 2410 buttons : {
2411 2411 Revert : {
2412 2412 class : "btn-danger",
2413 2413 click : function () {
2414 2414 that.restore_checkpoint(checkpoint.id);
2415 2415 }
2416 2416 },
2417 2417 Cancel : {}
2418 2418 }
2419 2419 });
2420 2420 };
2421 2421
2422 2422 /**
2423 2423 * Restore the notebook to a checkpoint state.
2424 2424 *
2425 2425 * @method restore_checkpoint
2426 2426 * @param {String} checkpoint ID
2427 2427 */
2428 2428 Notebook.prototype.restore_checkpoint = function (checkpoint) {
2429 2429 this.events.trigger('notebook_restoring.Notebook', checkpoint);
2430 2430 var that = this;
2431 this.contents.restore_checkpoint(this.notebook_path,
2432 checkpoint, {
2433 success: $.proxy(this.restore_checkpoint_success, this),
2434 error: function (error) {
2431 this.contents.restore_checkpoint(this.notebook_path, checkpoint).then(
2432 $.proxy(this.restore_checkpoint_success, this),
2433 function (error) {
2435 2434 that.events.trigger('checkpoint_restore_failed.Notebook', error);
2436 2435 }
2437 });
2436 );
2438 2437 };
2439 2438
2440 2439 /**
2441 2440 * Success callback for restoring a notebook to a checkpoint.
2442 2441 *
2443 2442 * @method restore_checkpoint_success
2444 2443 */
2445 2444 Notebook.prototype.restore_checkpoint_success = function () {
2446 2445 this.events.trigger('checkpoint_restored.Notebook');
2447 2446 this.load_notebook(this.notebook_path);
2448 2447 };
2449 2448
2450 2449 /**
2451 2450 * Delete a notebook checkpoint.
2452 2451 *
2453 2452 * @method delete_checkpoint
2454 2453 * @param {String} checkpoint ID
2455 2454 */
2456 2455 Notebook.prototype.delete_checkpoint = function (checkpoint) {
2457 2456 this.events.trigger('notebook_restoring.Notebook', checkpoint);
2458 2457 var that = this;
2459 this.contents.delete_checkpoint(this.notebook_path,
2460 checkpoint, {
2461 success: $.proxy(this.delete_checkpoint_success, this),
2462 error: function (error) {
2458 this.contents.delete_checkpoint(this.notebook_path, checkpoint).then(
2459 $.proxy(this.delete_checkpoint_success, this),
2460 function (error) {
2463 2461 that.events.trigger('checkpoint_delete_failed.Notebook', error);
2464 2462 }
2465 });
2463 );
2466 2464 };
2467 2465
2468 2466 /**
2469 2467 * Success callback for deleting a notebook checkpoint
2470 2468 *
2471 2469 * @method delete_checkpoint_success
2472 2470 */
2473 2471 Notebook.prototype.delete_checkpoint_success = function () {
2474 2472 this.events.trigger('checkpoint_deleted.Notebook');
2475 2473 this.load_notebook(this.notebook_path);
2476 2474 };
2477 2475
2478 2476
2479 2477 // For backwards compatability.
2480 2478 IPython.Notebook = Notebook;
2481 2479
2482 2480 return {'Notebook': Notebook};
2483 2481 });
@@ -1,255 +1,239 b''
1 1 // Copyright (c) IPython Development Team.
2 2 // Distributed under the terms of the Modified BSD License.
3 3
4 4 define([
5 5 'base/js/namespace',
6 6 'jquery',
7 7 'base/js/utils',
8 8 ], function(IPython, $, utils) {
9 9 var Contents = function(options) {
10 10 // Constructor
11 11 //
12 12 // A contents handles passing file operations
13 13 // to the back-end. This includes checkpointing
14 14 // with the normal file operations.
15 15 //
16 16 // Parameters:
17 17 // options: dictionary
18 18 // Dictionary of keyword arguments.
19 19 // base_url: string
20 20 this.base_url = options.base_url;
21 21 };
22 22
23 23 /** Error type */
24 24 Contents.DIRECTORY_NOT_EMPTY_ERROR = 'DirectoryNotEmptyError';
25 25
26 26 Contents.DirectoryNotEmptyError = function() {
27 27 // Constructor
28 28 //
29 29 // An error representing the result of attempting to delete a non-empty
30 30 // directory.
31 31 this.message = 'A directory must be empty before being deleted.';
32 32 };
33 33
34 34 Contents.DirectoryNotEmptyError.prototype = Object.create(Error.prototype);
35 35 Contents.DirectoryNotEmptyError.prototype.name =
36 36 Contents.DIRECTORY_NOT_EMPTY_ERROR;
37 37
38 38
39 39 Contents.prototype.api_url = function() {
40 40 var url_parts = [this.base_url, 'api/contents'].concat(
41 41 Array.prototype.slice.apply(arguments));
42 42 return utils.url_join_encode.apply(null, url_parts);
43 43 };
44 44
45 45 /**
46 46 * Creates a basic error handler that wraps a jqXHR error as an Error.
47 47 *
48 48 * Takes a callback that accepts an Error, and returns a callback that can
49 49 * be passed directly to $.ajax, which will wrap the error from jQuery
50 50 * as an Error, and pass that to the original callback.
51 51 *
52 52 * @method create_basic_error_handler
53 53 * @param{Function} callback
54 54 * @return{Function}
55 55 */
56 56 Contents.prototype.create_basic_error_handler = function(callback) {
57 57 if (!callback) {
58 58 return utils.log_ajax_error;
59 59 }
60 60 return function(xhr, status, error) {
61 61 callback(utils.wrap_ajax_error(xhr, status, error));
62 62 };
63 63 };
64 64
65 65 /**
66 66 * File Functions (including notebook operations)
67 67 */
68 68
69 69 /**
70 70 * Get a file.
71 71 *
72 72 * Calls success with file JSON model, or error with error.
73 73 *
74 74 * @method get
75 75 * @param {String} path
76 76 * @param {Function} success
77 77 * @param {Function} error
78 78 */
79 79 Contents.prototype.get = function (path, options) {
80 80 // We do the call with settings so we can set cache to false.
81 81 var settings = {
82 82 processData : false,
83 83 cache : false,
84 84 type : "GET",
85 85 dataType : "json",
86 86 };
87 87 var url = this.api_url(path);
88 88 params = {};
89 89 if (options.type) { params.type = options.type; }
90 90 if (options.format) { params.format = options.format; }
91 91 return utils.promising_ajax(url + '?' + $.param(params), settings);
92 92 };
93 93
94 94
95 95 /**
96 96 * Creates a new untitled file or directory in the specified directory path.
97 97 *
98 98 * @method new
99 99 * @param {String} path: the directory in which to create the new file/directory
100 100 * @param {Object} options:
101 101 * ext: file extension to use
102 102 * type: model type to create ('notebook', 'file', or 'directory')
103 103 */
104 104 Contents.prototype.new_untitled = function(path, options) {
105 105 var data = JSON.stringify({
106 106 ext: options.ext,
107 107 type: options.type
108 108 });
109 109
110 110 var settings = {
111 111 processData : false,
112 112 type : "POST",
113 113 data: data,
114 114 dataType : "json",
115 success : options.success || function() {},
116 error : this.create_basic_error_handler(options.error)
117 115 };
118 $.ajax(this.api_url(path), settings);
116 return utils.promising_ajax(this.api_url(path), settings);
119 117 };
120 118
121 Contents.prototype.delete = function(path, options) {
122 var error_callback = options.error || function() {};
119 Contents.prototype.delete = function(path) {
123 120 var settings = {
124 121 processData : false,
125 122 type : "DELETE",
126 123 dataType : "json",
127 success : options.success || function() {},
128 error : function(xhr, status, error) {
124 };
125 var url = this.api_url(path);
126 return utils.promising_ajax(url, settings).catch(
127 // Translate certain errors to more specific ones.
128 function(error) {
129 129 // TODO: update IPEP27 to specify errors more precisely, so
130 130 // that error types can be detected here with certainty.
131 if (xhr.status === 400) {
132 error_callback(new Contents.DirectoryNotEmptyError());
131 if (error.xhr.status === 400) {
132 return Promise.reject(new Contents.DirectoryNotEmptyError());
133 133 }
134 error_callback(utils.wrap_ajax_error(xhr, status, error));
134 return Promise.reject(error);
135 135 }
136 };
137 var url = this.api_url(path);
138 $.ajax(url, settings);
136 );
139 137 };
140 138
141 Contents.prototype.rename = function(path, new_path, options) {
139 Contents.prototype.rename = function(path, new_path) {
142 140 var data = {path: new_path};
143 141 var settings = {
144 142 processData : false,
145 143 type : "PATCH",
146 144 data : JSON.stringify(data),
147 145 dataType: "json",
148 146 contentType: 'application/json',
149 success : options.success || function() {},
150 error : this.create_basic_error_handler(options.error)
151 147 };
152 148 var url = this.api_url(path);
153 $.ajax(url, settings);
149 return utils.promising_ajax(url, settings);
154 150 };
155 151
156 Contents.prototype.save = function(path, model, options) {
152 Contents.prototype.save = function(path, model) {
157 153 // We do the call with settings so we can set cache to false.
158 154 var settings = {
159 155 processData : false,
160 156 type : "PUT",
161 157 data : JSON.stringify(model),
162 158 contentType: 'application/json',
163 success : options.success || function() {},
164 error : this.create_basic_error_handler(options.error)
165 159 };
166 160 var url = this.api_url(path);
167 $.ajax(url, settings);
161 return utils.promising_ajax(url, settings);
168 162 };
169 163
170 Contents.prototype.copy = function(from_file, to_dir, options) {
164 Contents.prototype.copy = function(from_file, to_dir) {
171 165 // Copy a file into a given directory via POST
172 166 // The server will select the name of the copied file
173 167 var url = this.api_url(to_dir);
174 168
175 169 var settings = {
176 170 processData : false,
177 171 type: "POST",
178 172 data: JSON.stringify({copy_from: from_file}),
179 173 dataType : "json",
180 success: options.success || function() {},
181 error: this.create_basic_error_handler(options.error)
182 174 };
183 $.ajax(url, settings);
175 return utils.promising_ajax(url, settings);
184 176 };
185 177
186 178 /**
187 179 * Checkpointing Functions
188 180 */
189 181
190 Contents.prototype.create_checkpoint = function(path, options) {
182 Contents.prototype.create_checkpoint = function(path) {
191 183 var url = this.api_url(path, 'checkpoints');
192 184 var settings = {
193 185 type : "POST",
194 success: options.success || function() {},
195 error : this.create_basic_error_handler(options.error)
196 186 };
197 $.ajax(url, settings);
187 return utils.promising_ajax(url, settings);
198 188 };
199 189
200 Contents.prototype.list_checkpoints = function(path, options) {
190 Contents.prototype.list_checkpoints = function(path) {
201 191 var url = this.api_url(path, 'checkpoints');
202 192 var settings = {
203 193 type : "GET",
204 success: options.success,
205 error : this.create_basic_error_handler(options.error)
206 194 };
207 $.ajax(url, settings);
195 return utils.promising_ajax(url, settings);
208 196 };
209 197
210 Contents.prototype.restore_checkpoint = function(path, checkpoint_id, options) {
198 Contents.prototype.restore_checkpoint = function(path, checkpoint_id) {
211 199 var url = this.api_url(path, 'checkpoints', checkpoint_id);
212 200 var settings = {
213 201 type : "POST",
214 success: options.success || function() {},
215 error : this.create_basic_error_handler(options.error)
216 202 };
217 $.ajax(url, settings);
203 return utils.promising_ajax(url, settings);
218 204 };
219 205
220 Contents.prototype.delete_checkpoint = function(path, checkpoint_id, options) {
206 Contents.prototype.delete_checkpoint = function(path, checkpoint_id) {
221 207 var url = this.api_url(path, 'checkpoints', checkpoint_id);
222 208 var settings = {
223 209 type : "DELETE",
224 success: options.success || function() {},
225 error : this.create_basic_error_handler(options.error)
226 210 };
227 $.ajax(url, settings);
211 return utils.promising_ajax(url, settings);
228 212 };
229 213
230 214 /**
231 215 * File management functions
232 216 */
233 217
234 218 /**
235 219 * List notebooks and directories at a given path
236 220 *
237 221 * On success, load_callback is called with an array of dictionaries
238 222 * representing individual files or directories. Each dictionary has
239 223 * the keys:
240 224 * type: "notebook" or "directory"
241 225 * created: created date
242 226 * last_modified: last modified dat
243 227 * @method list_notebooks
244 228 * @param {String} path The path to list notebooks in
245 229 * @param {Object} options including success and error callbacks
246 230 */
247 231 Contents.prototype.list_contents = function(path) {
248 232 return this.get(path, {type: 'directory'});
249 233 };
250 234
251 235
252 236 IPython.Contents = Contents;
253 237
254 238 return {'Contents': Contents};
255 239 });
@@ -1,147 +1,146 b''
1 1 // Copyright (c) IPython Development Team.
2 2 // Distributed under the terms of the Modified BSD License.
3 3
4 4 require([
5 5 'jquery',
6 6 'base/js/namespace',
7 7 'base/js/dialog',
8 8 'base/js/events',
9 9 'base/js/page',
10 10 'base/js/utils',
11 11 'contents',
12 12 'tree/js/notebooklist',
13 13 'tree/js/clusterlist',
14 14 'tree/js/sessionlist',
15 15 'tree/js/kernellist',
16 16 'tree/js/terminallist',
17 17 'auth/js/loginwidget',
18 18 // only loaded, not used:
19 19 'jqueryui',
20 20 'bootstrap',
21 21 'custom/custom',
22 22 ], function(
23 23 $,
24 24 IPython,
25 25 dialog,
26 26 events,
27 27 page,
28 28 utils,
29 29 contents_service,
30 30 notebooklist,
31 31 clusterlist,
32 32 sesssionlist,
33 33 kernellist,
34 34 terminallist,
35 35 loginwidget){
36 36 "use strict";
37 37
38 38 page = new page.Page();
39 39
40 40 var common_options = {
41 41 base_url: utils.get_body_data("baseUrl"),
42 42 notebook_path: utils.get_body_data("notebookPath"),
43 43 };
44 44 var session_list = new sesssionlist.SesssionList($.extend({
45 45 events: events},
46 46 common_options));
47 47 var contents = new contents_service.Contents($.extend({
48 48 events: events},
49 49 common_options));
50 50 var notebook_list = new notebooklist.NotebookList('#notebook_list', $.extend({
51 51 contents: contents,
52 52 session_list: session_list},
53 53 common_options));
54 54 var cluster_list = new clusterlist.ClusterList('#cluster_list', common_options);
55 55 var kernel_list = new kernellist.KernelList('#running_list', $.extend({
56 56 session_list: session_list},
57 57 common_options));
58 58
59 59 var terminal_list;
60 60 if (utils.get_body_data("terminalsAvailable") === "True") {
61 61 terminal_list = new terminallist.TerminalList('#terminal_list', common_options);
62 62 }
63 63
64 64 var login_widget = new loginwidget.LoginWidget('#login_widget', common_options);
65 65
66 66 $('#new_notebook').click(function (e) {
67 67 var w = window.open();
68 contents.new_untitled(common_options.notebook_path, {
69 type: "notebook",
70 success: function (data) {
68 contents.new_untitled(common_options.notebook_path, {type: "notebook"}).then(
69 function (data) {
71 70 w.location = utils.url_join_encode(
72 71 common_options.base_url, 'notebooks', data.path
73 72 );
74 73 },
75 error: function(error) {
74 function(error) {
76 75 w.close();
77 76 dialog.modal({
78 77 title : 'Creating Notebook Failed',
79 78 body : "The error was: " + error.message,
80 79 buttons : {'OK' : {'class' : 'btn-primary'}}
81 80 });
82 81 }
83 });
82 );
84 83 });
85 84
86 85 var interval_id=0;
87 86 // auto refresh every xx secondes, no need to be fast,
88 87 // update is done at least when page get focus
89 88 var time_refresh = 60; // in sec
90 89
91 90 var enable_autorefresh = function(){
92 91 //refresh immediately , then start interval
93 92 session_list.load_sessions();
94 93 cluster_list.load_list();
95 94 if (!interval_id){
96 95 interval_id = setInterval(function(){
97 96 session_list.load_sessions();
98 97 cluster_list.load_list();
99 98 }, time_refresh*1000);
100 99 }
101 100 };
102 101
103 102 var disable_autorefresh = function(){
104 103 clearInterval(interval_id);
105 104 interval_id = 0;
106 105 };
107 106
108 107 // stop autorefresh when page lose focus
109 108 $(window).blur(function() {
110 109 disable_autorefresh();
111 110 });
112 111
113 112 //re-enable when page get focus back
114 113 $(window).focus(function() {
115 114 enable_autorefresh();
116 115 });
117 116
118 117 // finally start it, it will refresh immediately
119 118 enable_autorefresh();
120 119
121 120 page.show();
122 121
123 122 // For backwards compatability.
124 123 IPython.page = page;
125 124 IPython.notebook_list = notebook_list;
126 125 IPython.cluster_list = cluster_list;
127 126 IPython.session_list = session_list;
128 127 IPython.kernel_list = kernel_list;
129 128 IPython.login_widget = login_widget;
130 129
131 130 events.trigger('app_initialized.DashboardApp');
132 131
133 132 // bound the upload method to the on change of the file select list
134 133 $("#alternate_upload").change(function (event){
135 134 notebook_list.handleFilesUpload(event,'form');
136 135 });
137 136
138 137 // set hash on tab click
139 138 $("#tabs").find("a").click(function() {
140 139 window.location.hash = $(this).attr("href");
141 140 });
142 141
143 142 // load tab if url hash
144 143 if (window.location.hash) {
145 144 $("#tabs").find("a[href=" + window.location.hash + "]").click();
146 145 }
147 146 });
@@ -1,469 +1,467 b''
1 1 // Copyright (c) IPython Development Team.
2 2 // Distributed under the terms of the Modified BSD License.
3 3
4 4 define([
5 5 'base/js/namespace',
6 6 'jquery',
7 7 'base/js/utils',
8 8 'base/js/dialog',
9 9 ], function(IPython, $, utils, dialog) {
10 10 "use strict";
11 11
12 12 var NotebookList = function (selector, options) {
13 13 // Constructor
14 14 //
15 15 // Parameters:
16 16 // selector: string
17 17 // options: dictionary
18 18 // Dictionary of keyword arguments.
19 19 // session_list: SessionList instance
20 20 // element_name: string
21 21 // base_url: string
22 22 // notebook_path: string
23 23 // contents: Contents instance
24 24 var that = this;
25 25 this.session_list = options.session_list;
26 26 // allow code re-use by just changing element_name in kernellist.js
27 27 this.element_name = options.element_name || 'notebook';
28 28 this.selector = selector;
29 29 if (this.selector !== undefined) {
30 30 this.element = $(selector);
31 31 this.style();
32 32 this.bind_events();
33 33 }
34 34 this.notebooks_list = [];
35 35 this.sessions = {};
36 36 this.base_url = options.base_url || utils.get_body_data("baseUrl");
37 37 this.notebook_path = options.notebook_path || utils.get_body_data("notebookPath");
38 38 this.contents = options.contents;
39 39 if (this.session_list && this.session_list.events) {
40 40 this.session_list.events.on('sessions_loaded.Dashboard',
41 41 function(e, d) { that.sessions_loaded(d); });
42 42 }
43 43 };
44 44
45 45 NotebookList.prototype.style = function () {
46 46 var prefix = '#' + this.element_name;
47 47 $(prefix + '_toolbar').addClass('list_toolbar');
48 48 $(prefix + '_list_info').addClass('toolbar_info');
49 49 $(prefix + '_buttons').addClass('toolbar_buttons');
50 50 $(prefix + '_list_header').addClass('list_header');
51 51 this.element.addClass("list_container");
52 52 };
53 53
54 54
55 55 NotebookList.prototype.bind_events = function () {
56 56 var that = this;
57 57 $('#refresh_' + this.element_name + '_list').click(function () {
58 58 that.load_sessions();
59 59 });
60 60 this.element.bind('dragover', function () {
61 61 return false;
62 62 });
63 63 this.element.bind('drop', function(event){
64 64 that.handleFilesUpload(event,'drop');
65 65 return false;
66 66 });
67 67 };
68 68
69 69 NotebookList.prototype.handleFilesUpload = function(event, dropOrForm) {
70 70 var that = this;
71 71 var files;
72 72 if(dropOrForm =='drop'){
73 73 files = event.originalEvent.dataTransfer.files;
74 74 } else
75 75 {
76 76 files = event.originalEvent.target.files;
77 77 }
78 78 for (var i = 0; i < files.length; i++) {
79 79 var f = files[i];
80 80 var name_and_ext = utils.splitext(f.name);
81 81 var file_ext = name_and_ext[1];
82 82
83 83 var reader = new FileReader();
84 84 if (file_ext === '.ipynb') {
85 85 reader.readAsText(f);
86 86 } else {
87 87 // read non-notebook files as binary
88 88 reader.readAsArrayBuffer(f);
89 89 }
90 90 var item = that.new_item(0);
91 91 item.addClass('new-file');
92 92 that.add_name_input(f.name, item, file_ext == '.ipynb' ? 'notebook' : 'file');
93 93 // Store the list item in the reader so we can use it later
94 94 // to know which item it belongs to.
95 95 $(reader).data('item', item);
96 96 reader.onload = function (event) {
97 97 var item = $(event.target).data('item');
98 98 that.add_file_data(event.target.result, item);
99 99 that.add_upload_button(item);
100 100 };
101 101 reader.onerror = function (event) {
102 102 var item = $(event.target).data('item');
103 103 var name = item.data('name');
104 104 item.remove();
105 105 dialog.modal({
106 106 title : 'Failed to read file',
107 107 body : "Failed to read file '" + name + "'",
108 108 buttons : {'OK' : { 'class' : 'btn-primary' }}
109 109 });
110 110 };
111 111 }
112 112 // Replace the file input form wth a clone of itself. This is required to
113 113 // reset the form. Otherwise, if you upload a file, delete it and try to
114 114 // upload it again, the changed event won't fire.
115 115 var form = $('input.fileinput');
116 116 form.replaceWith(form.clone(true));
117 117 return false;
118 118 };
119 119
120 120 NotebookList.prototype.clear_list = function (remove_uploads) {
121 121 // Clears the navigation tree.
122 122 //
123 123 // Parameters
124 124 // remove_uploads: bool=False
125 125 // Should upload prompts also be removed from the tree.
126 126 if (remove_uploads) {
127 127 this.element.children('.list_item').remove();
128 128 } else {
129 129 this.element.children('.list_item:not(.new-file)').remove();
130 130 }
131 131 };
132 132
133 133 NotebookList.prototype.load_sessions = function(){
134 134 this.session_list.load_sessions();
135 135 };
136 136
137 137
138 138 NotebookList.prototype.sessions_loaded = function(data){
139 139 this.sessions = data;
140 140 this.load_list();
141 141 };
142 142
143 143 NotebookList.prototype.load_list = function () {
144 144 var that = this;
145 145 this.contents.list_contents(that.notebook_path).then(
146 146 $.proxy(this.draw_notebook_list, this),
147 147 function(error) {
148 148 that.draw_notebook_list({content: []}, "Server error: " + error.message);
149 149 }
150 150 );
151 151 };
152 152
153 153 /**
154 154 * Draw the list of notebooks
155 155 * @method draw_notebook_list
156 156 * @param {Array} list An array of dictionaries representing files or
157 157 * directories.
158 158 * @param {String} error_msg An error message
159 159 */
160 160 NotebookList.prototype.draw_notebook_list = function (list, error_msg) {
161 161 var message = error_msg || 'Notebook list empty.';
162 162 var item = null;
163 163 var model = null;
164 164 var len = list.content.length;
165 165 this.clear_list();
166 166 var n_uploads = this.element.children('.list_item').length;
167 167 if (len === 0) {
168 168 item = this.new_item(0);
169 169 var span12 = item.children().first();
170 170 span12.empty();
171 171 span12.append($('<div style="margin:auto;text-align:center;color:grey"/>').text(message));
172 172 }
173 173 var path = this.notebook_path;
174 174 var offset = n_uploads;
175 175 if (path !== '') {
176 176 item = this.new_item(offset);
177 177 model = {
178 178 type: 'directory',
179 179 name: '..',
180 180 path: utils.url_path_split(path)[0],
181 181 };
182 182 this.add_link(model, item);
183 183 offset += 1;
184 184 }
185 185 for (var i=0; i<len; i++) {
186 186 model = list.content[i];
187 187 item = this.new_item(i+offset);
188 188 this.add_link(model, item);
189 189 }
190 190 };
191 191
192 192
193 193 NotebookList.prototype.new_item = function (index) {
194 194 var item = $('<div/>').addClass("list_item").addClass("row");
195 195 // item.addClass('list_item ui-widget ui-widget-content ui-helper-clearfix');
196 196 // item.css('border-top-style','none');
197 197 item.append($("<div/>").addClass("col-md-12").append(
198 198 $('<i/>').addClass('item_icon')
199 199 ).append(
200 200 $("<a/>").addClass("item_link").append(
201 201 $("<span/>").addClass("item_name")
202 202 )
203 203 ).append(
204 204 $('<div/>').addClass("item_buttons btn-group pull-right")
205 205 ));
206 206
207 207 if (index === -1) {
208 208 this.element.append(item);
209 209 } else {
210 210 this.element.children().eq(index).after(item);
211 211 }
212 212 return item;
213 213 };
214 214
215 215
216 216 NotebookList.icons = {
217 217 directory: 'folder_icon',
218 218 notebook: 'notebook_icon',
219 219 file: 'file_icon',
220 220 };
221 221
222 222 NotebookList.uri_prefixes = {
223 223 directory: 'tree',
224 224 notebook: 'notebooks',
225 225 file: 'files',
226 226 };
227 227
228 228
229 229 NotebookList.prototype.add_link = function (model, item) {
230 230 var path = model.path,
231 231 name = model.name;
232 232 item.data('name', name);
233 233 item.data('path', path);
234 234 item.find(".item_name").text(name);
235 235 var icon = NotebookList.icons[model.type];
236 236 var uri_prefix = NotebookList.uri_prefixes[model.type];
237 237 item.find(".item_icon").addClass(icon).addClass('icon-fixed-width');
238 238 var link = item.find("a.item_link")
239 239 .attr('href',
240 240 utils.url_join_encode(
241 241 this.base_url,
242 242 uri_prefix,
243 243 path
244 244 )
245 245 );
246 246 // directory nav doesn't open new tabs
247 247 // files, notebooks do
248 248 if (model.type !== "directory") {
249 249 link.attr('target','_blank');
250 250 }
251 251 var path_name = utils.url_path_join(path, name);
252 252 if (model.type == 'file') {
253 253 this.add_delete_button(item);
254 254 } else if (model.type == 'notebook') {
255 255 if(this.sessions[path_name] === undefined){
256 256 this.add_delete_button(item);
257 257 } else {
258 258 this.add_shutdown_button(item, this.sessions[path_name]);
259 259 }
260 260 }
261 261 };
262 262
263 263
264 264 NotebookList.prototype.add_name_input = function (name, item, icon_type) {
265 265 item.data('name', name);
266 266 item.find(".item_icon").addClass(NotebookList.icons[icon_type]).addClass('icon-fixed-width');
267 267 item.find(".item_name").empty().append(
268 268 $('<input/>')
269 269 .addClass("filename_input")
270 270 .attr('value', name)
271 271 .attr('size', '30')
272 272 .attr('type', 'text')
273 273 .keyup(function(event){
274 274 if(event.keyCode == 13){item.find('.upload_button').click();}
275 275 else if(event.keyCode == 27){item.remove();}
276 276 })
277 277 );
278 278 };
279 279
280 280
281 281 NotebookList.prototype.add_file_data = function (data, item) {
282 282 item.data('filedata', data);
283 283 };
284 284
285 285
286 286 NotebookList.prototype.add_shutdown_button = function (item, session) {
287 287 var that = this;
288 288 var shutdown_button = $("<button/>").text("Shutdown").addClass("btn btn-xs btn-danger").
289 289 click(function (e) {
290 290 var settings = {
291 291 processData : false,
292 292 cache : false,
293 293 type : "DELETE",
294 294 dataType : "json",
295 295 success : function () {
296 296 that.load_sessions();
297 297 },
298 298 error : utils.log_ajax_error,
299 299 };
300 300 var url = utils.url_join_encode(
301 301 that.base_url,
302 302 'api/sessions',
303 303 session
304 304 );
305 305 $.ajax(url, settings);
306 306 return false;
307 307 });
308 308 // var new_buttons = item.find('a'); // shutdown_button;
309 309 item.find(".item_buttons").text("").append(shutdown_button);
310 310 };
311 311
312 312 NotebookList.prototype.add_delete_button = function (item) {
313 313 var notebooklist = this;
314 314 var delete_button = $("<button/>").text("Delete").addClass("btn btn-default btn-xs").
315 315 click(function (e) {
316 316 // $(this) is the button that was clicked.
317 317 var that = $(this);
318 318 // We use the filename from the parent list_item element's
319 319 // data because the outer scope's values change as we iterate through the loop.
320 320 var parent_item = that.parents('div.list_item');
321 321 var name = parent_item.data('name');
322 322 var path = parent_item.data('path');
323 323 var message = 'Are you sure you want to permanently delete the file: ' + name + '?';
324 324 dialog.modal({
325 325 title : "Delete file",
326 326 body : message,
327 327 buttons : {
328 328 Delete : {
329 329 class: "btn-danger",
330 330 click: function() {
331 notebooklist.contents.delete(path, {
332 success: function() {
331 notebooklist.contents.delete(path).then(
332 function() {
333 333 notebooklist.notebook_deleted(path);
334 334 }
335 });
335 );
336 336 }
337 337 },
338 338 Cancel : {}
339 339 }
340 340 });
341 341 return false;
342 342 });
343 343 item.find(".item_buttons").text("").append(delete_button);
344 344 };
345 345
346 346 NotebookList.prototype.notebook_deleted = function(path) {
347 347 // Remove the deleted notebook.
348 348 $( ":data(path)" ).each(function() {
349 349 var element = $(this);
350 350 if (element.data("path") == path) {
351 351 element.remove();
352 352 }
353 353 });
354 354 };
355 355
356 356
357 357 NotebookList.prototype.add_upload_button = function (item) {
358 358 var that = this;
359 359 var upload_button = $('<button/>').text("Upload")
360 360 .addClass('btn btn-primary btn-xs upload_button')
361 361 .click(function (e) {
362 362 var filename = item.find('.item_name > input').val();
363 363 var path = utils.url_path_join(that.notebook_path, filename);
364 364 var filedata = item.data('filedata');
365 365 var format = 'text';
366 366 if (filename.length === 0 || filename[0] === '.') {
367 367 dialog.modal({
368 368 title : 'Invalid file name',
369 369 body : "File names must be at least one character and not start with a dot",
370 370 buttons : {'OK' : { 'class' : 'btn-primary' }}
371 371 });
372 372 return false;
373 373 }
374 374 if (filedata instanceof ArrayBuffer) {
375 375 // base64-encode binary file data
376 376 var bytes = '';
377 377 var buf = new Uint8Array(filedata);
378 378 var nbytes = buf.byteLength;
379 379 for (var i=0; i<nbytes; i++) {
380 380 bytes += String.fromCharCode(buf[i]);
381 381 }
382 382 filedata = btoa(bytes);
383 383 format = 'base64';
384 384 }
385 385 var model = {};
386 386
387 387 var name_and_ext = utils.splitext(filename);
388 388 var file_ext = name_and_ext[1];
389 389 var content_type;
390 390 if (file_ext === '.ipynb') {
391 391 model.type = 'notebook';
392 392 model.format = 'json';
393 393 try {
394 394 model.content = JSON.parse(filedata);
395 395 } catch (e) {
396 396 dialog.modal({
397 397 title : 'Cannot upload invalid Notebook',
398 398 body : "The error was: " + e,
399 399 buttons : {'OK' : {
400 400 'class' : 'btn-primary',
401 401 click: function () {
402 402 item.remove();
403 403 }
404 404 }}
405 405 });
406 406 return false;
407 407 }
408 408 content_type = 'application/json';
409 409 } else {
410 410 model.type = 'file';
411 411 model.format = format;
412 412 model.content = filedata;
413 413 content_type = 'application/octet-stream';
414 414 }
415 415 filedata = item.data('filedata');
416 416
417 var settings = {
418 success : function () {
417 var on_success = function () {
419 418 item.removeClass('new-file');
420 419 that.add_link(model, item);
421 420 that.add_delete_button(item);
422 421 that.session_list.load_sessions();
423 },
424 422 };
425 423
426 424 var exists = false;
427 425 $.each(that.element.find('.list_item:not(.new-file)'), function(k,v){
428 426 if ($(v).data('name') === filename) { exists = true; return false; }
429 427 });
430 428
431 429 if (exists) {
432 430 dialog.modal({
433 431 title : "Replace file",
434 432 body : 'There is already a file named ' + filename + ', do you want to replace it?',
435 433 buttons : {
436 434 Overwrite : {
437 435 class: "btn-danger",
438 436 click: function () {
439 that.contents.save(path, model, settings);
437 that.contents.save(path, model).then(on_success);
440 438 }
441 439 },
442 440 Cancel : {
443 441 click: function() { item.remove(); }
444 442 }
445 443 }
446 444 });
447 445 } else {
448 that.contents.save(path, model, settings);
446 that.contents.save(path, model).then(on_success);
449 447 }
450 448
451 449 return false;
452 450 });
453 451 var cancel_button = $('<button/>').text("Cancel")
454 452 .addClass("btn btn-default btn-xs")
455 453 .click(function (e) {
456 454 item.remove();
457 455 return false;
458 456 });
459 457 item.find(".item_buttons").empty()
460 458 .append(upload_button)
461 459 .append(cancel_button);
462 460 };
463 461
464 462
465 463 // Backwards compatability.
466 464 IPython.NotebookList = NotebookList;
467 465
468 466 return {'NotebookList': NotebookList};
469 467 });
General Comments 0
You need to be logged in to leave comments. Login now