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