Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Avatar for KuCalc : devops.
Download
50659 views
1
// Copyright (c) IPython Development Team.
2
// Distributed under the terms of the Modified BSD License.
3
4
define([
5
"underscore",
6
"backbone",
7
"jquery",
8
"base/js/utils",
9
"base/js/namespace",
10
"services/kernels/comm"
11
], function (_, Backbone, $, utils, IPython, comm) {
12
"use strict";
13
//--------------------------------------------------------------------
14
// WidgetManager class
15
//--------------------------------------------------------------------
16
var WidgetManager = function (comm_manager, notebook) {
17
/**
18
* Public constructor
19
*/
20
WidgetManager._managers.push(this);
21
22
// Attach a comm manager to the
23
this.keyboard_manager = notebook.keyboard_manager;
24
this.notebook = notebook;
25
this.comm_manager = comm_manager;
26
this.comm_target_name = 'ipython.widget';
27
this._models = {}; /* Dictionary of model ids and model instance promises */
28
29
// Register with the comm manager.
30
this.comm_manager.register_target(this.comm_target_name, $.proxy(this._handle_comm_open, this));
31
32
// Load the initial state of the widget manager if a load callback was
33
// registered.
34
var that = this;
35
if (WidgetManager._load_callback) {
36
Promise.resolve().then(function () {
37
return WidgetManager._load_callback.call(that);
38
}).then(function(state) {
39
that.set_state(state);
40
}).catch(utils.reject('Error loading widget manager state', true));
41
}
42
43
// Setup state saving code.
44
this.notebook.events.on('before_save.Notebook', function() {
45
var save_callback = WidgetManager._save_callback;
46
var options = WidgetManager._get_state_options;
47
if (save_callback) {
48
that.get_state(options).then(function(state) {
49
save_callback.call(that, state);
50
}).catch(utils.reject('Could not call widget save state callback.', true));
51
}
52
});
53
};
54
55
//--------------------------------------------------------------------
56
// Class level
57
//--------------------------------------------------------------------
58
WidgetManager._model_types = {}; /* Dictionary of model type names (target_name) and model types. */
59
WidgetManager._view_types = {}; /* Dictionary of view names and view types. */
60
WidgetManager._managers = []; /* List of widget managers */
61
WidgetManager._load_callback = null;
62
WidgetManager._save_callback = null;
63
64
WidgetManager.register_widget_model = function (model_name, model_type) {
65
/**
66
* Registers a widget model by name.
67
*/
68
WidgetManager._model_types[model_name] = model_type;
69
};
70
71
WidgetManager.register_widget_view = function (view_name, view_type) {
72
/**
73
* Registers a widget view by name.
74
*/
75
WidgetManager._view_types[view_name] = view_type;
76
};
77
78
WidgetManager.set_state_callbacks = function (load_callback, save_callback, options) {
79
/**
80
* Registers callbacks for widget state persistence.
81
*
82
* Parameters
83
* ----------
84
* load_callback: function()
85
* function that is called when the widget manager state should be
86
* loaded. This function should return a promise for the widget
87
* manager state. An empty state is an empty dictionary `{}`.
88
* save_callback: function(state as dictionary)
89
* function that is called when the notebook is saved or autosaved.
90
* The current state of the widget manager is passed in as the first
91
* argument.
92
*/
93
WidgetManager._load_callback = load_callback;
94
WidgetManager._save_callback = save_callback;
95
WidgetManager._get_state_options = options;
96
97
// Use the load callback to immediately load widget states.
98
WidgetManager._managers.forEach(function(manager) {
99
if (load_callback) {
100
Promise.resolve().then(function () {
101
return load_callback.call(manager);
102
}).then(function(state) {
103
manager.set_state(state);
104
}).catch(utils.reject('Error loading widget manager state', true));
105
}
106
});
107
};
108
109
// Use local storage to persist widgets across page refresh by default.
110
// LocalStorage is per domain, so we need to explicitly set the URL
111
// that the widgets are associated with so they don't show on other
112
// pages hosted by the noteboook server.
113
var url = [window.location.protocol, '//', window.location.host, window.location.pathname].join('');
114
var key = 'widgets:' + url;
115
WidgetManager.set_state_callbacks(function() {
116
if (localStorage[key]) {
117
return JSON.parse(localStorage[key]);
118
}
119
return {};
120
}, function(state) {
121
localStorage[key] = JSON.stringify(state);
122
});
123
124
//--------------------------------------------------------------------
125
// Instance level
126
//--------------------------------------------------------------------
127
WidgetManager.prototype.display_view = function(msg, model) {
128
/**
129
* Displays a view for a particular model.
130
*/
131
var cell = this.get_msg_cell(msg.parent_header.msg_id);
132
if (cell === null) {
133
return Promise.reject(new Error("Could not determine where the display" +
134
" message was from. Widget will not be displayed"));
135
} else {
136
return this.display_view_in_cell(cell, model)
137
.catch(utils.reject('Could not display view', true));
138
}
139
};
140
141
WidgetManager.prototype.display_view_in_cell = function(cell, model) {
142
// Displays a view in a cell.
143
if (cell.display_widget_view) {
144
var that = this;
145
return cell.display_widget_view(this.create_view(model, {
146
cell: cell,
147
// Only set cell_index when view is displayed as directly.
148
cell_index: that.notebook.find_cell_index(cell),
149
})).then(function(view) {
150
that._handle_display_view(view);
151
view.trigger('displayed');
152
return view;
153
}).catch(utils.reject('Could not create or display view', true));
154
} else {
155
return Promise.reject(new Error('Cell does not have a `display_widget_view` method'));
156
}
157
};
158
159
WidgetManager.prototype._handle_display_view = function (view) {
160
/**
161
* Have the IPython keyboard manager disable its event
162
* handling so the widget can capture keyboard input.
163
* Note, this is only done on the outer most widgets.
164
*/
165
if (this.keyboard_manager) {
166
this.keyboard_manager.register_events(view.$el);
167
168
if (view.additional_elements) {
169
for (var i = 0; i < view.additional_elements.length; i++) {
170
this.keyboard_manager.register_events(view.additional_elements[i]);
171
}
172
}
173
}
174
};
175
176
WidgetManager.prototype.create_view = function(model, options) {
177
/**
178
* Creates a promise for a view of a given model
179
*
180
* Make sure the view creation is not out of order with
181
* any state updates.
182
*/
183
model.state_change = model.state_change.then(function() {
184
185
return utils.load_class(model.get('_view_name'), model.get('_view_module'),
186
WidgetManager._view_types).then(function(ViewType) {
187
188
// If a view is passed into the method, use that view's cell as
189
// the cell for the view that is created.
190
options = options || {};
191
if (options.parent !== undefined) {
192
options.cell = options.parent.options.cell;
193
}
194
// Create and render the view...
195
var parameters = {model: model, options: options};
196
var view = new ViewType(parameters);
197
view.listenTo(model, 'destroy', view.remove);
198
return Promise.resolve(view.render()).then(function() {return view;});
199
}).catch(utils.reject("Couldn't create a view for model id '" + String(model.id) + "'", true));
200
});
201
var id = utils.uuid();
202
model.views[id] = model.state_change;
203
model.state_change.then(function(view) {
204
view.once('remove', function() {
205
delete view.model.views[id];
206
}, this);
207
});
208
return model.state_change;
209
};
210
211
WidgetManager.prototype.get_msg_cell = function (msg_id) {
212
var cell = null;
213
// First, check to see if the msg was triggered by cell execution.
214
if (this.notebook) {
215
cell = this.notebook.get_msg_cell(msg_id);
216
}
217
if (cell !== null) {
218
return cell;
219
}
220
// Second, check to see if a get_cell callback was defined
221
// for the message. get_cell callbacks are registered for
222
// widget messages, so this block is actually checking to see if the
223
// message was triggered by a widget.
224
var kernel = this.comm_manager.kernel;
225
if (kernel) {
226
var callbacks = kernel.get_callbacks_for_msg(msg_id);
227
if (callbacks && callbacks.iopub &&
228
callbacks.iopub.get_cell !== undefined) {
229
return callbacks.iopub.get_cell();
230
}
231
}
232
233
// Not triggered by a cell or widget (no get_cell callback
234
// exists).
235
return null;
236
};
237
238
WidgetManager.prototype.callbacks = function (view) {
239
/**
240
* callback handlers specific a view
241
*/
242
var callbacks = {};
243
if (view && view.options.cell) {
244
245
// Try to get output handlers
246
var cell = view.options.cell;
247
var handle_output = null;
248
var handle_clear_output = null;
249
if (cell.output_area) {
250
handle_output = $.proxy(cell.output_area.handle_output, cell.output_area);
251
handle_clear_output = $.proxy(cell.output_area.handle_clear_output, cell.output_area);
252
}
253
254
// Create callback dictionary using what is known
255
var that = this;
256
callbacks = {
257
iopub : {
258
output : handle_output,
259
clear_output : handle_clear_output,
260
261
// Special function only registered by widget messages.
262
// Allows us to get the cell for a message so we know
263
// where to add widgets if the code requires it.
264
get_cell : function () {
265
return cell;
266
},
267
},
268
};
269
}
270
return callbacks;
271
};
272
273
WidgetManager.prototype.get_model = function (model_id) {
274
/**
275
* Get a promise for a model by model id.
276
*/
277
return this._models[model_id];
278
};
279
280
WidgetManager.prototype._handle_comm_open = function (comm, msg) {
281
/**
282
* Handle when a comm is opened.
283
*/
284
return this.create_model({
285
model_name: msg.content.data.model_name,
286
model_module: msg.content.data.model_module,
287
comm: comm}).catch(utils.reject("Couldn't create a model.", true));
288
};
289
290
WidgetManager.prototype.create_model = function (options) {
291
/**
292
* Create and return a promise for a new widget model
293
*
294
* Minimally, one must provide the model_name and widget_class
295
* parameters to create a model from Javascript.
296
*
297
* Example
298
* --------
299
* JS:
300
* IPython.notebook.kernel.widget_manager.create_model({
301
* model_name: 'WidgetModel',
302
* widget_class: 'IPython.html.widgets.widget_int.IntSlider'})
303
* .then(function(model) { console.log('Create success!', model); },
304
* $.proxy(console.error, console));
305
*
306
* Parameters
307
* ----------
308
* options: dictionary
309
* Dictionary of options with the following contents:
310
* model_name: string
311
* Target name of the widget model to create.
312
* model_module: (optional) string
313
* Module name of the widget model to create.
314
* widget_class: (optional) string
315
* Target name of the widget in the back-end.
316
* comm: (optional) Comm
317
*
318
* Create a comm if it wasn't provided.
319
*/
320
var comm = options.comm;
321
if (!comm) {
322
comm = this.comm_manager.new_comm('ipython.widget', {'widget_class': options.widget_class});
323
}
324
325
var that = this;
326
var model_id = comm.comm_id;
327
var model_promise = utils.load_class(options.model_name, options.model_module, WidgetManager._model_types)
328
.then(function(ModelType) {
329
var widget_model = new ModelType(that, model_id, comm);
330
widget_model.once('comm:close', function () {
331
delete that._models[model_id];
332
});
333
widget_model.name = options.model_name;
334
widget_model.module = options.model_module;
335
return widget_model;
336
337
}, function(error) {
338
delete that._models[model_id];
339
var wrapped_error = new utils.WrappedError("Couldn't create model", error);
340
return Promise.reject(wrapped_error);
341
});
342
this._models[model_id] = model_promise;
343
return model_promise;
344
};
345
346
WidgetManager.prototype.get_state = function(options) {
347
/**
348
* Asynchronously get the state of the widget manager.
349
*
350
* This includes all of the widget models and the cells that they are
351
* displayed in.
352
*
353
* Parameters
354
* ----------
355
* options: dictionary
356
* Dictionary of options with the following contents:
357
* only_displayed: (optional) boolean=false
358
* Only return models with one or more displayed views.
359
* not_live: (optional) boolean=false
360
* Include models that have comms with severed connections.
361
*
362
* Returns
363
* -------
364
* Promise for a state dictionary
365
*/
366
var that = this;
367
return utils.resolve_promises_dict(this._models).then(function(models) {
368
var state = {};
369
370
var model_promises = [];
371
for (var model_id in models) {
372
if (models.hasOwnProperty(model_id)) {
373
var model = models[model_id];
374
375
// If the model has one or more views defined for it,
376
// consider it displayed.
377
var displayed_flag = !(options && options.only_displayed) || Object.keys(model.views).length > 0;
378
var live_flag = (options && options.not_live) || model.comm_live;
379
if (displayed_flag && live_flag) {
380
state[model_id] = {
381
model_name: model.name,
382
model_module: model.module,
383
state: model.get_state(),
384
views: [],
385
};
386
387
// Get the views that are displayed *now*.
388
(function(local_state) {
389
model_promises.push(utils.resolve_promises_dict(model.views).then(function(model_views) {
390
for (var id in model_views) {
391
if (model_views.hasOwnProperty(id)) {
392
var view = model_views[id];
393
if (view.options.cell_index) {
394
local_state.views.push(view.options.cell_index);
395
}
396
}
397
}
398
}));
399
})(state[model_id]);
400
}
401
}
402
}
403
return Promise.all(model_promises).then(function() { return state; });
404
}).catch(utils.reject('Could not get state of widget manager', true));
405
};
406
407
WidgetManager.prototype.set_state = function(state) {
408
/**
409
* Set the notebook's state.
410
*
411
* Reconstructs all of the widget models and attempts to redisplay the
412
* widgets in the appropriate cells by cell index.
413
*/
414
415
// Get the kernel when it's available.
416
var that = this;
417
return this._get_connected_kernel().then(function(kernel) {
418
419
// Recreate all the widget models for the given state and
420
// display the views.
421
that.all_views = [];
422
var model_ids = Object.keys(state);
423
for (var i = 0; i < model_ids.length; i++) {
424
var model_id = model_ids[i];
425
426
// Recreate a comm using the widget's model id (model_id == comm_id).
427
var new_comm = new comm.Comm(kernel.widget_manager.comm_target_name, model_id);
428
kernel.comm_manager.register_comm(new_comm);
429
430
// Create the model using the recreated comm. When the model is
431
// created we don't know yet if the comm is valid so set_comm_live
432
// false. Once we receive the first state push from the back-end
433
// we know the comm is alive.
434
var views = kernel.widget_manager.create_model({
435
comm: new_comm,
436
model_name: state[model_id].model_name,
437
model_module: state[model_id].model_module})
438
.then(function(model) {
439
440
model.set_comm_live(false);
441
var view_promise = Promise.resolve().then(function() {
442
return model.set_state(state[model.id].state);
443
}).then(function() {
444
model.request_state().then(function() {
445
model.set_comm_live(true);
446
});
447
448
// Display the views of the model.
449
var views = [];
450
var model_views = state[model.id].views;
451
for (var j=0; j<model_views.length; j++) {
452
var cell_index = model_views[j];
453
var cell = that.notebook.get_cell(cell_index);
454
views.push(that.display_view_in_cell(cell, model));
455
}
456
return Promise.all(views);
457
});
458
return view_promise;
459
});
460
that.all_views.push(views);
461
}
462
return Promise.all(that.all_views);
463
}).catch(utils.reject('Could not set widget manager state.', true));
464
};
465
466
WidgetManager.prototype._get_connected_kernel = function() {
467
/**
468
* Gets a promise for a connected kernel
469
*/
470
var that = this;
471
return new Promise(function(resolve, reject) {
472
if (that.comm_manager &&
473
that.comm_manager.kernel &&
474
that.comm_manager.kernel.is_connected()) {
475
476
resolve(that.comm_manager.kernel);
477
} else {
478
that.notebook.events.on('kernel_connected.Kernel', function(event, data) {
479
resolve(data.kernel);
480
});
481
}
482
});
483
};
484
485
// Backwards compatibility.
486
IPython.WidgetManager = WidgetManager;
487
488
return {'WidgetManager': WidgetManager};
489
});
490
491