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