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