Skip to content

Commit 430013e

Browse files
maartenbreddelsmartinRenou
authored andcommitted
Implement jupyter.widget.control comm channel
1 parent fc84ae5 commit 430013e

File tree

6 files changed

+101
-4
lines changed

6 files changed

+101
-4
lines changed

ipywidgets/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ def register_comm_target(kernel=None):
3838
if kernel is None:
3939
kernel = get_ipython().kernel
4040
kernel.comm_manager.register_target('jupyter.widget', Widget.handle_comm_opened)
41+
kernel.comm_manager.register_target('jupyter.widget.control', Widget.handle_control_comm_opened)
4142

4243
# deprecated alias
4344
handle_kernel = register_comm_target

ipywidgets/_version.py

+1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
'' if version_info[3]=='final' else _specifier_[version_info[3]]+str(version_info[4]))
1010

1111
__protocol_version__ = '2.0.0'
12+
__control_protocol_version__ = '1.0.0'
1213

1314
# These are *protocol* versions for each package, *not* npm versions. To check, look at each package's src/version.ts file for the protocol version the package implements.
1415
__jupyter_widgets_base_version__ = '1.2.0'

ipywidgets/widgets/tests/test_send_state.py

+10-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
from traitlets import Bool, Tuple, List
55

6-
from .utils import setup, teardown
6+
from .utils import setup, teardown, DummyComm
77

88
from ..widget import Widget
99

@@ -23,3 +23,12 @@ def test_empty_hold_sync():
2323
with w.hold_sync():
2424
pass
2525
assert w.comm.messages == []
26+
27+
28+
def test_control():
29+
comm = DummyComm()
30+
Widget.close_all()
31+
w = SimpleWidget()
32+
Widget.handle_control_comm_opened(comm, {})
33+
Widget.handle_control_comm_msg({'type': 'models-request'})
34+
assert comm.messages

ipywidgets/widgets/widget.py

+48-2
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,9 @@
2525

2626
from base64 import standard_b64encode
2727

28-
from .._version import __protocol_version__, __jupyter_widgets_base_version__
28+
from .._version import __protocol_version__, __control_protocol_version__, __jupyter_widgets_base_version__
2929
PROTOCOL_VERSION_MAJOR = __protocol_version__.split('.')[0]
30+
CONTROL_PROTOCOL_VERSION_MAJOR = __control_protocol_version__.split('.')[0]
3031

3132
def _widget_to_json(x, obj):
3233
if isinstance(x, dict):
@@ -290,6 +291,7 @@ class Widget(LoggingHasTraits):
290291
# Class attributes
291292
#-------------------------------------------------------------------------
292293
_widget_construction_callback = None
294+
_control_comm = None
293295

294296
# widgets is a dictionary of all active widget objects
295297
widgets = {}
@@ -302,7 +304,6 @@ def close_all(cls):
302304
for widget in list(cls.widgets.values()):
303305
widget.close()
304306

305-
306307
@staticmethod
307308
def on_widget_constructed(callback):
308309
"""Registers a callback to be called when a widget is constructed.
@@ -317,6 +318,51 @@ def _call_widget_constructed(widget):
317318
if Widget._widget_construction_callback is not None and callable(Widget._widget_construction_callback):
318319
Widget._widget_construction_callback(widget)
319320

321+
@classmethod
322+
def handle_control_comm_opened(cls, comm, msg):
323+
"""
324+
Class method, called when the comm-open message on the
325+
"jupyter.widget.control" comm channel is received
326+
"""
327+
version = msg.get('metadata', {}).get('version', '')
328+
if version.split('.')[0] != CONTROL_PROTOCOL_VERSION_MAJOR:
329+
raise ValueError("Incompatible widget control protocol versions: received version %r, expected version %r"%(version, __control_protocol_version__))
330+
331+
cls._control_comm = comm
332+
cls._control_comm.on_msg(cls._handle_control_comm_msg)
333+
334+
@classmethod
335+
def _handle_control_comm_msg(cls, msg):
336+
# This shouldn't happen unless someone calls this method manually
337+
if cls._control_comm is None:
338+
raise RuntimeError('Control comm has not been properly opened')
339+
340+
data = msg['content']['data']
341+
method = data['method']
342+
343+
if method == 'request_states':
344+
# Send back the full widgets state
345+
cls.get_manager_state()
346+
widgets = cls.widgets.values()
347+
full_state = {}
348+
drop_defaults = False
349+
for widget in widgets:
350+
full_state[widget.model_id] = {
351+
'model_name': widget._model_name,
352+
'model_module': widget._model_module,
353+
'model_module_version': widget._model_module_version,
354+
'state': widget.get_state(drop_defaults=drop_defaults),
355+
}
356+
full_state, buffer_paths, buffers = _remove_buffers(full_state)
357+
cls._control_comm.send(dict(
358+
method='update_states',
359+
states=full_state,
360+
buffer_paths=buffer_paths
361+
), buffers=buffers)
362+
363+
else:
364+
self.log.error('Unknown front-end to back-end widget control msg with method "%s"' % method)
365+
320366
@staticmethod
321367
def handle_comm_opened(comm, msg):
322368
"""Static method, called when a widget is constructed."""

packages/base/src/version.ts

-1
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,3 @@ const JUPYTER_WIDGETS_VERSION = '1.2.0';
66

77
export
88
const PROTOCOL_VERSION = '2.0.0';
9-

packages/schema/messages.md

+41
Original file line numberDiff line numberDiff line change
@@ -338,3 +338,44 @@ To display a widget, the kernel sends a Jupyter [iopub `display_data` message](h
338338
}
339339
}
340340
```
341+
342+
343+
344+
345+
# Control Widget messaging protocol, version 1.0
346+
347+
This is implemented in ipywidgets 7.7.
348+
349+
### The `jupyter.widget.control` comm target
350+
351+
A kernel-side Jupyter widgets library registers a `jupyter.widget.control` comm target that is used for fetching all widgets states through a "one shot" comm message (one for all widget instances). Unlike the `jupyter.widget` comm target, the created comm is global to all widgets,
352+
353+
#### State requests: `request_states`
354+
355+
When a frontend wants to request the full state of a all widgets, the frontend sends a `request_states` message:
356+
357+
```
358+
{
359+
'comm_id' : 'u-u-i-d',
360+
'data' : {
361+
'method': 'request_states'
362+
}
363+
}
364+
```
365+
366+
The kernel side of the widget should immediately send an `update_states` message with all widgets states:
367+
368+
```
369+
{
370+
'comm_id' : 'u-u-i-d',
371+
'data' : {
372+
'method': 'update_states',
373+
'states': {
374+
<widget1 u-u-i-d>: <widget1 state>,
375+
<widget2 u-u-i-d>: <widget2 state>,
376+
[...]
377+
},
378+
'buffer_paths': [ <list with paths corresponding to the binary buffers> ]
379+
}
380+
}
381+
```

0 commit comments

Comments
 (0)