##// END OF EJS Templates
Custom widget persistence
Sylvain Corlay -
Show More
@@ -1,489 +1,481 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 "underscore",
6 6 "backbone",
7 7 "jquery",
8 8 "base/js/utils",
9 9 "base/js/namespace",
10 10 "services/kernels/comm"
11 11 ], function (_, Backbone, $, utils, IPython, comm) {
12 12 "use strict";
13 13 //--------------------------------------------------------------------
14 14 // WidgetManager class
15 15 //--------------------------------------------------------------------
16 16 var WidgetManager = function (comm_manager, notebook) {
17 17 /**
18 18 * Public constructor
19 19 */
20 20 WidgetManager._managers.push(this);
21 21
22 22 // Attach a comm manager to the
23 23 this.keyboard_manager = notebook.keyboard_manager;
24 24 this.notebook = notebook;
25 25 this.comm_manager = comm_manager;
26 26 this.comm_target_name = 'ipython.widget';
27 27 this._models = {}; /* Dictionary of model ids and model instance promises */
28 28
29 29 // Register with the comm manager.
30 30 this.comm_manager.register_target(this.comm_target_name, $.proxy(this._handle_comm_open, this));
31 31
32 32 // Load the initial state of the widget manager if a load callback was
33 33 // registered.
34 34 var that = this;
35 35 if (WidgetManager._load_callback) {
36 36 Promise.resolve().then(function () {
37 37 return WidgetManager._load_callback.call(that);
38 38 }).then(function(state) {
39 39 that.set_state(state);
40 40 }).catch(utils.reject('Error loading widget manager state', true));
41 41 }
42 42
43 43 // Setup state saving code.
44 44 this.notebook.events.on('before_save.Notebook', function() {
45 45 var save_callback = WidgetManager._save_callback;
46 46 var options = WidgetManager._get_state_options;
47 47 if (save_callback) {
48 48 that.get_state(options).then(function(state) {
49 49 save_callback.call(that, state);
50 50 }).catch(utils.reject('Could not call widget save state callback.', true));
51 51 }
52 52 });
53 53 };
54 54
55 55 //--------------------------------------------------------------------
56 56 // Class level
57 57 //--------------------------------------------------------------------
58 58 WidgetManager._model_types = {}; /* Dictionary of model type names (target_name) and model types. */
59 59 WidgetManager._view_types = {}; /* Dictionary of view names and view types. */
60 60 WidgetManager._managers = []; /* List of widget managers */
61 61 WidgetManager._load_callback = null;
62 62 WidgetManager._save_callback = null;
63 63
64 64 WidgetManager.register_widget_model = function (model_name, model_type) {
65 65 /**
66 66 * Registers a widget model by name.
67 67 */
68 68 WidgetManager._model_types[model_name] = model_type;
69 69 };
70 70
71 71 WidgetManager.register_widget_view = function (view_name, view_type) {
72 72 /**
73 73 * Registers a widget view by name.
74 74 */
75 75 WidgetManager._view_types[view_name] = view_type;
76 76 };
77 77
78 78 WidgetManager.set_state_callbacks = function (load_callback, save_callback, options) {
79 79 /**
80 80 * Registers callbacks for widget state persistence.
81 81 *
82 82 * Parameters
83 83 * ----------
84 84 * load_callback: function()
85 85 * function that is called when the widget manager state should be
86 86 * loaded. This function should return a promise for the widget
87 87 * manager state. An empty state is an empty dictionary `{}`.
88 88 * save_callback: function(state as dictionary)
89 89 * function that is called when the notebook is saved or autosaved.
90 90 * The current state of the widget manager is passed in as the first
91 91 * argument.
92 92 */
93 93 WidgetManager._load_callback = load_callback;
94 94 WidgetManager._save_callback = save_callback;
95 95 WidgetManager._get_state_options = options;
96 96
97 97 // Use the load callback to immediately load widget states.
98 98 WidgetManager._managers.forEach(function(manager) {
99 99 if (load_callback) {
100 100 Promise.resolve().then(function () {
101 101 return load_callback.call(manager);
102 102 }).then(function(state) {
103 103 manager.set_state(state);
104 104 }).catch(utils.reject('Error loading widget manager state', true));
105 105 }
106 106 });
107 107 };
108 108
109 109 // Use local storage to persist widgets across page refresh by default.
110 110 // LocalStorage is per domain, so we need to explicitly set the URL
111 111 // that the widgets are associated with so they don't show on other
112 112 // pages hosted by the noteboook server.
113 113 var url = [window.location.protocol, '//', window.location.host, window.location.pathname].join('');
114 114 var key = 'widgets:' + url;
115 115 WidgetManager.set_state_callbacks(function() {
116 116 if (localStorage[key]) {
117 117 return JSON.parse(localStorage[key]);
118 118 }
119 119 return {};
120 120 }, function(state) {
121 121 localStorage[key] = JSON.stringify(state);
122 122 });
123 123
124 124 //--------------------------------------------------------------------
125 125 // Instance level
126 126 //--------------------------------------------------------------------
127 127 WidgetManager.prototype.display_view = function(msg, model) {
128 128 /**
129 129 * Displays a view for a particular model.
130 130 */
131 131 var cell = this.get_msg_cell(msg.parent_header.msg_id);
132 132 if (cell === null) {
133 133 return Promise.reject(new Error("Could not determine where the display" +
134 134 " message was from. Widget will not be displayed"));
135 135 } else {
136 136 return this.display_view_in_cell(cell, model)
137 137 .catch(utils.reject('Could not display view', true));
138 138 }
139 139 };
140 140
141 141 WidgetManager.prototype.display_view_in_cell = function(cell, model) {
142 142 // Displays a view in a cell.
143 143 if (cell.display_widget_view) {
144 144 var that = this;
145 145 return cell.display_widget_view(this.create_view(model, {
146 146 cell: cell,
147 147 // Only set cell_index when view is displayed as directly.
148 148 cell_index: that.notebook.find_cell_index(cell),
149 149 })).then(function(view) {
150 150 that._handle_display_view(view);
151 151 view.trigger('displayed');
152 152 return view;
153 153 }).catch(utils.reject('Could not create or display view', true));
154 154 } else {
155 155 return Promise.reject(new Error('Cell does not have a `display_widget_view` method'));
156 156 }
157 157 };
158 158
159 159 WidgetManager.prototype._handle_display_view = function (view) {
160 160 /**
161 161 * Have the IPython keyboard manager disable its event
162 162 * handling so the widget can capture keyboard input.
163 163 * Note, this is only done on the outer most widgets.
164 164 */
165 165 if (this.keyboard_manager) {
166 166 this.keyboard_manager.register_events(view.$el);
167 167
168 168 if (view.additional_elements) {
169 169 for (var i = 0; i < view.additional_elements.length; i++) {
170 170 this.keyboard_manager.register_events(view.additional_elements[i]);
171 171 }
172 172 }
173 173 }
174 174 };
175 175
176 176 WidgetManager.prototype.create_view = function(model, options) {
177 177 /**
178 178 * Creates a promise for a view of a given model
179 179 *
180 180 * Make sure the view creation is not out of order with
181 181 * any state updates.
182 182 */
183 183 model.state_change = model.state_change.then(function() {
184 184
185 185 return utils.load_class(model.get('_view_name'), model.get('_view_module'),
186 186 WidgetManager._view_types).then(function(ViewType) {
187 187
188 188 // If a view is passed into the method, use that view's cell as
189 189 // the cell for the view that is created.
190 190 options = options || {};
191 191 if (options.parent !== undefined) {
192 192 options.cell = options.parent.options.cell;
193 193 }
194 194 // Create and render the view...
195 195 var parameters = {model: model, options: options};
196 196 var view = new ViewType(parameters);
197 197 view.listenTo(model, 'destroy', view.remove);
198 198 return Promise.resolve(view.render()).then(function() {return view;});
199 199 }).catch(utils.reject("Couldn't create a view for model id '" + String(model.id) + "'", true));
200 200 });
201 201 var id = utils.uuid();
202 202 model.views[id] = model.state_change;
203 203 model.state_change.then(function(view) {
204 204 view.once('remove', function() {
205 205 delete view.model.views[id];
206 206 }, this);
207 207 });
208 208 return model.state_change;
209 209 };
210 210
211 211 WidgetManager.prototype.get_msg_cell = function (msg_id) {
212 212 var cell = null;
213 213 // First, check to see if the msg was triggered by cell execution.
214 214 if (this.notebook) {
215 215 cell = this.notebook.get_msg_cell(msg_id);
216 216 }
217 217 if (cell !== null) {
218 218 return cell;
219 219 }
220 220 // Second, check to see if a get_cell callback was defined
221 221 // for the message. get_cell callbacks are registered for
222 222 // widget messages, so this block is actually checking to see if the
223 223 // message was triggered by a widget.
224 224 var kernel = this.comm_manager.kernel;
225 225 if (kernel) {
226 226 var callbacks = kernel.get_callbacks_for_msg(msg_id);
227 227 if (callbacks && callbacks.iopub &&
228 228 callbacks.iopub.get_cell !== undefined) {
229 229 return callbacks.iopub.get_cell();
230 230 }
231 231 }
232 232
233 233 // Not triggered by a cell or widget (no get_cell callback
234 234 // exists).
235 235 return null;
236 236 };
237 237
238 238 WidgetManager.prototype.callbacks = function (view) {
239 239 /**
240 240 * callback handlers specific a view
241 241 */
242 242 var callbacks = {};
243 243 if (view && view.options.cell) {
244 244
245 245 // Try to get output handlers
246 246 var cell = view.options.cell;
247 247 var handle_output = null;
248 248 var handle_clear_output = null;
249 249 if (cell.output_area) {
250 250 handle_output = $.proxy(cell.output_area.handle_output, cell.output_area);
251 251 handle_clear_output = $.proxy(cell.output_area.handle_clear_output, cell.output_area);
252 252 }
253 253
254 254 // Create callback dictionary using what is known
255 255 var that = this;
256 256 callbacks = {
257 257 iopub : {
258 258 output : handle_output,
259 259 clear_output : handle_clear_output,
260 260
261 261 // Special function only registered by widget messages.
262 262 // Allows us to get the cell for a message so we know
263 263 // where to add widgets if the code requires it.
264 264 get_cell : function () {
265 265 return cell;
266 266 },
267 267 },
268 268 };
269 269 }
270 270 return callbacks;
271 271 };
272 272
273 273 WidgetManager.prototype.get_model = function (model_id) {
274 274 /**
275 275 * Get a promise for a model by model id.
276 276 */
277 277 return this._models[model_id];
278 278 };
279 279
280 280 WidgetManager.prototype._handle_comm_open = function (comm, msg) {
281 281 /**
282 282 * Handle when a comm is opened.
283 283 */
284 284 return this.create_model({
285 model_name: msg.content.data.model_name,
286 model_module: msg.content.data.model_module,
287 comm: comm}).catch(utils.reject("Couldn't create a model.", true));
285 model_name: msg.content.data.model_name,
286 model_module: msg.content.data.model_module,
287 comm: comm,
288 }).catch(utils.reject("Couldn't create a model.", true));
288 289 };
289 290
290 291 WidgetManager.prototype.create_model = function (options) {
291 292 /**
292 293 * Create and return a promise for a new widget model
293 294 *
294 295 * Minimally, one must provide the model_name and widget_class
295 296 * parameters to create a model from Javascript.
296 297 *
297 298 * Example
298 299 * --------
299 300 * JS:
300 301 * IPython.notebook.kernel.widget_manager.create_model({
301 * model_name: 'WidgetModel',
302 * widget_class: 'IPython.html.widgets.widget_int.IntSlider'})
303 * .then(function(model) { console.log('Create success!', model); },
304 * $.proxy(console.error, console));
302 * model_name: 'WidgetModel',
303 * widget_class: 'IPython.html.widgets.widget_int.IntSlider'
304 * })
305 * .then(function(model) { console.log('Create success!', model); },
306 * $.proxy(console.error, console));
305 307 *
306 308 * Parameters
307 309 * ----------
308 310 * options: dictionary
309 311 * Dictionary of options with the following contents:
310 312 * model_name: string
311 313 * Target name of the widget model to create.
312 314 * model_module: (optional) string
313 315 * Module name of the widget model to create.
314 316 * widget_class: (optional) string
315 317 * Target name of the widget in the back-end.
316 318 * comm: (optional) Comm
317 319 *
318 320 * Create a comm if it wasn't provided.
319 321 */
320 322 var comm = options.comm;
321 323 if (!comm) {
322 324 comm = this.comm_manager.new_comm('ipython.widget', {'widget_class': options.widget_class});
323 325 }
324 326
325 327 var that = this;
326 328 var model_id = comm.comm_id;
327 329 var model_promise = utils.load_class(options.model_name, options.model_module, WidgetManager._model_types)
328 330 .then(function(ModelType) {
329 331 var widget_model = new ModelType(that, model_id, comm);
330 332 widget_model.once('comm:close', function () {
331 333 delete that._models[model_id];
332 334 });
333 335 widget_model.name = options.model_name;
334 336 widget_model.module = options.model_module;
335 337 return widget_model;
336 338
337 339 }, function(error) {
338 340 delete that._models[model_id];
339 341 var wrapped_error = new utils.WrappedError("Couldn't create model", error);
340 342 return Promise.reject(wrapped_error);
341 343 });
342 344 this._models[model_id] = model_promise;
343 345 return model_promise;
344 346 };
345 347
346 348 WidgetManager.prototype.get_state = function(options) {
347 349 /**
348 350 * Asynchronously get the state of the widget manager.
349 351 *
350 352 * This includes all of the widget models and the cells that they are
351 353 * displayed in.
352 354 *
353 355 * Parameters
354 356 * ----------
355 357 * options: dictionary
356 358 * Dictionary of options with the following contents:
357 359 * only_displayed: (optional) boolean=false
358 360 * Only return models with one or more displayed views.
359 361 * not_live: (optional) boolean=false
360 362 * Include models that have comms with severed connections.
361 363 *
362 364 * Returns
363 365 * -------
364 366 * Promise for a state dictionary
365 367 */
366 368 var that = this;
367 369 return utils.resolve_promises_dict(this._models).then(function(models) {
368 370 var state = {};
369 371
370 372 var model_promises = [];
371 373 for (var model_id in models) {
372 374 if (models.hasOwnProperty(model_id)) {
373 375 var model = models[model_id];
374 376
375 377 // If the model has one or more views defined for it,
376 378 // consider it displayed.
377 379 var displayed_flag = !(options && options.only_displayed) || Object.keys(model.views).length > 0;
378 380 var live_flag = (options && options.not_live) || model.comm_live;
379 381 if (displayed_flag && live_flag) {
380 382 state[model_id] = {
381 383 model_name: model.name,
382 384 model_module: model.module,
383 385 state: model.get_state(),
384 386 views: [],
385 387 };
386 388
387 389 // Get the views that are displayed *now*.
388 390 (function(local_state) {
389 391 model_promises.push(utils.resolve_promises_dict(model.views).then(function(model_views) {
390 392 for (var id in model_views) {
391 393 if (model_views.hasOwnProperty(id)) {
392 394 var view = model_views[id];
393 395 if (view.options.cell_index) {
394 396 local_state.views.push(view.options.cell_index);
395 397 }
396 398 }
397 399 }
398 400 }));
399 401 })(state[model_id]);
400 402 }
401 403 }
402 404 }
403 405 return Promise.all(model_promises).then(function() { return state; });
404 406 }).catch(utils.reject('Could not get state of widget manager', true));
405 407 };
406
408
407 409 WidgetManager.prototype.set_state = function(state) {
408 410 /**
409 411 * Set the notebook's state.
410 412 *
411 413 * Reconstructs all of the widget models and attempts to redisplay the
412 414 * widgets in the appropriate cells by cell index.
413 415 */
414
416
415 417 // Get the kernel when it's available.
416 418 var that = this;
417 419 return this._get_connected_kernel().then(function(kernel) {
418
419 // Recreate all the widget models for the given state and
420 // display the views.
421 that.all_views = [];
422 var model_ids = Object.keys(state);
423 for (var i = 0; i < model_ids.length; i++) {
424 var model_id = model_ids[i];
425
420
421 // Recreate all the widget models for the given notebook state.
422 var all_models = Promise.all(_.map(Object.keys(state), function (model_id) {
426 423 // Recreate a comm using the widget's model id (model_id == comm_id).
427 424 var new_comm = new comm.Comm(kernel.widget_manager.comm_target_name, model_id);
428 425 kernel.comm_manager.register_comm(new_comm);
429 426
430 427 // Create the model using the recreated comm. When the model is
431 428 // created we don't know yet if the comm is valid so set_comm_live
432 429 // false. Once we receive the first state push from the back-end
433 430 // we know the comm is alive.
434 var views = kernel.widget_manager.create_model({
435 comm: new_comm,
436 model_name: state[model_id].model_name,
437 model_module: state[model_id].model_module})
438 .then(function(model) {
439
431 return kernel.widget_manager.create_model({
432 comm: new_comm,
433 model_name: state[model_id].model_name,
434 model_module: state[model_id].model_module,
435 }).then(function(model) {
440 436 model.set_comm_live(false);
441 var view_promise = Promise.resolve().then(function() {
442 return model.set_state(state[model.id].state);
443 }).then(function() {
444 model.request_state().then(function() {
445 model.set_comm_live(true);
446 });
447
448 // Display the views of the model.
449 var views = [];
450 var model_views = state[model.id].views;
451 for (var j=0; j<model_views.length; j++) {
452 var cell_index = model_views[j];
453 var cell = that.notebook.get_cell(cell_index);
454 views.push(that.display_view_in_cell(cell, model));
455 }
456 return Promise.all(views);
437 model.set_state(state[model.id].state);
438 return model.request_state().then(function() {
439 model.set_comm_live(true);
440 return model;
457 441 });
458 return view_promise;
459 442 });
460 that.all_views.push(views);
461 }
462 return Promise.all(that.all_views);
463 }).catch(utils.reject('Could not set widget manager state.', true));
443 }, this));
444
445 // Display all the views
446 return all_models.then(function(models) {
447 return Promise.all(_.map(models, function(model) {
448 // Display the views of the model.
449 return Promise.all(_.map(state[model.id].views, function(cell_index) {
450 var cell = that.notebook.get_cell(cell_index);
451 return that.display_view_in_cell(cell, model);
452 }));
453 }));
454 });
455 }).catch(utils.reject('Could not set widget manager state.', true));
464 456 };
465 457
466 458 WidgetManager.prototype._get_connected_kernel = function() {
467 459 /**
468 460 * Gets a promise for a connected kernel
469 461 */
470 462 var that = this;
471 463 return new Promise(function(resolve, reject) {
472 if (that.comm_manager &&
473 that.comm_manager.kernel &&
464 if (that.comm_manager &&
465 that.comm_manager.kernel &&
474 466 that.comm_manager.kernel.is_connected()) {
475 467
476 468 resolve(that.comm_manager.kernel);
477 469 } else {
478 470 that.notebook.events.on('kernel_connected.Kernel', function(event, data) {
479 471 resolve(data.kernel);
480 472 });
481 }
473 }
482 474 });
483 475 };
484 476
485 477 // Backwards compatibility.
486 478 IPython.WidgetManager = WidgetManager;
487 479
488 480 return {'WidgetManager': WidgetManager};
489 481 });
General Comments 0
You need to be logged in to leave comments. Login now