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