Skip to content

Commit

Permalink
Merge pull request #3313 from martinRenou/control_channel
Browse files Browse the repository at this point in the history
Implement jupyter.widget.control comm channel
  • Loading branch information
vidartf authored Nov 23, 2021
2 parents 4160af3 + b0e7ecf commit 584fb26
Show file tree
Hide file tree
Showing 5 changed files with 107 additions and 3 deletions.
41 changes: 41 additions & 0 deletions packages/schema/messages.md
Original file line number Diff line number Diff line change
Expand Up @@ -338,3 +338,44 @@ To display a widget, the kernel sends a Jupyter [iopub `display_data` message](h
}
}
```




# Control Widget messaging protocol, version 1.0

This is implemented in ipywidgets 7.7.

### The `jupyter.widget.control` comm target

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,

#### State requests: `request_states`

When a frontend wants to request the full state of a all widgets, the frontend sends a `request_states` message:

```
{
'comm_id' : 'u-u-i-d',
'data' : {
'method': 'request_states'
}
}
```

The kernel side of the widget should immediately send an `update_states` message with all widgets states:

```
{
'comm_id' : 'u-u-i-d',
'data' : {
'method': 'update_states',
'states': {
<widget1 u-u-i-d>: <widget1 state>,
<widget2 u-u-i-d>: <widget2 state>,
[...]
},
'buffer_paths': [ <list with paths corresponding to the binary buffers> ]
}
}
```
1 change: 1 addition & 0 deletions python/ipywidgets/ipywidgets/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ def register_comm_target(kernel=None):
if kernel is None:
kernel = get_ipython().kernel
kernel.comm_manager.register_target('jupyter.widget', Widget.handle_comm_opened)
kernel.comm_manager.register_target('jupyter.widget.control', Widget.handle_control_comm_opened)

def _handle_ipython():
"""Register with the comm target at import if running in Jupyter"""
Expand Down
1 change: 1 addition & 0 deletions python/ipywidgets/ipywidgets/_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
__version__ = '8.0.0b0'

__protocol_version__ = '2.0.0'
__control_protocol_version__ = '1.0.0'

# 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.
__jupyter_widgets_base_version__ = '2.0.0'
Expand Down
17 changes: 16 additions & 1 deletion python/ipywidgets/ipywidgets/widgets/tests/test_send_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@

from traitlets import Bool, Tuple, List

from .utils import setup, teardown
from .utils import setup, teardown, DummyComm

from ..widget import Widget

from ..._version import __control_protocol_version__

# A widget with simple traits
class SimpleWidget(Widget):
a = Bool().tag(sync=True)
Expand All @@ -23,3 +25,16 @@ def test_empty_hold_sync():
with w.hold_sync():
pass
assert w.comm.messages == []


def test_control():
comm = DummyComm()
Widget.close_all()
w = SimpleWidget()
Widget.handle_control_comm_opened(
comm, dict(metadata={'version': __control_protocol_version__})
)
Widget._handle_control_comm_msg(dict(content=dict(
data={'method': 'request_states'}
)))
assert comm.messages
50 changes: 48 additions & 2 deletions python/ipywidgets/ipywidgets/widgets/widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@

from base64 import standard_b64encode

from .._version import __protocol_version__, __jupyter_widgets_base_version__
from .._version import __protocol_version__, __control_protocol_version__, __jupyter_widgets_base_version__
PROTOCOL_VERSION_MAJOR = __protocol_version__.split('.')[0]
CONTROL_PROTOCOL_VERSION_MAJOR = __control_protocol_version__.split('.')[0]

def _widget_to_json(x, obj):
if isinstance(x, dict):
Expand Down Expand Up @@ -262,6 +263,7 @@ class Widget(LoggingHasTraits):
# Class attributes
#-------------------------------------------------------------------------
_widget_construction_callback = None
_control_comm = None

# _active_widgets is a dictionary of all active widget objects
_active_widgets = {}
Expand All @@ -274,7 +276,6 @@ def close_all(cls):
for widget in list(cls._active_widgets.values()):
widget.close()


@staticmethod
def on_widget_constructed(callback):
"""Registers a callback to be called when a widget is constructed.
Expand All @@ -289,6 +290,51 @@ def _call_widget_constructed(widget):
if Widget._widget_construction_callback is not None and callable(Widget._widget_construction_callback):
Widget._widget_construction_callback(widget)

@classmethod
def handle_control_comm_opened(cls, comm, msg):
"""
Class method, called when the comm-open message on the
"jupyter.widget.control" comm channel is received
"""
version = msg.get('metadata', {}).get('version', '')
if version.split('.')[0] != CONTROL_PROTOCOL_VERSION_MAJOR:
raise ValueError("Incompatible widget control protocol versions: received version %r, expected version %r"%(version, __control_protocol_version__))

cls._control_comm = comm
cls._control_comm.on_msg(cls._handle_control_comm_msg)

@classmethod
def _handle_control_comm_msg(cls, msg):
# This shouldn't happen unless someone calls this method manually
if cls._control_comm is None:
raise RuntimeError('Control comm has not been properly opened')

data = msg['content']['data']
method = data['method']

if method == 'request_states':
# Send back the full widgets state
cls.get_manager_state()
widgets = cls._active_widgets.values()
full_state = {}
drop_defaults = False
for widget in widgets:
full_state[widget.model_id] = {
'model_name': widget._model_name,
'model_module': widget._model_module,
'model_module_version': widget._model_module_version,
'state': widget.get_state(drop_defaults=drop_defaults),
}
full_state, buffer_paths, buffers = _remove_buffers(full_state)
cls._control_comm.send(dict(
method='update_states',
states=full_state,
buffer_paths=buffer_paths
), buffers=buffers)

else:
raise RuntimeError('Unknown front-end to back-end widget control msg with method "%s"' % method)

@staticmethod
def handle_comm_opened(comm, msg):
"""Static method, called when a widget is constructed."""
Expand Down

0 comments on commit 584fb26

Please sign in to comment.