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