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