##// END OF EJS Templates
Address @jasongrout 's review comments, take 2
Jonathan Frederic -
Show More
@@ -1,442 +1,431 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 if (WidgetManager._load_callback) {
35 35 this.set_state(WidgetManager._load_callback.call(this));
36 36 }
37 37
38 38 // Setup state saving code.
39 39 var that = this;
40 40 this.notebook.events.on('before_save.Notebook', function() {
41 41 var save_callback = WidgetManager._save_callback;
42 42 var options = WidgetManager._get_state_options;
43 43 if (save_callback) {
44 44 that.get_state(options).then(function(state) {
45 45 save_callback.call(that, state);
46 46 }).catch(utils.reject('Could not call widget save state callback.', true));
47 47 }
48 48 });
49 49 };
50 50
51 51 //--------------------------------------------------------------------
52 52 // Class level
53 53 //--------------------------------------------------------------------
54 54 WidgetManager._model_types = {}; /* Dictionary of model type names (target_name) and model types. */
55 55 WidgetManager._view_types = {}; /* Dictionary of view names and view types. */
56 56 WidgetManager._managers = []; /* List of widget managers */
57 57 WidgetManager._load_callback = null;
58 58 WidgetManager._save_callback = null;
59 59
60 60 WidgetManager.register_widget_model = function (model_name, model_type) {
61 61 // Registers a widget model by name.
62 62 WidgetManager._model_types[model_name] = model_type;
63 63 };
64 64
65 65 WidgetManager.register_widget_view = function (view_name, view_type) {
66 66 // Registers a widget view by name.
67 67 WidgetManager._view_types[view_name] = view_type;
68 68 };
69 69
70 70 WidgetManager.set_state_callbacks = function (load_callback, save_callback, options) {
71 71 // Registers callbacks for widget state persistence.
72 72 WidgetManager._load_callback = load_callback;
73 73 WidgetManager._save_callback = save_callback;
74 74 WidgetManager._get_state_options = options;
75 75
76 76 // Use the load callback to immediately load widget states.
77 77 WidgetManager._managers.forEach(function(manager) {
78 78 if (load_callback) {
79 79 manager.set_state(load_callback.call(manager));
80 80 }
81 81 });
82 82 };
83 83
84 84 //--------------------------------------------------------------------
85 85 // Instance level
86 86 //--------------------------------------------------------------------
87 87 WidgetManager.prototype.display_view = function(msg, model) {
88 88 /**
89 89 * Displays a view for a particular model.
90 90 */
91 var that = this;
92 return new Promise(function(resolve, reject) {
93 var cell = that.get_msg_cell(msg.parent_header.msg_id);
94 if (cell === null) {
95 reject(new Error("Could not determine where the display" +
96 " message was from. Widget will not be displayed"));
97 } else {
98 return that.display_view_in_cell(cell, model)
99 .catch(function(error) {
100 reject(new utils.WrappedError('View could not be displayed.', error));
101 });
102 }
103 });
91 var cell = this.get_msg_cell(msg.parent_header.msg_id);
92 if (cell === null) {
93 return Promise.reject(new Error("Could not determine where the display" +
94 " message was from. Widget will not be displayed"));
95 } else {
96 return this.display_view_in_cell(cell, model)
97 .catch(utils.reject('View could not be displayed.', true));
98 }
104 99 };
105 100
106 101 WidgetManager.prototype.display_view_in_cell = function(cell, model) {
107 102 // Displays a view in a cell.
108 var that = this;
109 return new Promise(function(resolve, reject) {
110 if (cell.display_widget_view) {
111 cell.display_widget_view(that.create_view(model, {cell: cell}))
112 .then(function(view) {
113 that._handle_display_view(view);
114 view.trigger('displayed');
115 resolve(view);
116 }, function(error) {
117 reject(new utils.WrappedError('Could not create or display view', error));
118 });
119 } else {
120 reject(new Error('Cell does not have a `display_widget_view` method'));
121 }
122 });
103 if (cell.display_widget_view) {
104 var that = this;
105 return cell.display_widget_view(this.create_view(model, {
106 cell: cell,
107 // Only set cell_index when view is displayed as directly.
108 cell_index: that.notebook.find_cell_index(cell),
109 })).then(function(view) {
110 that._handle_display_view(view);
111 view.trigger('displayed');
112 resolve(view);
113 }).catch(utils.reject('Could not create or display view', true));
114 } else {
115 return Promise.reject(new Error('Cell does not have a `display_widget_view` method'));
116 }
123 117 };
124 118
125 119 WidgetManager.prototype._handle_display_view = function (view) {
126 120 /**
127 121 * Have the IPython keyboard manager disable its event
128 122 * handling so the widget can capture keyboard input.
129 123 * Note, this is only done on the outer most widgets.
130 124 */
131 125 if (this.keyboard_manager) {
132 126 this.keyboard_manager.register_events(view.$el);
133 127
134 128 if (view.additional_elements) {
135 129 for (var i = 0; i < view.additional_elements.length; i++) {
136 130 this.keyboard_manager.register_events(view.additional_elements[i]);
137 131 }
138 132 }
139 133 }
140 134 };
141 135
142 136 WidgetManager.prototype.create_view = function(model, options) {
143 137 /**
144 138 * Creates a promise for a view of a given model
145 139 *
146 140 * Make sure the view creation is not out of order with
147 141 * any state updates.
148 142 */
149 143 model.state_change = model.state_change.then(function() {
150 144
151 145 return utils.load_class(model.get('_view_name'), model.get('_view_module'),
152 146 WidgetManager._view_types).then(function(ViewType) {
153 147
154 148 // If a view is passed into the method, use that view's cell as
155 149 // the cell for the view that is created.
156 150 options = options || {};
157 151 if (options.parent !== undefined) {
158 152 options.cell = options.parent.options.cell;
159 153 }
160 154 // Create and render the view...
161 155 var parameters = {model: model, options: options};
162 156 var view = new ViewType(parameters);
163 157 view.listenTo(model, 'destroy', view.remove);
164 158 return Promise.resolve(view.render()).then(function() {return view;});
165 159 }).catch(utils.reject("Couldn't create a view for model id '" + String(model.id) + "'", true));
166 160 });
167 161 model.views[utils.uuid()] = model.state_change;
168 162 return model.state_change;
169 163 };
170 164
171 165 WidgetManager.prototype.get_msg_cell = function (msg_id) {
172 166 var cell = null;
173 167 // First, check to see if the msg was triggered by cell execution.
174 168 if (this.notebook) {
175 169 cell = this.notebook.get_msg_cell(msg_id);
176 170 }
177 171 if (cell !== null) {
178 172 return cell;
179 173 }
180 174 // Second, check to see if a get_cell callback was defined
181 175 // for the message. get_cell callbacks are registered for
182 176 // widget messages, so this block is actually checking to see if the
183 177 // message was triggered by a widget.
184 178 var kernel = this.comm_manager.kernel;
185 179 if (kernel) {
186 180 var callbacks = kernel.get_callbacks_for_msg(msg_id);
187 181 if (callbacks && callbacks.iopub &&
188 182 callbacks.iopub.get_cell !== undefined) {
189 183 return callbacks.iopub.get_cell();
190 184 }
191 185 }
192 186
193 187 // Not triggered by a cell or widget (no get_cell callback
194 188 // exists).
195 189 return null;
196 190 };
197 191
198 192 WidgetManager.prototype.callbacks = function (view) {
199 193 /**
200 194 * callback handlers specific a view
201 195 */
202 196 var callbacks = {};
203 197 if (view && view.options.cell) {
204 198
205 199 // Try to get output handlers
206 200 var cell = view.options.cell;
207 201 var handle_output = null;
208 202 var handle_clear_output = null;
209 203 if (cell.output_area) {
210 204 handle_output = $.proxy(cell.output_area.handle_output, cell.output_area);
211 205 handle_clear_output = $.proxy(cell.output_area.handle_clear_output, cell.output_area);
212 206 }
213 207
214 208 // Create callback dictionary using what is known
215 209 var that = this;
216 210 callbacks = {
217 211 iopub : {
218 212 output : handle_output,
219 213 clear_output : handle_clear_output,
220 214
221 215 // Special function only registered by widget messages.
222 216 // Allows us to get the cell for a message so we know
223 217 // where to add widgets if the code requires it.
224 218 get_cell : function () {
225 219 return cell;
226 220 },
227 221 },
228 222 };
229 223 }
230 224 return callbacks;
231 225 };
232 226
233 227 WidgetManager.prototype.get_model = function (model_id) {
234 228 /**
235 229 * Get a promise for a model by model id.
236 230 */
237 231 return this._models[model_id];
238 232 };
239 233
240 234 WidgetManager.prototype._handle_comm_open = function (comm, msg) {
241 235 /**
242 236 * Handle when a comm is opened.
243 237 */
244 238 return this.create_model({
245 239 model_name: msg.content.data.model_name,
246 240 model_module: msg.content.data.model_module,
247 241 comm: comm}).catch(utils.reject("Couldn't create a model.", true));
248 242 };
249 243
250 244 WidgetManager.prototype.create_model = function (options) {
251 245 /**
252 246 * Create and return a promise for a new widget model
253 247 *
254 248 * Minimally, one must provide the model_name and widget_class
255 249 * parameters to create a model from Javascript.
256 250 *
257 251 * Example
258 252 * --------
259 253 * JS:
260 254 * IPython.notebook.kernel.widget_manager.create_model({
261 255 * model_name: 'WidgetModel',
262 256 * widget_class: 'IPython.html.widgets.widget_int.IntSlider'})
263 257 * .then(function(model) { console.log('Create success!', model); },
264 258 * $.proxy(console.error, console));
265 259 *
266 260 * Parameters
267 261 * ----------
268 262 * options: dictionary
269 263 * Dictionary of options with the following contents:
270 264 * model_name: string
271 265 * Target name of the widget model to create.
272 266 * model_module: (optional) string
273 267 * Module name of the widget model to create.
274 268 * widget_class: (optional) string
275 269 * Target name of the widget in the back-end.
276 270 * comm: (optional) Comm
277 271 *
278 272 * Create a comm if it wasn't provided.
279 273 */
280 274 var comm = options.comm;
281 275 if (!comm) {
282 276 comm = this.comm_manager.new_comm('ipython.widget', {'widget_class': options.widget_class});
283 277 }
284 278
285 279 var that = this;
286 280 var model_id = comm.comm_id;
287 281 var model_promise = utils.load_class(options.model_name, options.model_module, WidgetManager._model_types)
288 282 .then(function(ModelType) {
289 283 var widget_model = new ModelType(that, model_id, comm);
290 284 widget_model.once('comm:close', function () {
291 285 delete that._models[model_id];
292 286 });
293 287 widget_model.name = options.model_name;
294 288 widget_model.module = options.model_module;
295 289 return widget_model;
296 290
297 291 }, function(error) {
298 292 delete that._models[model_id];
299 293 var wrapped_error = new utils.WrappedError("Couldn't create model", error);
300 294 return Promise.reject(wrapped_error);
301 295 });
302 296 this._models[model_id] = model_promise;
303 297 return model_promise;
304 298 };
305 299
306 300 WidgetManager.prototype.get_state = function(options) {
307 301 // Asynchronously get the state of the widget manager.
308 302 //
309 303 // This includes all of the widget models and the cells that they are
310 304 // displayed in.
311 305 //
312 306 // Parameters
313 307 // ----------
314 308 // options: dictionary
315 309 // Dictionary of options with the following contents:
316 310 // only_displayed: (optional) boolean=false
317 311 // Only return models with one or more displayed views.
318 // not_alive: (optional) boolean=false
312 // not_live: (optional) boolean=false
319 313 // Include models that have comms with severed connections.
320 314 //
321 315 // Returns
322 316 // -------
323 317 // Promise for a state dictionary
324 318 var that = this;
325 319 return utils.resolve_promises_dict(this._models).then(function(models) {
326 320 var state = {};
327 321 for (var model_id in models) {
328 322 if (models.hasOwnProperty(model_id)) {
329 323 var model = models[model_id];
330 324
331 325 // If the model has one or more views defined for it,
332 326 // consider it displayed.
333 327 var displayed_flag = !(options && options.only_displayed) || Object.keys(model.views).length > 0;
334 var alive_flag = (options && options.not_alive) || model.comm_alive;
335 if (displayed_flag && alive_flag) {
328 var live_flag = (options && options.not_live) || model.comm_live;
329 if (displayed_flag && live_flag) {
336 330 state[model_id] = {
337 331 model_name: model.name,
338 332 model_module: model.module,
339 333 state: model.get_state(),
340 334 views: [],
341 335 };
342 336
343 337 // Get the views that are displayed *now*.
344 338 for (var id in model.views) {
345 339 if (model.views.hasOwnProperty(id)) {
346 340 var view = model.views[id];
347 var cell = view.options.cell;
348
349 // Only store the cell reference if this view is a top level
350 // child of the cell.
351 if (cell.widget_views.indexOf(view) != -1) {
352 var cell_index = that.notebook.find_cell_index(cell);
353 state[model_id].views.push(cell_index);
341 if (view.options.cell_index) {
342 state[model_id].views.push(view.options.cell_index);
354 343 }
355 344 }
356 345 }
357 346 }
358 347 }
359 348 }
360 349 return state;
361 });
350 }).catch(utils.reject('Could not get state of widget manager', true));
362 351 };
363 352
364 353 WidgetManager.prototype.set_state = function(state) {
365 354 // Set the notebook's state.
366 355 //
367 356 // Reconstructs all of the widget models and attempts to redisplay the
368 357 // widgets in the appropriate cells by cell index.
369 358
370 359 // Get the kernel when it's available.
371 360 var that = this;
372 361 return this._get_connected_kernel().then(function(kernel) {
373 362
374 363 // Recreate all the widget models for the given state and
375 364 // display the views.
376 365 that.all_views = [];
377 366 var model_ids = Object.keys(state);
378 367 for (var i = 0; i < model_ids.length; i++) {
379 368 var model_id = model_ids[i];
380 369
381 370 // Recreate a comm using the widget's model id (model_id == comm_id).
382 371 var new_comm = new comm.Comm(kernel.widget_manager.comm_target_name, model_id);
383 372 kernel.comm_manager.register_comm(new_comm);
384 373
385 374 // Create the model using the recreated comm. When the model is
386 // created we don't know yet if the comm is valid so set_comm_alive
375 // created we don't know yet if the comm is valid so set_comm_live
387 376 // false. Once we receive the first state push from the back-end
388 377 // we know the comm is alive.
389 378 var views = kernel.widget_manager.create_model({
390 379 comm: new_comm,
391 380 model_name: state[model_id].model_name,
392 381 model_module: state[model_id].model_module})
393 382 .then(function(model) {
394 383
395 model.set_comm_alive(false);
384 model.set_comm_live(false);
396 385 var view_promise = Promise.resolve().then(function() {
397 386 return model.set_state(state[model.id].state);
398 387 }).then(function() {
399 388 model.request_state().then(function() {
400 model.set_comm_alive(true);
389 model.set_comm_live(true);
401 390 });
402 391
403 392 // Display the views of the model.
404 393 var views = [];
405 394 var model_views = state[model.id].views;
406 395 for (var j=0; j<model_views.length; j++) {
407 396 var cell_index = model_views[j];
408 397 var cell = that.notebook.get_cell(cell_index);
409 398 views.push(that.display_view_in_cell(cell, model));
410 399 }
411 400 return Promise.all(views);
412 401 });
413 402 return view_promise;
414 403 });
415 404 that.all_views.push(views);
416 405 }
417 406 return Promise.all(that.all_views);
418 407 }).catch(utils.reject('Could not set widget manager state.', true));
419 408 };
420 409
421 410 WidgetManager.prototype._get_connected_kernel = function() {
422 411 // Gets a promise for a connected kernel.
423 412 var that = this;
424 413 return new Promise(function(resolve, reject) {
425 414 if (that.comm_manager &&
426 415 that.comm_manager.kernel &&
427 416 that.comm_manager.kernel.is_connected()) {
428 417
429 418 resolve(that.comm_manager.kernel);
430 419 } else {
431 420 that.notebook.events.on('kernel_connected.Kernel', function(event, data) {
432 421 resolve(data.kernel);
433 422 });
434 423 }
435 424 });
436 425 };
437 426
438 427 // Backwards compatibility.
439 428 IPython.WidgetManager = WidgetManager;
440 429
441 430 return {'WidgetManager': WidgetManager};
442 431 });
@@ -1,753 +1,757 b''
1 1 // Copyright (c) IPython Development Team.
2 2 // Distributed under the terms of the Modified BSD License.
3 3
4 4 define(["widgets/js/manager",
5 5 "underscore",
6 6 "backbone",
7 7 "jquery",
8 8 "base/js/utils",
9 9 "base/js/namespace",
10 10 ], function(widgetmanager, _, Backbone, $, utils, IPython){
11 11
12 12 var WidgetModel = Backbone.Model.extend({
13 13 constructor: function (widget_manager, model_id, comm) {
14 14 /**
15 15 * Constructor
16 16 *
17 17 * Creates a WidgetModel instance.
18 18 *
19 19 * Parameters
20 20 * ----------
21 21 * widget_manager : WidgetManager instance
22 22 * model_id : string
23 23 * An ID unique to this model.
24 24 * comm : Comm instance (optional)
25 25 */
26 26 this.widget_manager = widget_manager;
27 27 this.state_change = Promise.resolve();
28 28 this._buffered_state_diff = {};
29 29 this.pending_msgs = 0;
30 30 this.msg_buffer = null;
31 31 this.state_lock = null;
32 32 this.id = model_id;
33 33 this.views = {};
34 this._resolve_received_state = {};
34 35
35 36 if (comm !== undefined) {
36 37 // Remember comm associated with the model.
37 38 this.comm = comm;
38 39 comm.model = this;
39 40
40 41 // Hook comm messages up to model.
41 42 comm.on_close($.proxy(this._handle_comm_closed, this));
42 43 comm.on_msg($.proxy(this._handle_comm_msg, this));
43 44
44 45 // Assume the comm is alive.
45 this.set_comm_alive(true);
46 this.set_comm_live(true);
46 47 } else {
47 this.set_comm_alive(false);
48 this.set_comm_live(false);
48 49 }
49 50 return Backbone.Model.apply(this);
50 51 },
51 52
52 53 send: function (content, callbacks) {
53 54 /**
54 55 * Send a custom msg over the comm.
55 56 */
56 57 if (this.comm !== undefined) {
57 58 var data = {method: 'custom', content: content};
58 59 this.comm.send(data, callbacks);
59 60 this.pending_msgs++;
60 61 }
61 62 },
62 63
63 64 request_state: function(callbacks) {
64 65 /**
65 66 * Request a state push from the back-end.
66 67 */
67 68 if (!this.comm) {
68 69 console.error("Could not request_state because comm doesn't exist!");
69 70 return;
70 71 }
71 72
73 var msg_id = this.comm.send({method: 'request_state'}, callbacks || this.widget_manager.callbacks());
74
72 75 // Promise that is resolved when a state is received
73 76 // from the back-end.
74 77 var that = this;
75 78 var received_state = new Promise(function(resolve) {
76 that._resolve_received_state = resolve;
79 that._resolve_received_state[msg_id] = resolve;
77 80 });
78
79 this.comm.send({method: 'request_state'}, callbacks || this.widget_manager.callbacks());
80 81 return received_state;
81 82 },
82 83
83 set_comm_alive: function(alive) {
84 set_comm_live: function(live) {
84 85 /**
85 * Change the comm_alive state of the model.
86 * Change the comm_live state of the model.
86 87 */
87 if (this.comm_alive === undefined || this.comm_alive != alive) {
88 this.comm_alive = alive;
89 this.trigger(alive ? 'comm_is_live' : 'comm_is_dead', {model: this});
88 if (this.comm_live === undefined || this.comm_live != live) {
89 this.comm_live = live;
90 this.trigger(live ? 'comm:live' : 'comm:dead', {model: this});
90 91 }
91 92 },
92 93
93 94 close: function(comm_closed) {
94 95 /**
95 96 * Close model
96 97 */
97 98 if (this.comm && !comm_closed) {
98 99 this.comm.close();
99 100 }
100 101 this.stopListening();
101 102 this.trigger('destroy', this);
102 103 delete this.comm.model; // Delete ref so GC will collect widget model.
103 104 delete this.comm;
104 105 delete this.model_id; // Delete id from model so widget manager cleans up.
105 106 _.each(this.views, function(v, id, views) {
106 107 v.then(function(view) {
107 108 view.remove();
108 109 delete views[id];
109 110 });
110 111 });
111 112 },
112 113
113 114 _handle_comm_closed: function (msg) {
114 115 /**
115 116 * Handle when a widget is closed.
116 117 */
117 118 this.trigger('comm:close');
118 119 this.close(true);
119 120 },
120 121
121 122 _handle_comm_msg: function (msg) {
122 123 /**
123 124 * Handle incoming comm msg.
124 125 */
125 126 var method = msg.content.data.method;
126 127 var that = this;
127 128 switch (method) {
128 129 case 'update':
129 this.state_change = this.state_change.then(function() {
130 return that.set_state(msg.content.data.state);
131 }).catch(utils.reject("Couldn't process update msg for model id '" + String(that.id) + "'", true));
130 this.state_change = this.state_change
131 .then(function() {
132 return that.set_state(msg.content.data.state);
133 }).catch(utils.reject("Couldn't process update msg for model id '" + String(that.id) + "'", true))
134 .then(function() {
135 var parent_id = msg.parent_header.msg_id;
136 if (that._resolve_received_state[parent_id] !== undefined) {
137 that._resolve_received_state[parent_id].call();
138 delete that._resolve_received_state[parent_id];
139 }
140 }).catch(utils.reject("Couldn't resolve state request promise.", true));
132 141 break;
133 142 case 'custom':
134 143 this.trigger('msg:custom', msg.content.data.content);
135 144 break;
136 145 case 'display':
137 146 this.widget_manager.display_view(msg, this)
138 147 .catch(utils.reject('Could not display view.', true));
139 148 break;
140 149 }
141 150 },
142 151
143 152 set_state: function (state) {
144 153 var that = this;
145 154 // Handle when a widget is updated via the python side.
146 155 return this._unpack_models(state).then(function(state) {
147 156 that.state_lock = state;
148 157 try {
149 158 WidgetModel.__super__.set.call(that, state);
150 159 } finally {
151 160 that.state_lock = null;
152 161 }
153
154 if (that._resolve_received_state !== undefined) {
155 that._resolve_received_state();
156 }
157 return Promise.resolve();
158 162 }, utils.reject("Couldn't set model state", true));
159 163 },
160 164
161 165 get_state: function() {
162 166 // Get the serializable state of the model.
163 167 state = this.toJSON();
164 168 for (var key in state) {
165 169 if (state.hasOwnProperty(key)) {
166 170 state[key] = this._pack_models(state[key]);
167 171 }
168 172 }
169 173 return state;
170 174 },
171 175
172 176 _handle_status: function (msg, callbacks) {
173 177 /**
174 178 * Handle status msgs.
175 179 *
176 180 * execution_state : ('busy', 'idle', 'starting')
177 181 */
178 182 if (this.comm !== undefined) {
179 183 if (msg.content.execution_state ==='idle') {
180 184 // Send buffer if this message caused another message to be
181 185 // throttled.
182 186 if (this.msg_buffer !== null &&
183 187 (this.get('msg_throttle') || 3) === this.pending_msgs) {
184 188 var data = {method: 'backbone', sync_method: 'update', sync_data: this.msg_buffer};
185 189 this.comm.send(data, callbacks);
186 190 this.msg_buffer = null;
187 191 } else {
188 192 --this.pending_msgs;
189 193 }
190 194 }
191 195 }
192 196 },
193 197
194 198 callbacks: function(view) {
195 199 /**
196 200 * Create msg callbacks for a comm msg.
197 201 */
198 202 var callbacks = this.widget_manager.callbacks(view);
199 203
200 204 if (callbacks.iopub === undefined) {
201 205 callbacks.iopub = {};
202 206 }
203 207
204 208 var that = this;
205 209 callbacks.iopub.status = function (msg) {
206 210 that._handle_status(msg, callbacks);
207 211 };
208 212 return callbacks;
209 213 },
210 214
211 215 set: function(key, val, options) {
212 216 /**
213 217 * Set a value.
214 218 */
215 219 var return_value = WidgetModel.__super__.set.apply(this, arguments);
216 220
217 221 // Backbone only remembers the diff of the most recent set()
218 222 // operation. Calling set multiple times in a row results in a
219 223 // loss of diff information. Here we keep our own running diff.
220 224 this._buffered_state_diff = $.extend(this._buffered_state_diff, this.changedAttributes() || {});
221 225 return return_value;
222 226 },
223 227
224 228 sync: function (method, model, options) {
225 229 /**
226 230 * Handle sync to the back-end. Called when a model.save() is called.
227 231 *
228 232 * Make sure a comm exists.
229 233 */
230 234 var error = options.error || function() {
231 235 console.error('Backbone sync error:', arguments);
232 236 };
233 237 if (this.comm === undefined) {
234 238 error();
235 239 return false;
236 240 }
237 241
238 242 // Delete any key value pairs that the back-end already knows about.
239 243 var attrs = (method === 'patch') ? options.attrs : model.toJSON(options);
240 244 if (this.state_lock !== null) {
241 245 var keys = Object.keys(this.state_lock);
242 246 for (var i=0; i<keys.length; i++) {
243 247 var key = keys[i];
244 248 if (attrs[key] === this.state_lock[key]) {
245 249 delete attrs[key];
246 250 }
247 251 }
248 252 }
249 253
250 254 // Only sync if there are attributes to send to the back-end.
251 255 attrs = this._pack_models(attrs);
252 256 if (_.size(attrs) > 0) {
253 257
254 258 // If this message was sent via backbone itself, it will not
255 259 // have any callbacks. It's important that we create callbacks
256 260 // so we can listen for status messages, etc...
257 261 var callbacks = options.callbacks || this.callbacks();
258 262
259 263 // Check throttle.
260 264 if (this.pending_msgs >= (this.get('msg_throttle') || 3)) {
261 265 // The throttle has been exceeded, buffer the current msg so
262 266 // it can be sent once the kernel has finished processing
263 267 // some of the existing messages.
264 268
265 269 // Combine updates if it is a 'patch' sync, otherwise replace updates
266 270 switch (method) {
267 271 case 'patch':
268 272 this.msg_buffer = $.extend(this.msg_buffer || {}, attrs);
269 273 break;
270 274 case 'update':
271 275 case 'create':
272 276 this.msg_buffer = attrs;
273 277 break;
274 278 default:
275 279 error();
276 280 return false;
277 281 }
278 282 this.msg_buffer_callbacks = callbacks;
279 283
280 284 } else {
281 285 // We haven't exceeded the throttle, send the message like
282 286 // normal.
283 287 var data = {method: 'backbone', sync_data: attrs};
284 288 this.comm.send(data, callbacks);
285 289 this.pending_msgs++;
286 290 }
287 291 }
288 292 // Since the comm is a one-way communication, assume the message
289 293 // arrived. Don't call success since we don't have a model back from the server
290 294 // this means we miss out on the 'sync' event.
291 295 this._buffered_state_diff = {};
292 296 },
293 297
294 298 save_changes: function(callbacks) {
295 299 /**
296 300 * Push this model's state to the back-end
297 301 *
298 302 * This invokes a Backbone.Sync.
299 303 */
300 304 this.save(this._buffered_state_diff, {patch: true, callbacks: callbacks});
301 305 },
302 306
303 307 _pack_models: function(value) {
304 308 /**
305 309 * Replace models with model ids recursively.
306 310 */
307 311 var that = this;
308 312 var packed;
309 313 if (value instanceof Backbone.Model) {
310 314 return "IPY_MODEL_" + value.id;
311 315
312 316 } else if ($.isArray(value)) {
313 317 packed = [];
314 318 _.each(value, function(sub_value, key) {
315 319 packed.push(that._pack_models(sub_value));
316 320 });
317 321 return packed;
318 322 } else if (value instanceof Date || value instanceof String) {
319 323 return value;
320 324 } else if (value instanceof Object) {
321 325 packed = {};
322 326 _.each(value, function(sub_value, key) {
323 327 packed[key] = that._pack_models(sub_value);
324 328 });
325 329 return packed;
326 330
327 331 } else {
328 332 return value;
329 333 }
330 334 },
331 335
332 336 _unpack_models: function(value) {
333 337 /**
334 338 * Replace model ids with models recursively.
335 339 */
336 340 var that = this;
337 341 var unpacked;
338 342 if ($.isArray(value)) {
339 343 unpacked = [];
340 344 _.each(value, function(sub_value, key) {
341 345 unpacked.push(that._unpack_models(sub_value));
342 346 });
343 347 return Promise.all(unpacked);
344 348 } else if (value instanceof Object) {
345 349 unpacked = {};
346 350 _.each(value, function(sub_value, key) {
347 351 unpacked[key] = that._unpack_models(sub_value);
348 352 });
349 353 return utils.resolve_promises_dict(unpacked);
350 354 } else if (typeof value === 'string' && value.slice(0,10) === "IPY_MODEL_") {
351 355 // get_model returns a promise already
352 356 return this.widget_manager.get_model(value.slice(10, value.length));
353 357 } else {
354 358 return Promise.resolve(value);
355 359 }
356 360 },
357 361
358 362 on_some_change: function(keys, callback, context) {
359 363 /**
360 364 * on_some_change(["key1", "key2"], foo, context) differs from
361 365 * on("change:key1 change:key2", foo, context).
362 366 * If the widget attributes key1 and key2 are both modified,
363 367 * the second form will result in foo being called twice
364 368 * while the first will call foo only once.
365 369 */
366 370 this.on('change', function() {
367 371 if (keys.some(this.hasChanged, this)) {
368 372 callback.apply(context);
369 373 }
370 374 }, this);
371 375
372 376 },
373 377 });
374 378 widgetmanager.WidgetManager.register_widget_model('WidgetModel', WidgetModel);
375 379
376 380
377 381 var WidgetView = Backbone.View.extend({
378 382 initialize: function(parameters) {
379 383 /**
380 384 * Public constructor.
381 385 */
382 386 this.model.on('change',this.update,this);
383 387 this.options = parameters.options;
384 388 this.on('displayed', function() {
385 389 this.is_displayed = true;
386 390 }, this);
387 391 this.on('remove', function() {
388 392 delete this.model.views[this.id];
389 393 }, this);
390 394 },
391 395
392 396 update: function(){
393 397 /**
394 398 * Triggered on model change.
395 399 *
396 400 * Update view to be consistent with this.model
397 401 */
398 402 },
399 403
400 404 create_child_view: function(child_model, options) {
401 405 /**
402 406 * Create and promise that resolves to a child view of a given model
403 407 */
404 408 var that = this;
405 409 options = $.extend({ parent: this }, options || {});
406 410 return this.model.widget_manager.create_view(child_model, options).catch(utils.reject("Couldn't create child view"), true);
407 411 },
408 412
409 413 callbacks: function(){
410 414 /**
411 415 * Create msg callbacks for a comm msg.
412 416 */
413 417 return this.model.callbacks(this);
414 418 },
415 419
416 420 render: function(){
417 421 /**
418 422 * Render the view.
419 423 *
420 424 * By default, this is only called the first time the view is created
421 425 */
422 426 },
423 427
424 428 show: function(){
425 429 /**
426 430 * Show the widget-area
427 431 */
428 432 if (this.options && this.options.cell &&
429 433 this.options.cell.widget_area !== undefined) {
430 434 this.options.cell.widget_area.show();
431 435 }
432 436 },
433 437
434 438 send: function (content) {
435 439 /**
436 440 * Send a custom msg associated with this view.
437 441 */
438 442 this.model.send(content, this.callbacks());
439 443 },
440 444
441 445 touch: function () {
442 446 this.model.save_changes(this.callbacks());
443 447 },
444 448
445 449 after_displayed: function (callback, context) {
446 450 /**
447 451 * Calls the callback right away is the view is already displayed
448 452 * otherwise, register the callback to the 'displayed' event.
449 453 */
450 454 if (this.is_displayed) {
451 455 callback.apply(context);
452 456 } else {
453 457 this.on('displayed', callback, context);
454 458 }
455 459 },
456 460
457 461 remove: function () {
458 462 // Raise a remove event when the view is removed.
459 463 WidgetView.__super__.remove.apply(this, arguments);
460 464 this.trigger('remove');
461 465 }
462 466 });
463 467
464 468
465 469 var DOMWidgetView = WidgetView.extend({
466 470 initialize: function (parameters) {
467 471 /**
468 472 * Public constructor
469 473 */
470 474 DOMWidgetView.__super__.initialize.apply(this, [parameters]);
471 475 this.on('displayed', this.show, this);
472 476 this.model.on('change:visible', this.update_visible, this);
473 477 this.model.on('change:_css', this.update_css, this);
474 478
475 479 this.model.on('change:_dom_classes', function(model, new_classes) {
476 480 var old_classes = model.previous('_dom_classes');
477 481 this.update_classes(old_classes, new_classes);
478 482 }, this);
479 483
480 484 this.model.on('change:color', function (model, value) {
481 485 this.update_attr('color', value); }, this);
482 486
483 487 this.model.on('change:background_color', function (model, value) {
484 488 this.update_attr('background', value); }, this);
485 489
486 490 this.model.on('change:width', function (model, value) {
487 491 this.update_attr('width', value); }, this);
488 492
489 493 this.model.on('change:height', function (model, value) {
490 494 this.update_attr('height', value); }, this);
491 495
492 496 this.model.on('change:border_color', function (model, value) {
493 497 this.update_attr('border-color', value); }, this);
494 498
495 499 this.model.on('change:border_width', function (model, value) {
496 500 this.update_attr('border-width', value); }, this);
497 501
498 502 this.model.on('change:border_style', function (model, value) {
499 503 this.update_attr('border-style', value); }, this);
500 504
501 505 this.model.on('change:font_style', function (model, value) {
502 506 this.update_attr('font-style', value); }, this);
503 507
504 508 this.model.on('change:font_weight', function (model, value) {
505 509 this.update_attr('font-weight', value); }, this);
506 510
507 511 this.model.on('change:font_size', function (model, value) {
508 512 this.update_attr('font-size', this._default_px(value)); }, this);
509 513
510 514 this.model.on('change:font_family', function (model, value) {
511 515 this.update_attr('font-family', value); }, this);
512 516
513 517 this.model.on('change:padding', function (model, value) {
514 518 this.update_attr('padding', value); }, this);
515 519
516 520 this.model.on('change:margin', function (model, value) {
517 521 this.update_attr('margin', this._default_px(value)); }, this);
518 522
519 523 this.model.on('change:border_radius', function (model, value) {
520 524 this.update_attr('border-radius', this._default_px(value)); }, this);
521 525
522 526 this.after_displayed(function() {
523 527 this.update_visible(this.model, this.model.get("visible"));
524 528 this.update_classes([], this.model.get('_dom_classes'));
525 529
526 530 this.update_attr('color', this.model.get('color'));
527 531 this.update_attr('background', this.model.get('background_color'));
528 532 this.update_attr('width', this.model.get('width'));
529 533 this.update_attr('height', this.model.get('height'));
530 534 this.update_attr('border-color', this.model.get('border_color'));
531 535 this.update_attr('border-width', this.model.get('border_width'));
532 536 this.update_attr('border-style', this.model.get('border_style'));
533 537 this.update_attr('font-style', this.model.get('font_style'));
534 538 this.update_attr('font-weight', this.model.get('font_weight'));
535 539 this.update_attr('font-size', this.model.get('font_size'));
536 540 this.update_attr('font-family', this.model.get('font_family'));
537 541 this.update_attr('padding', this.model.get('padding'));
538 542 this.update_attr('margin', this.model.get('margin'));
539 543 this.update_attr('border-radius', this.model.get('border_radius'));
540 544
541 545 this.update_css(this.model, this.model.get("_css"));
542 546 }, this);
543 547 },
544 548
545 549 _default_px: function(value) {
546 550 /**
547 551 * Makes browser interpret a numerical string as a pixel value.
548 552 */
549 553 if (/^\d+\.?(\d+)?$/.test(value.trim())) {
550 554 return value.trim() + 'px';
551 555 }
552 556 return value;
553 557 },
554 558
555 559 update_attr: function(name, value) {
556 560 /**
557 561 * Set a css attr of the widget view.
558 562 */
559 563 this.$el.css(name, value);
560 564 },
561 565
562 566 update_visible: function(model, value) {
563 567 /**
564 568 * Update visibility
565 569 */
566 570 this.$el.toggle(value);
567 571 },
568 572
569 573 update_css: function (model, css) {
570 574 /**
571 575 * Update the css styling of this view.
572 576 */
573 577 var e = this.$el;
574 578 if (css === undefined) {return;}
575 579 for (var i = 0; i < css.length; i++) {
576 580 // Apply the css traits to all elements that match the selector.
577 581 var selector = css[i][0];
578 582 var elements = this._get_selector_element(selector);
579 583 if (elements.length > 0) {
580 584 var trait_key = css[i][1];
581 585 var trait_value = css[i][2];
582 586 elements.css(trait_key ,trait_value);
583 587 }
584 588 }
585 589 },
586 590
587 591 update_classes: function (old_classes, new_classes, $el) {
588 592 /**
589 593 * Update the DOM classes applied to an element, default to this.$el.
590 594 */
591 595 if ($el===undefined) {
592 596 $el = this.$el;
593 597 }
594 598 _.difference(old_classes, new_classes).map(function(c) {$el.removeClass(c);})
595 599 _.difference(new_classes, old_classes).map(function(c) {$el.addClass(c);})
596 600 },
597 601
598 602 update_mapped_classes: function(class_map, trait_name, previous_trait_value, $el) {
599 603 /**
600 604 * Update the DOM classes applied to the widget based on a single
601 605 * trait's value.
602 606 *
603 607 * Given a trait value classes map, this function automatically
604 608 * handles applying the appropriate classes to the widget element
605 609 * and removing classes that are no longer valid.
606 610 *
607 611 * Parameters
608 612 * ----------
609 613 * class_map: dictionary
610 614 * Dictionary of trait values to class lists.
611 615 * Example:
612 616 * {
613 617 * success: ['alert', 'alert-success'],
614 618 * info: ['alert', 'alert-info'],
615 619 * warning: ['alert', 'alert-warning'],
616 620 * danger: ['alert', 'alert-danger']
617 621 * };
618 622 * trait_name: string
619 623 * Name of the trait to check the value of.
620 624 * previous_trait_value: optional string, default ''
621 625 * Last trait value
622 626 * $el: optional jQuery element handle, defaults to this.$el
623 627 * Element that the classes are applied to.
624 628 */
625 629 var key = previous_trait_value;
626 630 if (key === undefined) {
627 631 key = this.model.previous(trait_name);
628 632 }
629 633 var old_classes = class_map[key] ? class_map[key] : [];
630 634 key = this.model.get(trait_name);
631 635 var new_classes = class_map[key] ? class_map[key] : [];
632 636
633 637 this.update_classes(old_classes, new_classes, $el || this.$el);
634 638 },
635 639
636 640 _get_selector_element: function (selector) {
637 641 /**
638 642 * Get the elements via the css selector.
639 643 */
640 644 var elements;
641 645 if (!selector) {
642 646 elements = this.$el;
643 647 } else {
644 648 elements = this.$el.find(selector).addBack(selector);
645 649 }
646 650 return elements;
647 651 },
648 652
649 653 typeset: function(element, text){
650 654 utils.typeset.apply(null, arguments);
651 655 },
652 656 });
653 657
654 658
655 659 var ViewList = function(create_view, remove_view, context) {
656 660 /**
657 661 * - create_view and remove_view are default functions called when adding or removing views
658 662 * - create_view takes a model and returns a view or a promise for a view for that model
659 663 * - remove_view takes a view and destroys it (including calling `view.remove()`)
660 664 * - each time the update() function is called with a new list, the create and remove
661 665 * callbacks will be called in an order so that if you append the views created in the
662 666 * create callback and remove the views in the remove callback, you will duplicate
663 667 * the order of the list.
664 668 * - the remove callback defaults to just removing the view (e.g., pass in null for the second parameter)
665 669 * - the context defaults to the created ViewList. If you pass another context, the create and remove
666 670 * will be called in that context.
667 671 */
668 672
669 673 this.initialize.apply(this, arguments);
670 674 };
671 675
672 676 _.extend(ViewList.prototype, {
673 677 initialize: function(create_view, remove_view, context) {
674 678 this.state_change = Promise.resolve();
675 679 this._handler_context = context || this;
676 680 this._models = [];
677 681 this.views = [];
678 682 this._create_view = create_view;
679 683 this._remove_view = remove_view || function(view) {view.remove();};
680 684 },
681 685
682 686 update: function(new_models, create_view, remove_view, context) {
683 687 /**
684 688 * the create_view, remove_view, and context arguments override the defaults
685 689 * specified when the list is created.
686 690 * returns a promise that resolves after this update is done
687 691 */
688 692 var remove = remove_view || this._remove_view;
689 693 var create = create_view || this._create_view;
690 694 if (create === undefined || remove === undefined){
691 695 console.error("Must define a create a remove function");
692 696 }
693 697 var context = context || this._handler_context;
694 698 var added_views = [];
695 699 var that = this;
696 700 this.state_change = this.state_change.then(function() {
697 701 var i;
698 702 // first, skip past the beginning of the lists if they are identical
699 703 for (i = 0; i < new_models.length; i++) {
700 704 if (i >= that._models.length || new_models[i] !== that._models[i]) {
701 705 break;
702 706 }
703 707 }
704 708 var first_removed = i;
705 709 // Remove the non-matching items from the old list.
706 710 for (var j = first_removed; j < that._models.length; j++) {
707 711 remove.call(context, that.views[j]);
708 712 }
709 713
710 714 // Add the rest of the new list items.
711 715 for (; i < new_models.length; i++) {
712 716 added_views.push(create.call(context, new_models[i]));
713 717 }
714 718 // make a copy of the input array
715 719 that._models = new_models.slice();
716 720 return Promise.all(added_views).then(function(added) {
717 721 Array.prototype.splice.apply(that.views, [first_removed, that.views.length].concat(added));
718 722 return that.views;
719 723 });
720 724 });
721 725 return this.state_change;
722 726 },
723 727
724 728 remove: function() {
725 729 /**
726 730 * removes every view in the list; convenience function for `.update([])`
727 731 * that should be faster
728 732 * returns a promise that resolves after this removal is done
729 733 */
730 734 var that = this;
731 735 this.state_change = this.state_change.then(function() {
732 736 for (var i = 0; i < that.views.length; i++) {
733 737 that._remove_view.call(that._handler_context, that.views[i]);
734 738 }
735 739 that._models = [];
736 740 that.views = [];
737 741 });
738 742 return this.state_change;
739 743 },
740 744 });
741 745
742 746 var widget = {
743 747 'WidgetModel': WidgetModel,
744 748 'WidgetView': WidgetView,
745 749 'DOMWidgetView': DOMWidgetView,
746 750 'ViewList': ViewList,
747 751 };
748 752
749 753 // For backwards compatability.
750 754 $.extend(IPython, widget);
751 755
752 756 return widget;
753 757 });
General Comments 0
You need to be logged in to leave comments. Login now