##// END OF EJS Templates
stop listening
Sylvain Corlay -
Show More
@@ -1,487 +1,488 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/namespace",
9 9 ], function(widgetmanager, _, Backbone, $, IPython){
10 10
11 11 var WidgetModel = Backbone.Model.extend({
12 12 constructor: function (widget_manager, model_id, comm) {
13 13 // Constructor
14 14 //
15 15 // Creates a WidgetModel instance.
16 16 //
17 17 // Parameters
18 18 // ----------
19 19 // widget_manager : WidgetManager instance
20 20 // model_id : string
21 21 // An ID unique to this model.
22 22 // comm : Comm instance (optional)
23 23 this.widget_manager = widget_manager;
24 24 this._buffered_state_diff = {};
25 25 this.pending_msgs = 0;
26 26 this.msg_buffer = null;
27 27 this.key_value_lock = null;
28 28 this.id = model_id;
29 29 this.views = [];
30 30
31 31 if (comm !== undefined) {
32 32 // Remember comm associated with the model.
33 33 this.comm = comm;
34 34 comm.model = this;
35 35
36 36 // Hook comm messages up to model.
37 37 comm.on_close($.proxy(this._handle_comm_closed, this));
38 38 comm.on_msg($.proxy(this._handle_comm_msg, this));
39 39 }
40 40 return Backbone.Model.apply(this);
41 41 },
42 42
43 43 send: function (content, callbacks) {
44 44 // Send a custom msg over the comm.
45 45 if (this.comm !== undefined) {
46 46 var data = {method: 'custom', content: content};
47 47 this.comm.send(data, callbacks);
48 48 this.pending_msgs++;
49 49 }
50 50 },
51 51
52 52 _handle_comm_closed: function (msg) {
53 53 // Handle when a widget is closed.
54 54 this.trigger('comm:close');
55 this.stopListening();
55 56 this.trigger('destroy', this);
56 57 delete this.comm.model; // Delete ref so GC will collect widget model.
57 58 delete this.comm;
58 59 delete this.model_id; // Delete id from model so widget manager cleans up.
59 60 _.each(this.views, function(view, i) {
60 61 view.remove();
61 62 });
62 63 },
63 64
64 65 _handle_comm_msg: function (msg) {
65 66 // Handle incoming comm msg.
66 67 var method = msg.content.data.method;
67 68 switch (method) {
68 69 case 'update':
69 70 this.apply_update(msg.content.data.state);
70 71 break;
71 72 case 'custom':
72 73 this.trigger('msg:custom', msg.content.data.content);
73 74 break;
74 75 case 'display':
75 76 this.widget_manager.display_view(msg, this);
76 77 break;
77 78 }
78 79 },
79 80
80 81 apply_update: function (state) {
81 82 // Handle when a widget is updated via the python side.
82 83 var that = this;
83 84 _.each(state, function(value, key) {
84 85 that.key_value_lock = [key, value];
85 86 try {
86 87 WidgetModel.__super__.set.apply(that, [key, that._unpack_models(value)]);
87 88 } finally {
88 89 that.key_value_lock = null;
89 90 }
90 91 });
91 92 },
92 93
93 94 _handle_status: function (msg, callbacks) {
94 95 // Handle status msgs.
95 96
96 97 // execution_state : ('busy', 'idle', 'starting')
97 98 if (this.comm !== undefined) {
98 99 if (msg.content.execution_state ==='idle') {
99 100 // Send buffer if this message caused another message to be
100 101 // throttled.
101 102 if (this.msg_buffer !== null &&
102 103 (this.get('msg_throttle') || 3) === this.pending_msgs) {
103 104 var data = {method: 'backbone', sync_method: 'update', sync_data: this.msg_buffer};
104 105 this.comm.send(data, callbacks);
105 106 this.msg_buffer = null;
106 107 } else {
107 108 --this.pending_msgs;
108 109 }
109 110 }
110 111 }
111 112 },
112 113
113 114 callbacks: function(view) {
114 115 // Create msg callbacks for a comm msg.
115 116 var callbacks = this.widget_manager.callbacks(view);
116 117
117 118 if (callbacks.iopub === undefined) {
118 119 callbacks.iopub = {};
119 120 }
120 121
121 122 var that = this;
122 123 callbacks.iopub.status = function (msg) {
123 124 that._handle_status(msg, callbacks);
124 125 };
125 126 return callbacks;
126 127 },
127 128
128 129 set: function(key, val, options) {
129 130 // Set a value.
130 131 var return_value = WidgetModel.__super__.set.apply(this, arguments);
131 132
132 133 // Backbone only remembers the diff of the most recent set()
133 134 // operation. Calling set multiple times in a row results in a
134 135 // loss of diff information. Here we keep our own running diff.
135 136 this._buffered_state_diff = $.extend(this._buffered_state_diff, this.changedAttributes() || {});
136 137 return return_value;
137 138 },
138 139
139 140 sync: function (method, model, options) {
140 141 // Handle sync to the back-end. Called when a model.save() is called.
141 142
142 143 // Make sure a comm exists.
143 144 var error = options.error || function() {
144 145 console.error('Backbone sync error:', arguments);
145 146 };
146 147 if (this.comm === undefined) {
147 148 error();
148 149 return false;
149 150 }
150 151
151 152 // Delete any key value pairs that the back-end already knows about.
152 153 var attrs = (method === 'patch') ? options.attrs : model.toJSON(options);
153 154 if (this.key_value_lock !== null) {
154 155 var key = this.key_value_lock[0];
155 156 var value = this.key_value_lock[1];
156 157 if (attrs[key] === value) {
157 158 delete attrs[key];
158 159 }
159 160 }
160 161
161 162 // Only sync if there are attributes to send to the back-end.
162 163 attrs = this._pack_models(attrs);
163 164 if (_.size(attrs) > 0) {
164 165
165 166 // If this message was sent via backbone itself, it will not
166 167 // have any callbacks. It's important that we create callbacks
167 168 // so we can listen for status messages, etc...
168 169 var callbacks = options.callbacks || this.callbacks();
169 170
170 171 // Check throttle.
171 172 if (this.pending_msgs >= (this.get('msg_throttle') || 3)) {
172 173 // The throttle has been exceeded, buffer the current msg so
173 174 // it can be sent once the kernel has finished processing
174 175 // some of the existing messages.
175 176
176 177 // Combine updates if it is a 'patch' sync, otherwise replace updates
177 178 switch (method) {
178 179 case 'patch':
179 180 this.msg_buffer = $.extend(this.msg_buffer || {}, attrs);
180 181 break;
181 182 case 'update':
182 183 case 'create':
183 184 this.msg_buffer = attrs;
184 185 break;
185 186 default:
186 187 error();
187 188 return false;
188 189 }
189 190 this.msg_buffer_callbacks = callbacks;
190 191
191 192 } else {
192 193 // We haven't exceeded the throttle, send the message like
193 194 // normal.
194 195 var data = {method: 'backbone', sync_data: attrs};
195 196 this.comm.send(data, callbacks);
196 197 this.pending_msgs++;
197 198 }
198 199 }
199 200 // Since the comm is a one-way communication, assume the message
200 201 // arrived. Don't call success since we don't have a model back from the server
201 202 // this means we miss out on the 'sync' event.
202 203 this._buffered_state_diff = {};
203 204 },
204 205
205 206 save_changes: function(callbacks) {
206 207 // Push this model's state to the back-end
207 208 //
208 209 // This invokes a Backbone.Sync.
209 210 this.save(this._buffered_state_diff, {patch: true, callbacks: callbacks});
210 211 },
211 212
212 213 _pack_models: function(value) {
213 214 // Replace models with model ids recursively.
214 215 var that = this;
215 216 var packed;
216 217 if (value instanceof Backbone.Model) {
217 218 return "IPY_MODEL_" + value.id;
218 219
219 220 } else if ($.isArray(value)) {
220 221 packed = [];
221 222 _.each(value, function(sub_value, key) {
222 223 packed.push(that._pack_models(sub_value));
223 224 });
224 225 return packed;
225 226
226 227 } else if (value instanceof Object) {
227 228 packed = {};
228 229 _.each(value, function(sub_value, key) {
229 230 packed[key] = that._pack_models(sub_value);
230 231 });
231 232 return packed;
232 233
233 234 } else {
234 235 return value;
235 236 }
236 237 },
237 238
238 239 _unpack_models: function(value) {
239 240 // Replace model ids with models recursively.
240 241 var that = this;
241 242 var unpacked;
242 243 if ($.isArray(value)) {
243 244 unpacked = [];
244 245 _.each(value, function(sub_value, key) {
245 246 unpacked.push(that._unpack_models(sub_value));
246 247 });
247 248 return unpacked;
248 249
249 250 } else if (value instanceof Object) {
250 251 unpacked = {};
251 252 _.each(value, function(sub_value, key) {
252 253 unpacked[key] = that._unpack_models(sub_value);
253 254 });
254 255 return unpacked;
255 256
256 257 } else if (typeof value === 'string' && value.slice(0,10) === "IPY_MODEL_") {
257 258 var model = this.widget_manager.get_model(value.slice(10, value.length));
258 259 if (model) {
259 260 return model;
260 261 } else {
261 262 return value;
262 263 }
263 264 } else {
264 265 return value;
265 266 }
266 267 },
267 268
268 269 });
269 270 widgetmanager.WidgetManager.register_widget_model('WidgetModel', WidgetModel);
270 271
271 272
272 273 var WidgetView = Backbone.View.extend({
273 274 initialize: function(parameters) {
274 275 // Public constructor.
275 276 this.model.on('change',this.update,this);
276 277 this.options = parameters.options;
277 278 this.child_model_views = {};
278 279 this.child_views = {};
279 280 this.model.views.push(this);
280 281 this.id = this.id || IPython.utils.uuid();
281 282 this.on('displayed', function() {
282 283 this.is_displayed = true;
283 284 }, this);
284 285 },
285 286
286 287 update: function(){
287 288 // Triggered on model change.
288 289 //
289 290 // Update view to be consistent with this.model
290 291 },
291 292
292 293 create_child_view: function(child_model, options) {
293 294 // Create and return a child view.
294 295 //
295 296 // -given a model and (optionally) a view name if the view name is
296 297 // not given, it defaults to the model's default view attribute.
297 298
298 299 // TODO: this is hacky, and makes the view depend on this cell attribute and widget manager behavior
299 300 // it would be great to have the widget manager add the cell metadata
300 301 // to the subview without having to add it here.
301 302 options = $.extend({ parent: this }, options || {});
302 303 var child_view = this.model.widget_manager.create_view(child_model, options, this);
303 304
304 305 // Associate the view id with the model id.
305 306 if (this.child_model_views[child_model.id] === undefined) {
306 307 this.child_model_views[child_model.id] = [];
307 308 }
308 309 this.child_model_views[child_model.id].push(child_view.id);
309 310
310 311 // Remember the view by id.
311 312 this.child_views[child_view.id] = child_view;
312 313 return child_view;
313 314 },
314 315
315 316 pop_child_view: function(child_model) {
316 317 // Delete a child view that was previously created using create_child_view.
317 318 var view_ids = this.child_model_views[child_model.id];
318 319 if (view_ids !== undefined) {
319 320
320 321 // Only delete the first view in the list.
321 322 var view_id = view_ids[0];
322 323 var view = this.child_views[view_id];
323 324 delete this.child_views[view_id];
324 325 view_ids.splice(0,1);
325 326 child_model.views.pop(view);
326 327
327 328 // Remove the view list specific to this model if it is empty.
328 329 if (view_ids.length === 0) {
329 330 delete this.child_model_views[child_model.id];
330 331 }
331 332 return view;
332 333 }
333 334 return null;
334 335 },
335 336
336 337 do_diff: function(old_list, new_list, removed_callback, added_callback) {
337 338 // Difference a changed list and call remove and add callbacks for
338 339 // each removed and added item in the new list.
339 340 //
340 341 // Parameters
341 342 // ----------
342 343 // old_list : array
343 344 // new_list : array
344 345 // removed_callback : Callback(item)
345 346 // Callback that is called for each item removed.
346 347 // added_callback : Callback(item)
347 348 // Callback that is called for each item added.
348 349
349 350 // Walk the lists until an unequal entry is found.
350 351 var i;
351 352 for (i = 0; i < new_list.length; i++) {
352 353 if (i >= old_list.length || new_list[i] !== old_list[i]) {
353 354 break;
354 355 }
355 356 }
356 357
357 358 // Remove the non-matching items from the old list.
358 359 for (var j = i; j < old_list.length; j++) {
359 360 removed_callback(old_list[j]);
360 361 }
361 362
362 363 // Add the rest of the new list items.
363 364 for (; i < new_list.length; i++) {
364 365 added_callback(new_list[i]);
365 366 }
366 367 },
367 368
368 369 callbacks: function(){
369 370 // Create msg callbacks for a comm msg.
370 371 return this.model.callbacks(this);
371 372 },
372 373
373 374 render: function(){
374 375 // Render the view.
375 376 //
376 377 // By default, this is only called the first time the view is created
377 378 },
378 379
379 380 show: function(){
380 381 // Show the widget-area
381 382 if (this.options && this.options.cell &&
382 383 this.options.cell.widget_area !== undefined) {
383 384 this.options.cell.widget_area.show();
384 385 }
385 386 },
386 387
387 388 send: function (content) {
388 389 // Send a custom msg associated with this view.
389 390 this.model.send(content, this.callbacks());
390 391 },
391 392
392 393 touch: function () {
393 394 this.model.save_changes(this.callbacks());
394 395 },
395 396
396 397 after_displayed: function (callback, context) {
397 398 // Calls the callback right away is the view is already displayed
398 399 // otherwise, register the callback to the 'displayed' event.
399 400 if (this.is_displayed) {
400 401 callback.apply(context);
401 402 } else {
402 403 this.on('displayed', callback, context);
403 404 }
404 405 },
405 406 });
406 407
407 408
408 409 var DOMWidgetView = WidgetView.extend({
409 410 initialize: function (parameters) {
410 411 // Public constructor
411 412 DOMWidgetView.__super__.initialize.apply(this, [parameters]);
412 413 this.on('displayed', this.show, this);
413 414 this.after_displayed(function() {
414 415 this.update_visible(this.model, this.model.get("visible"));
415 416 this.update_css(this.model, this.model.get("_css"));
416 417 }, this);
417 418 this.model.on('msg:custom', this.on_msg, this);
418 419 this.model.on('change:visible', this.update_visible, this);
419 420 this.model.on('change:_css', this.update_css, this);
420 421 },
421 422
422 423 on_msg: function(msg) {
423 424 // Handle DOM specific msgs.
424 425 switch(msg.msg_type) {
425 426 case 'add_class':
426 427 this.add_class(msg.selector, msg.class_list);
427 428 break;
428 429 case 'remove_class':
429 430 this.remove_class(msg.selector, msg.class_list);
430 431 break;
431 432 }
432 433 },
433 434
434 435 add_class: function (selector, class_list) {
435 436 // Add a DOM class to an element.
436 437 this._get_selector_element(selector).addClass(class_list);
437 438 },
438 439
439 440 remove_class: function (selector, class_list) {
440 441 // Remove a DOM class from an element.
441 442 this._get_selector_element(selector).removeClass(class_list);
442 443 },
443 444
444 445 update_visible: function(model, value) {
445 446 // Update visibility
446 447 this.$el.toggle(value);
447 448 },
448 449
449 450 update_css: function (model, css) {
450 451 // Update the css styling of this view.
451 452 var e = this.$el;
452 453 if (css === undefined) {return;}
453 454 for (var i = 0; i < css.length; i++) {
454 455 // Apply the css traits to all elements that match the selector.
455 456 var selector = css[i][0];
456 457 var elements = this._get_selector_element(selector);
457 458 if (elements.length > 0) {
458 459 var trait_key = css[i][1];
459 460 var trait_value = css[i][2];
460 461 elements.css(trait_key ,trait_value);
461 462 }
462 463 }
463 464 },
464 465
465 466 _get_selector_element: function (selector) {
466 467 // Get the elements via the css selector.
467 468 var elements;
468 469 if (!selector) {
469 470 elements = this.$el;
470 471 } else {
471 472 elements = this.$el.find(selector).addBack(selector);
472 473 }
473 474 return elements;
474 475 },
475 476 });
476 477
477 478 var widget = {
478 479 'WidgetModel': WidgetModel,
479 480 'WidgetView': WidgetView,
480 481 'DOMWidgetView': DOMWidgetView,
481 482 };
482 483
483 484 // For backwards compatability.
484 485 $.extend(IPython, widget);
485 486
486 487 return widget;
487 488 });
General Comments 0
You need to be logged in to leave comments. Login now