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