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