##// END OF EJS Templates
Rewrite widget syncing...
Jason Grout -
Show More
@@ -1,205 +1,188
1 1 //----------------------------------------------------------------------------
2 2 // Copyright (C) 2013 The IPython Development Team
3 3 //
4 4 // Distributed under the terms of the BSD License. The full license is in
5 5 // the file COPYING, distributed as part of this software.
6 6 //----------------------------------------------------------------------------
7 7
8 8 //============================================================================
9 9 // WidgetModel, WidgetView, and WidgetManager
10 10 //============================================================================
11 11 /**
12 12 * Base Widget classes
13 13 * @module IPython
14 14 * @namespace IPython
15 15 * @submodule widget
16 16 */
17 17
18 18 (function () {
19 19 "use strict";
20 20
21 21 // Use require.js 'define' method so that require.js is intelligent enough to
22 22 // syncronously load everything within this file when it is being 'required'
23 23 // elsewhere.
24 24 define(["underscore",
25 25 "backbone",
26 ], function (Underscore, Backbone) {
27
28 Backbone.sync = function (method, model, options) {
29 // Sync widget models to back-end.
30 //
31 // Backbone.sync method must be in widgetmanager.js file instead of
32 // widget.js so it can be overwritten for different contexts.
33 var result = model._handle_sync(method, options);
34 if (options.success) {
35 options.success(result);
36 }
37 };
38
39 26
40 27 //--------------------------------------------------------------------
41 28 // WidgetManager class
42 29 //--------------------------------------------------------------------
43 30 var WidgetManager = function (comm_manager) {
44 31 // Public constructor
45 32 WidgetManager._managers.push(this);
46 33
47 34 // Attach a comm manager to the
48 35 this.comm_manager = comm_manager;
49 36
50 37 // Register already-registered widget model types with the comm manager.
51 38 for (var name in WidgetManager._model_types) {
52 39 if (WidgetManager._model_types.hasOwnProperty(name)) {
53 40 this.comm_manager.register_target(name, $.proxy(this._handle_comm_open, this));
54 41
55 42 }
56 43 }
57 44 };
58 45
59 46 //--------------------------------------------------------------------
60 47 // Class level
61 48 //--------------------------------------------------------------------
62 49 WidgetManager._model_types = {}; /* Dictionary of model type names (target_name) and model types. */
63 50 WidgetManager._view_types = {}; /* Dictionary of view names and view types. */
64 51 WidgetManager._models = {}; /* Dictionary of model ids and model instances */
65 52 WidgetManager._managers = []; /* List of widget managers */
66 53
67 54 WidgetManager.register_widget_model = function (model_name, model_type) {
68 55 // Registers a widget model by name.
69 56 WidgetManager._model_types[model_name] = model_type;
70 57
71 58 // Register the widget with the comm manager. Make sure to pass this object's context
72 59 // in so `this` works in the call back.
73 60 for (var i = 0; i < WidgetManager._managers.length; i++) {
74 61 var instance = WidgetManager._managers[i];
75 62 if (instance.comm_manager !== null) {
76 63 instance.comm_manager.register_target(model_name, $.proxy(instance._handle_comm_open, instance));
77 64 }
78 65 }
79 66 };
80 67
81 68 WidgetManager.register_widget_view = function (view_name, view_type) {
82 69 // Registers a widget view by name.
83 70 WidgetManager._view_types[view_name] = view_type;
84 71 };
85 72
86 73 //--------------------------------------------------------------------
87 74 // Instance level
88 75 //--------------------------------------------------------------------
89 76 WidgetManager.prototype.display_view = function(msg, model) {
90 77 var cell = this.get_msg_cell(msg.parent_header.msg_id);
91 78 if (cell === null) {
92 79 console.log("Could not determine where the display" +
93 80 " message was from. Widget will not be displayed");
94 81 } else {
95 82 var view = this.create_view(model, {cell: cell});
96 83 if (view === undefined) {
97 84 console.error("View creation failed", model);
98 85 }
99 86 if (cell.widget_subarea !== undefined
100 87 && cell.widget_subarea !== null) {
101 88
102 89 cell.widget_area.show();
103 90 cell.widget_subarea.append(view.$el);
104 91 }
105 92 }
106 93 },
107 94
108 95 WidgetManager.prototype.create_view = function(model, options) {
109 96 var view_name = model.get('view_name');
110 97 var ViewType = WidgetManager._view_types[view_name];
111 98 if (ViewType !== undefined && ViewType !== null) {
112 99 var parameters = {model: model, options: options};
113 100 var view = new ViewType(parameters);
114 101 view.render();
115 102 IPython.keyboard_manager.register_events(view.$el);
116 103 model.views.push(view);
117 104 model.on('destroy', view.remove, view);
118 105 return view;
119 106 }
120 107 },
121 108
122 109 WidgetManager.prototype.get_msg_cell = function (msg_id) {
123 110 var cell = null;
124 111 // First, check to see if the msg was triggered by cell execution.
125 112 if (IPython.notebook !== undefined && IPython.notebook !== null) {
126 113 cell = IPython.notebook.get_msg_cell(msg_id);
127 114 }
128 115 if (cell !== null) {
129 116 return cell
130 117 }
131 118 // Second, check to see if a get_cell callback was defined
132 119 // for the message. get_cell callbacks are registered for
133 120 // widget messages, so this block is actually checking to see if the
134 121 // message was triggered by a widget.
135 122 var kernel = this.comm_manager.kernel;
136 123 if (kernel !== undefined && kernel !== null) {
137 124 var callbacks = kernel.get_callbacks_for_msg(msg_id);
138 125 if (callbacks !== undefined &&
139 126 callbacks.iopub !== undefined &&
140 127 callbacks.iopub.get_cell !== undefined) {
141 128
142 129 return callbacks.iopub.get_cell();
143 130 }
144 131 }
145 132
146 133 // Not triggered by a cell or widget (no get_cell callback
147 134 // exists).
148 135 return null;
149 136 };
150 137
151 138 WidgetManager.prototype.callbacks = function (view) {
152 139 // callback handlers specific a view
153 140 var callbacks = {};
154 141 var cell = view.options.cell;
155 142 if (cell !== null) {
156 143 // Try to get output handlers
157 144 var handle_output = null;
158 145 var handle_clear_output = null;
159 146 if (cell.output_area !== undefined && cell.output_area !== null) {
160 147 handle_output = $.proxy(cell.output_area.handle_output, cell.output_area);
161 148 handle_clear_output = $.proxy(cell.output_area.handle_clear_output, cell.output_area);
162 149 }
163 150
164 151 // Create callback dict using what is known
165 152 var that = this;
166 153 callbacks = {
167 154 iopub : {
168 155 output : handle_output,
169 156 clear_output : handle_clear_output,
170 157
171 status : function (msg) {
172 view.model._handle_status(msg, that.callbacks(view));
173 },
174
175 158 // Special function only registered by widget messages.
176 159 // Allows us to get the cell for a message so we know
177 160 // where to add widgets if the code requires it.
178 161 get_cell : function () {
179 162 return cell;
180 163 },
181 164 },
182 165 };
183 166 }
184 167 return callbacks;
185 168 };
186 169
187 170 WidgetManager.prototype.get_model = function (model_id) {
188 171 var model = WidgetManager._models[model_id];
189 172 if (model !== undefined && model.id == model_id) {
190 173 return model;
191 174 }
192 175 return null;
193 176 };
194 177
195 178 WidgetManager.prototype._handle_comm_open = function (comm, msg) {
196 179 var model_id = comm.comm_id;
197 180 var widget_type_name = msg.content.target_name;
198 181 var widget_model = new WidgetManager._model_types[widget_type_name](this, model_id, comm);
199 182 WidgetManager._models[model_id] = widget_model;
200 183 };
201 184
202 185 IPython.WidgetManager = WidgetManager;
203 186 return IPython.WidgetManager;
204 187 });
205 188 }());
@@ -1,392 +1,406
1 1 //----------------------------------------------------------------------------
2 2 // Copyright (C) 2013 The IPython Development Team
3 3 //
4 4 // Distributed under the terms of the BSD License. The full license is in
5 5 // the file COPYING, distributed as part of this software.
6 6 //----------------------------------------------------------------------------
7 7
8 8 //============================================================================
9 9 // Base Widget Model and View classes
10 10 //============================================================================
11 11
12 12 /**
13 13 * @module IPython
14 14 * @namespace IPython
15 15 **/
16 16
17 17 define(["notebook/js/widgetmanager",
18 18 "underscore",
19 19 "backbone"],
20 20 function(WidgetManager, Underscore, Backbone){
21 21
22 22 var WidgetModel = Backbone.Model.extend({
23 23 constructor: function (widget_manager, model_id, comm) {
24 24 // Construcctor
25 25 //
26 26 // Creates a WidgetModel instance.
27 27 //
28 28 // Parameters
29 29 // ----------
30 30 // widget_manager : WidgetManager instance
31 31 // model_id : string
32 32 // An ID unique to this model.
33 33 // comm : Comm instance (optional)
34 34 this.widget_manager = widget_manager;
35 35 this.pending_msgs = 0;
36 36 this.msg_throttle = 2;
37 37 this.msg_buffer = null;
38 38 this.key_value_lock = null;
39 39 this.id = model_id;
40 40 this.views = [];
41 41
42 42 if (comm !== undefined) {
43 43 // Remember comm associated with the model.
44 44 this.comm = comm;
45 45 comm.model = this;
46 46
47 47 // Hook comm messages up to model.
48 48 comm.on_close($.proxy(this._handle_comm_closed, this));
49 49 comm.on_msg($.proxy(this._handle_comm_msg, this));
50 50 }
51 51 return Backbone.Model.apply(this);
52 52 },
53 53
54 54 send: function (content, callbacks) {
55 55 // Send a custom msg over the comm.
56 56 if (this.comm !== undefined) {
57 57 var data = {method: 'custom', custom_content: content};
58 58 this.comm.send(data, callbacks);
59 59 }
60 60 },
61 61
62 62 _handle_comm_closed: function (msg) {
63 63 // Handle when a widget is closed.
64 64 this.trigger('comm:close');
65 65 delete this.comm.model; // Delete ref so GC will collect widget model.
66 66 delete this.comm;
67 67 delete this.model_id; // Delete id from model so widget manager cleans up.
68 68 // TODO: Handle deletion, like this.destroy(), and delete views, etc.
69 69 },
70 70
71 71 _handle_comm_msg: function (msg) {
72 72 // Handle incoming comm msg.
73 73 var method = msg.content.data.method;
74 74 switch (method) {
75 75 case 'update':
76 76 this.apply_update(msg.content.data.state);
77 77 break;
78 78 case 'custom':
79 79 this.trigger('msg:custom', msg.content.data.custom_content);
80 80 break;
81 81 case 'display':
82 82 this.widget_manager.display_view(msg, this);
83 83 break;
84 84 }
85 85 },
86 86
87 87 apply_update: function (state) {
88 88 // Handle when a widget is updated via the python side.
89 89 for (var key in state) {
90 90 if (state.hasOwnProperty(key)) {
91 91 var value = state[key];
92 92 this.key_value_lock = [key, value];
93 93 try {
94 94 this.set(key, this._unpack_models(value));
95 95 } finally {
96 96 this.key_value_lock = null;
97 97 }
98 98 }
99 99 }
100 100 //TODO: are there callbacks that make sense in this case? If so, attach them here as an option
101 101 },
102 102
103 103 _handle_status: function (msg, callbacks) {
104 104 // Handle status msgs.
105 105
106 106 // execution_state : ('busy', 'idle', 'starting')
107 107 if (this.comm !== undefined) {
108 108 if (msg.content.execution_state ==='idle') {
109 109 // Send buffer if this message caused another message to be
110 110 // throttled.
111 111 if (this.msg_buffer !== null &&
112 112 this.msg_throttle === this.pending_msgs) {
113 113 var data = {method: 'backbone', sync_method: 'update', sync_data: this.msg_buffer};
114 114 this.comm.send(data, callbacks);
115 115 this.msg_buffer = null;
116 116 } else {
117 117 --this.pending_msgs;
118 118 }
119 119 }
120 120 }
121 121 },
122 122
123 _handle_sync: function (method, options) {
124 // Custom syncronization logic.
125 var model_json = this.toJSON();
126 var attr;
127
128 // Only send updated state if the state hasn't been changed
129 // during an update.
130 if (this.comm !== undefined) {
131 if (this.pending_msgs >= this.msg_throttle) {
132 // The throttle has been exceeded, buffer the current msg so
133 // it can be sent once the kernel has finished processing
134 // some of the existing messages.
135 if (this.msg_buffer === null) {
136 this.msg_buffer = $.extend({}, model_json); // Copy
137 }
138 for (attr in options.attrs) {
139 var value = this._pack_models(options.attrs[attr]);
140 if (this.key_value_lock === null || attr !== this.key_value_lock[0] || value !== this.key_value_lock[1]) {
141 this.msg_buffer[attr] = value;
142 }
143 }
123 callbacks: function(callbacks) {
124 // Create msg callbacks for a comm msg.
125 var that = this;
126 if (callbacks.iopub === undefined) {callbacks.iopub = {};}
127 callbacks.iopub.status = function (msg) {
128 that._handle_status(msg, callbacks);
129 }
130 return callbacks;
131 },
144 132
145 } else {
146 // We haven't exceeded the throttle, send the message like
147 // normal. If this is a patch operation, just send the
148 // changes.
149 var send_json = model_json;
150 send_json = {};
151 for (attr in options.attrs) {
152 var value = this._pack_models(options.attrs[attr]);
153 if (this.key_value_lock === null || attr !== this.key_value_lock[0] || value !== this.key_value_lock[1]) {
154 send_json[attr] = value;
155 }
156 }
157
158 var is_empty = true;
159 for (var prop in send_json) if (send_json.hasOwnProperty(prop)) is_empty = false;
160 if (!is_empty) {
161 ++this.pending_msgs;
162 var data = {method: 'backbone', sync_data: send_json};
163 this.comm.send(data, options.callbacks);
164 }
133 sync: function (method, model, options) {
134 var error = options.error || function() {console.error('Backbone sync error:', arguments);}
135 if (this.comm === undefined) {
136 error();
137 return false;
138 }
139
140 var attrs = (method==='patch') ? options.attrs : model.toJSON(options);
141
142 if (this.key_value_lock !== null) {
143 var k = this.key_value_lock[0];
144 var v = this.key_value_lock[1];
145 if (attrs[k]===v) {
146 delete attrs[k];
165 147 }
166 148 }
149 if (_.size(attrs) == 0) {
150 error();
151 return false;
152 }
153 var callbacks = model.callbacks(options.callbacks || {});
154 if (this.pending_msgs >= this.msg_throttle) {
155 // The throttle has been exceeded, buffer the current msg so
156 // it can be sent once the kernel has finished processing
157 // some of the existing messages.
158
159 // combine updates if it is a 'patch' sync, otherwise replace updates
160 switch (method) {
161 case 'patch':
162 this.msg_buffer = _.extend(this.msg_buffer || {}, attrs);
163 break;
164 case 'update':
165 this.msg_buffer = attrs;
166 break;
167 default:
168 error();
169 return false;
170 }
171 this.msg_buffer_callbacks = callbacks;
172
173 } else {
174 // We haven't exceeded the throttle, send the message like
175 // normal. If this is a patch operation, just send the
176 // changes.
177 var data = {method: 'backbone', sync_data: attrs};
178 this.comm.send(data, callbacks);
179 this.pending_msgs++;
180 }
167 181
168 182 // Since the comm is a one-way communication, assume the message
169 // arrived.
170 return model_json;
183 // arrived. Don't call success since we don't have a model back from the server
184 // this means we miss out on the 'sync' event.
171 185 },
172 186
173 push: function(callbacks) {
187 save_changes: function(callbacks) {
174 188 // Push this model's state to the back-end
175 189 //
176 190 // This invokes a Backbone.Sync.
177 191 this.save(this.changedAttributes(), {patch: true, callbacks: callbacks});
178 192 },
179 193
180 194 _pack_models: function(value) {
181 195 // Replace models with model ids recursively.
182 196 if (value instanceof Backbone.Model) {
183 197 return value.id;
184 198 } else if (value instanceof Object) {
185 199 var packed = {};
186 200 for (var key in value) {
187 201 packed[key] = this._pack_models(value[key]);
188 202 }
189 203 return packed;
190 204 } else {
191 205 return value;
192 206 }
193 207 },
194 208
195 209 _unpack_models: function(value) {
196 210 // Replace model ids with models recursively.
197 211 if (value instanceof Object) {
198 212 var unpacked = {};
199 213 for (var key in value) {
200 214 unpacked[key] = this._unpack_models(value[key]);
201 215 }
202 216 return unpacked;
203 217 } else {
204 218 var model = this.widget_manager.get_model(value);
205 219 if (model !== null) {
206 220 return model;
207 221 } else {
208 222 return value;
209 223 }
210 224 }
211 225 },
212 226
213 227 });
214 228 WidgetManager.register_widget_model('WidgetModel', WidgetModel);
215 229
216 230
217 231 var WidgetView = Backbone.View.extend({
218 232 initialize: function(parameters) {
219 233 // Public constructor.
220 234 this.model.on('change',this.update,this);
221 235 this.options = parameters.options;
222 236 this.child_views = [];
223 237 this.model.views.push(this);
224 238 },
225 239
226 240 update: function(){
227 241 // Triggered on model change.
228 242 //
229 243 // Update view to be consistent with this.model
230 244 },
231 245
232 246 create_child_view: function(child_model, options) {
233 247 // Create and return a child view.
234 248 //
235 249 // -given a model and (optionally) a view name if the view name is
236 250 // not given, it defaults to the model's default view attribute.
237 251
238 252 // TODO: this is hacky, and makes the view depend on this cell attribute and widget manager behavior
239 253 // it would be great to have the widget manager add the cell metadata
240 254 // to the subview without having to add it here.
241 255 options = options || {};
242 256 options.cell = this.options.cell;
243 257 var child_view = this.model.widget_manager.create_view(child_model, options);
244 258 this.child_views[child_model.id] = child_view;
245 259 return child_view;
246 260 },
247 261
248 262 delete_child_view: function(child_model, options) {
249 263 // Delete a child view that was previously created using create_child_view.
250 264 var view = this.child_views[child_model.id];
251 265 delete this.child_views[child_model.id];
252 266 view.remove();
253 267 },
254 268
255 269 do_diff: function(old_list, new_list, removed_callback, added_callback) {
256 270 // Difference a changed list and call remove and add callbacks for
257 271 // each removed and added item in the new list.
258 272 //
259 273 // Parameters
260 274 // ----------
261 275 // old_list : array
262 276 // new_list : array
263 277 // removed_callback : Callback(item)
264 278 // Callback that is called for each item removed.
265 279 // added_callback : Callback(item)
266 280 // Callback that is called for each item added.
267 281
268 282
269 283 // removed items
270 284 _.each(_.difference(old_list, new_list), function(item, index, list) {
271 285 removed_callback(item);
272 286 }, this);
273 287
274 288 // added items
275 289 _.each(_.difference(new_list, old_list), function(item, index, list) {
276 290 added_callback(item);
277 291 }, this);
278 292 },
279 293
280 294 callbacks: function(){
281 295 // Create msg callbacks for a comm msg.
282 296 return this.model.widget_manager.callbacks(this);
283 297 },
284 298
285 299 render: function(){
286 300 // Render the view.
287 301 //
288 302 // By default, this is only called the first time the view is created
289 303 },
290 304
291 305 send: function (content) {
292 306 // Send a custom msg associated with this view.
293 307 this.model.send(content, this.callbacks());
294 308 },
295 309
296 310 touch: function () {
297 this.model.push(this.callbacks());
311 this.model.save_changes(this.callbacks());
298 312 },
299 313
300 314 });
301 315
302 316
303 317 var DOMWidgetView = WidgetView.extend({
304 318 initialize: function (options) {
305 319 // Public constructor
306 320
307 321 // In the future we may want to make changes more granular
308 322 // (e.g., trigger on visible:change).
309 323 this.model.on('change', this.update, this);
310 324 this.model.on('msg:custom', this.on_msg, this);
311 325 DOMWidgetView.__super__.initialize.apply(this, arguments);
312 326 },
313 327
314 328 on_msg: function(msg) {
315 329 // Handle DOM specific msgs.
316 330 switch(msg.msg_type) {
317 331 case 'add_class':
318 332 this.add_class(msg.selector, msg.class_list);
319 333 break;
320 334 case 'remove_class':
321 335 this.remove_class(msg.selector, msg.class_list);
322 336 break;
323 337 }
324 338 },
325 339
326 340 add_class: function (selector, class_list) {
327 341 // Add a DOM class to an element.
328 342 this._get_selector_element(selector).addClass(class_list);
329 343 },
330 344
331 345 remove_class: function (selector, class_list) {
332 346 // Remove a DOM class from an element.
333 347 this._get_selector_element(selector).removeClass(class_list);
334 348 },
335 349
336 350 update: function () {
337 351 // Update the contents of this view
338 352 //
339 353 // Called when the model is changed. The model may have been
340 354 // changed by another view or by a state update from the back-end.
341 355 // The very first update seems to happen before the element is
342 356 // finished rendering so we use setTimeout to give the element time
343 357 // to render
344 358 var e = this.$el;
345 359 var visible = this.model.get('visible');
346 360 setTimeout(function() {e.toggle(visible)},0);
347 361
348 362 var css = this.model.get('_css');
349 363 if (css === undefined) {return;}
350 364 for (var selector in css) {
351 365 if (css.hasOwnProperty(selector)) {
352 366 // Apply the css traits to all elements that match the selector.
353 367 var elements = this._get_selector_element(selector);
354 368 if (elements.length > 0) {
355 369 var css_traits = css[selector];
356 370 for (var css_key in css_traits) {
357 371 if (css_traits.hasOwnProperty(css_key)) {
358 372 elements.css(css_key, css_traits[css_key]);
359 373 }
360 374 }
361 375 }
362 376 }
363 377 }
364 378 },
365 379
366 380 _get_selector_element: function (selector) {
367 381 // Get the elements via the css selector.
368 382
369 383 // If the selector is blank, apply the style to the $el_to_style
370 384 // element. If the $el_to_style element is not defined, use apply
371 385 // the style to the view's element.
372 386 var elements;
373 387 if (selector === undefined || selector === null || selector === '') {
374 388 if (this.$el_to_style === undefined) {
375 389 elements = this.$el;
376 390 } else {
377 391 elements = this.$el_to_style;
378 392 }
379 393 } else {
380 394 elements = this.$el.find(selector);
381 395 }
382 396 return elements;
383 397 },
384 398 });
385 399
386 400 IPython.WidgetModel = WidgetModel;
387 401 IPython.WidgetView = WidgetView;
388 402 IPython.DOMWidgetView = DOMWidgetView;
389 403
390 404 // Pass through WidgetManager namespace.
391 405 return WidgetManager;
392 406 });
General Comments 0
You need to be logged in to leave comments. Login now