mirror of
https://github.com/jupyter/notebook.git
synced 2024-12-21 04:10:17 +08:00
Separate the display from the models on the python side, creating a BaseWidget class.
Conflicts: IPython/html/widgets/widget.py
This commit is contained in:
parent
2df05bc5b8
commit
518cb4c647
@ -30,10 +30,13 @@ from IPython.utils.py3compat import string_types
|
|||||||
#-----------------------------------------------------------------------------
|
#-----------------------------------------------------------------------------
|
||||||
# Classes
|
# Classes
|
||||||
#-----------------------------------------------------------------------------
|
#-----------------------------------------------------------------------------
|
||||||
class Widget(LoggingConfigurable):
|
|
||||||
|
class BaseWidget(LoggingConfigurable):
|
||||||
|
|
||||||
# Shared declarations (Class level)
|
# Shared declarations (Class level)
|
||||||
_keys = []
|
_keys = List(Unicode, help="List of keys comprising the state of the model.")
|
||||||
|
_children_attr = List(Unicode, help="List of keys of children objects of the model.")
|
||||||
|
_children_lists_attr = List(Unicode, help="List of keys containing lists of children objects of the model.")
|
||||||
widget_construction_callback = None
|
widget_construction_callback = None
|
||||||
|
|
||||||
def on_widget_constructed(callback):
|
def on_widget_constructed(callback):
|
||||||
@ -54,52 +57,24 @@ class Widget(LoggingConfigurable):
|
|||||||
registered in the frontend to create and sync this widget with.""")
|
registered in the frontend to create and sync this widget with.""")
|
||||||
default_view_name = Unicode(help="""Default view registered in the frontend
|
default_view_name = Unicode(help="""Default view registered in the frontend
|
||||||
to use to represent the widget.""")
|
to use to represent the widget.""")
|
||||||
parent = Instance('IPython.html.widgets.widget.Widget')
|
|
||||||
visible = Bool(True, help="Whether or not the widget is visible.")
|
|
||||||
|
|
||||||
def _parent_changed(self, name, old, new):
|
|
||||||
if self._displayed:
|
|
||||||
raise Exception('Parent cannot be set because widget has been displayed.')
|
|
||||||
elif new == self:
|
|
||||||
raise Exception('Parent cannot be set to self.')
|
|
||||||
else:
|
|
||||||
|
|
||||||
# Parent/child association
|
|
||||||
if new is not None and not self in new._children:
|
|
||||||
new._children.append(self)
|
|
||||||
if old is not None and self in old._children:
|
|
||||||
old._children.remove(self)
|
|
||||||
|
|
||||||
# Private/protected declarations
|
# Private/protected declarations
|
||||||
_property_lock = (None, None) # Last updated (key, value) from the front-end. Prevents echo.
|
_property_lock = (None, None) # Last updated (key, value) from the front-end. Prevents echo.
|
||||||
_css = Dict() # Internal CSS property dict
|
|
||||||
_displayed = False
|
_displayed = False
|
||||||
|
_comm = None
|
||||||
|
|
||||||
def __init__(self, **kwargs):
|
def __init__(self, **kwargs):
|
||||||
"""Public constructor
|
"""Public constructor
|
||||||
|
|
||||||
Parameters
|
|
||||||
----------
|
|
||||||
parent : Widget instance (optional)
|
|
||||||
Widget that this widget instance is child of. When the widget is
|
|
||||||
displayed in the frontend, it's corresponding view will be made
|
|
||||||
child of the parent's view if the parent's view exists already. If
|
|
||||||
the parent's view is displayed, it will automatically display this
|
|
||||||
widget's default view as it's child. The default view can be set
|
|
||||||
via the default_view_name property.
|
|
||||||
"""
|
"""
|
||||||
self._children = []
|
|
||||||
self._display_callbacks = []
|
self._display_callbacks = []
|
||||||
self._msg_callbacks = []
|
self._msg_callbacks = []
|
||||||
super(Widget, self).__init__(**kwargs)
|
super(BaseWidget, self).__init__(**kwargs)
|
||||||
|
|
||||||
# Register after init to allow default values to be specified
|
# Register after init to allow default values to be specified
|
||||||
self.on_trait_change(self._handle_property_changed, self.keys)
|
# TODO: register three different handlers, one for each list, and abstract out the common parts
|
||||||
|
self.on_trait_change(self._handle_property_changed, self.keys+self._children_attr+self._children_lists_attr)
|
||||||
Widget._handle_widget_constructed(self)
|
Widget._handle_widget_constructed(self)
|
||||||
|
|
||||||
|
|
||||||
def __del__(self):
|
def __del__(self):
|
||||||
"""Object disposal"""
|
"""Object disposal"""
|
||||||
self.close()
|
self.close()
|
||||||
@ -113,12 +88,17 @@ class Widget(LoggingConfigurable):
|
|||||||
|
|
||||||
|
|
||||||
# Properties
|
# Properties
|
||||||
def _get_keys(self):
|
@property
|
||||||
keys = ['visible', '_css']
|
def keys(self):
|
||||||
|
keys = ['_children_attr', '_children_lists_attr']
|
||||||
keys.extend(self._keys)
|
keys.extend(self._keys)
|
||||||
return keys
|
return keys
|
||||||
keys = property(_get_keys)
|
|
||||||
|
|
||||||
|
@property
|
||||||
|
def comm(self):
|
||||||
|
if self._comm is None:
|
||||||
|
self._open_communication()
|
||||||
|
return self._comm
|
||||||
|
|
||||||
# Event handlers
|
# Event handlers
|
||||||
def _handle_msg(self, msg):
|
def _handle_msg(self, msg):
|
||||||
@ -179,7 +159,6 @@ class Widget(LoggingConfigurable):
|
|||||||
# Send new state to frontend
|
# Send new state to frontend
|
||||||
self.send_state(key=name)
|
self.send_state(key=name)
|
||||||
|
|
||||||
|
|
||||||
def _handle_displayed(self, **kwargs):
|
def _handle_displayed(self, **kwargs):
|
||||||
"""Called when a view has been displayed for this widget instance
|
"""Called when a view has been displayed for this widget instance
|
||||||
|
|
||||||
@ -206,7 +185,6 @@ class Widget(LoggingConfigurable):
|
|||||||
else:
|
else:
|
||||||
handler(self, **kwargs)
|
handler(self, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
# Public methods
|
# Public methods
|
||||||
def send_state(self, key=None):
|
def send_state(self, key=None):
|
||||||
"""Sends the widget state, or a piece of it, to the frontend.
|
"""Sends the widget state, or a piece of it, to the frontend.
|
||||||
@ -216,23 +194,159 @@ class Widget(LoggingConfigurable):
|
|||||||
key : unicode (optional)
|
key : unicode (optional)
|
||||||
A single property's name to sync with the frontend.
|
A single property's name to sync with the frontend.
|
||||||
"""
|
"""
|
||||||
|
self._send({"method": "update",
|
||||||
|
"state": self.get_state()})
|
||||||
|
|
||||||
|
def get_state(self, key=None)
|
||||||
|
"""Gets the widget state, or a piece of it.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
key : unicode (optional)
|
||||||
|
A single property's name to get.
|
||||||
|
"""
|
||||||
state = {}
|
state = {}
|
||||||
|
|
||||||
# If a key is provided, just send the state of that key.
|
# If a key is provided, just send the state of that key.
|
||||||
keys = []
|
|
||||||
if key is None:
|
if key is None:
|
||||||
keys.extend(self.keys)
|
keys = self.keys[:]
|
||||||
|
children_attr = self._children_attr[:]
|
||||||
|
children_lists_attr = self._children_lists_attr[:]
|
||||||
|
else:
|
||||||
|
keys = []
|
||||||
|
children_attr = []
|
||||||
|
children_lists_attr = []
|
||||||
|
if key in self._children_attr:
|
||||||
|
children_attr.append(key)
|
||||||
|
elif key in self._children_lists_attr:
|
||||||
|
children_lists_attr.append(key)
|
||||||
else:
|
else:
|
||||||
keys.append(key)
|
keys.append(key)
|
||||||
for key in self.keys:
|
for k in keys:
|
||||||
try:
|
state[k] = getattr(self, k)
|
||||||
state[key] = getattr(self, key)
|
for k in children_attr:
|
||||||
except Exception as e:
|
# automatically create models on the browser side if they aren't already created
|
||||||
pass # Eat errors, nom nom nom
|
state[k] = getattr(self, k).comm.comm_id
|
||||||
self._send({"method": "update",
|
for k in children_lists_attr:
|
||||||
"state": state})
|
# automatically create models on the browser side if they aren't already created
|
||||||
|
state[k] = [i.comm.comm_id for i in getattr(self, k)]
|
||||||
|
return state
|
||||||
|
|
||||||
|
|
||||||
|
def send(self, content):
|
||||||
|
"""Sends a custom msg to the widget model in the front-end.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
content : dict
|
||||||
|
Content of the message to send.
|
||||||
|
"""
|
||||||
|
self._send({"method": "custom",
|
||||||
|
"custom_content": content})
|
||||||
|
|
||||||
|
|
||||||
|
def on_msg(self, callback, remove=False):
|
||||||
|
"""Register a callback for when a custom msg is recieved from the front-end
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
callback: method handler
|
||||||
|
Can have a signature of:
|
||||||
|
- callback(content)
|
||||||
|
- callback(sender, content)
|
||||||
|
remove: bool
|
||||||
|
True if the callback should be unregistered."""
|
||||||
|
if remove and callback in self._msg_callbacks:
|
||||||
|
self._msg_callbacks.remove(callback)
|
||||||
|
elif not remove and not callback in self._msg_callbacks:
|
||||||
|
self._msg_callbacks.append(callback)
|
||||||
|
|
||||||
|
|
||||||
|
def on_displayed(self, callback, remove=False):
|
||||||
|
"""Register a callback to be called when the widget has been displayed
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
callback: method handler
|
||||||
|
Can have a signature of:
|
||||||
|
- callback()
|
||||||
|
- callback(sender)
|
||||||
|
- callback(sender, view_name)
|
||||||
|
- callback(sender, **kwargs)
|
||||||
|
kwargs from display call passed through without modification.
|
||||||
|
remove: bool
|
||||||
|
True if the callback should be unregistered."""
|
||||||
|
if remove and callback in self._display_callbacks:
|
||||||
|
self._display_callbacks.remove(callback)
|
||||||
|
elif not remove and not callback in self._display_callbacks:
|
||||||
|
self._display_callbacks.append(callback)
|
||||||
|
|
||||||
|
|
||||||
|
# Support methods
|
||||||
|
def _repr_widget_(self, **kwargs):
|
||||||
|
"""Function that is called when `IPython.display.display` is called on
|
||||||
|
the widget.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
view_name: unicode (optional)
|
||||||
|
View to display in the frontend. Overrides default_view_name."""
|
||||||
|
view_name = kwargs.get('view_name', self.default_view_name)
|
||||||
|
|
||||||
|
# Create a communication.
|
||||||
|
self._open_communication()
|
||||||
|
|
||||||
|
# Make sure model is syncronized
|
||||||
|
self.send_state()
|
||||||
|
|
||||||
|
# Show view.
|
||||||
|
self._send({"method": "display", "view_name": view_name})
|
||||||
|
self._displayed = True
|
||||||
|
self._handle_displayed(**kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
def _open_communication(self):
|
||||||
|
"""Opens a communication with the front-end."""
|
||||||
|
# Create a comm.
|
||||||
|
if not hasattr(self, '_comm') or self._comm is None:
|
||||||
|
self._comm = Comm(target_name=self.target_name)
|
||||||
|
self._comm.on_msg(self._handle_msg)
|
||||||
|
self._comm.on_close(self._close_communication)
|
||||||
|
|
||||||
|
|
||||||
|
def _close_communication(self):
|
||||||
|
"""Closes a communication with the front-end."""
|
||||||
|
if hasattr(self, '_comm') and self._comm is not None:
|
||||||
|
try:
|
||||||
|
self._comm.close()
|
||||||
|
finally:
|
||||||
|
self._comm = None
|
||||||
|
|
||||||
|
|
||||||
|
def _send(self, msg):
|
||||||
|
"""Sends a message to the model in the front-end"""
|
||||||
|
if self._comm is not None:
|
||||||
|
self._comm.send(msg)
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
return False
|
||||||
|
|
||||||
|
class Widget(BaseWidget):
|
||||||
|
|
||||||
|
_children = List(Instance('IPython.html.widgets.widget.Widget'))
|
||||||
|
_children_lists_attr = List(Unicode, ['_children'])
|
||||||
|
visible = Bool(True, help="Whether or not the widget is visible.")
|
||||||
|
|
||||||
|
# Private/protected declarations
|
||||||
|
_css = Dict() # Internal CSS property dict
|
||||||
|
|
||||||
|
# Properties
|
||||||
|
@property
|
||||||
|
def keys(self):
|
||||||
|
keys = ['visible', '_css']
|
||||||
|
keys.extend(super(Widget, self).keys)
|
||||||
|
return keys
|
||||||
|
|
||||||
def get_css(self, key, selector=""):
|
def get_css(self, key, selector=""):
|
||||||
"""Get a CSS property of the widget. Note, this function does not
|
"""Get a CSS property of the widget. Note, this function does not
|
||||||
actually request the CSS from the front-end; Only properties that have
|
actually request the CSS from the front-end; Only properties that have
|
||||||
@ -329,113 +443,3 @@ class Widget(LoggingConfigurable):
|
|||||||
self._send({"method": "remove_class",
|
self._send({"method": "remove_class",
|
||||||
"class_list": class_name,
|
"class_list": class_name,
|
||||||
"selector": selector})
|
"selector": selector})
|
||||||
|
|
||||||
|
|
||||||
def send(self, content):
|
|
||||||
"""Sends a custom msg to the widget model in the front-end.
|
|
||||||
|
|
||||||
Parameters
|
|
||||||
----------
|
|
||||||
content : dict
|
|
||||||
Content of the message to send.
|
|
||||||
"""
|
|
||||||
self._send({"method": "custom",
|
|
||||||
"custom_content": content})
|
|
||||||
|
|
||||||
|
|
||||||
def on_msg(self, callback, remove=False):
|
|
||||||
"""Register a callback for when a custom msg is recieved from the front-end
|
|
||||||
|
|
||||||
Parameters
|
|
||||||
----------
|
|
||||||
callback: method handler
|
|
||||||
Can have a signature of:
|
|
||||||
- callback(content)
|
|
||||||
- callback(sender, content)
|
|
||||||
remove: bool
|
|
||||||
True if the callback should be unregistered."""
|
|
||||||
if remove and callback in self._msg_callbacks:
|
|
||||||
self._msg_callbacks.remove(callback)
|
|
||||||
elif not remove and not callback in self._msg_callbacks:
|
|
||||||
self._msg_callbacks.append(callback)
|
|
||||||
|
|
||||||
|
|
||||||
def on_displayed(self, callback, remove=False):
|
|
||||||
"""Register a callback to be called when the widget has been displayed
|
|
||||||
|
|
||||||
Parameters
|
|
||||||
----------
|
|
||||||
callback: method handler
|
|
||||||
Can have a signature of:
|
|
||||||
- callback()
|
|
||||||
- callback(sender)
|
|
||||||
- callback(sender, view_name)
|
|
||||||
- callback(sender, **kwargs)
|
|
||||||
kwargs from display call passed through without modification.
|
|
||||||
remove: bool
|
|
||||||
True if the callback should be unregistered."""
|
|
||||||
if remove and callback in self._display_callbacks:
|
|
||||||
self._display_callbacks.remove(callback)
|
|
||||||
elif not remove and not callback in self._display_callbacks:
|
|
||||||
self._display_callbacks.append(callback)
|
|
||||||
|
|
||||||
|
|
||||||
# Support methods
|
|
||||||
def _repr_widget_(self, **kwargs):
|
|
||||||
"""Function that is called when `IPython.display.display` is called on
|
|
||||||
the widget.
|
|
||||||
|
|
||||||
Parameters
|
|
||||||
----------
|
|
||||||
view_name: unicode (optional)
|
|
||||||
View to display in the frontend. Overrides default_view_name."""
|
|
||||||
view_name = kwargs.get('view_name', self.default_view_name)
|
|
||||||
|
|
||||||
# Create a communication.
|
|
||||||
self._open_communication()
|
|
||||||
|
|
||||||
# Make sure model is syncronized
|
|
||||||
self.send_state()
|
|
||||||
|
|
||||||
# Show view.
|
|
||||||
if self.parent is None or self.parent._comm is None:
|
|
||||||
self._send({"method": "display", "view_name": view_name})
|
|
||||||
else:
|
|
||||||
self._send({"method": "display",
|
|
||||||
"view_name": view_name,
|
|
||||||
"parent": self.parent._comm.comm_id})
|
|
||||||
self._handle_displayed(**kwargs)
|
|
||||||
self._displayed = True
|
|
||||||
|
|
||||||
# Now display children if any.
|
|
||||||
for child in self._children:
|
|
||||||
if child != self:
|
|
||||||
child._repr_widget_()
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _open_communication(self):
|
|
||||||
"""Opens a communication with the front-end."""
|
|
||||||
# Create a comm.
|
|
||||||
if not hasattr(self, '_comm') or self._comm is None:
|
|
||||||
self._comm = Comm(target_name=self.target_name)
|
|
||||||
self._comm.on_msg(self._handle_msg)
|
|
||||||
self._comm.on_close(self._close_communication)
|
|
||||||
|
|
||||||
|
|
||||||
def _close_communication(self):
|
|
||||||
"""Closes a communication with the front-end."""
|
|
||||||
if hasattr(self, '_comm') and self._comm is not None:
|
|
||||||
try:
|
|
||||||
self._comm.close()
|
|
||||||
finally:
|
|
||||||
self._comm = None
|
|
||||||
|
|
||||||
|
|
||||||
def _send(self, msg):
|
|
||||||
"""Sends a message to the model in the front-end"""
|
|
||||||
if hasattr(self, '_comm') and self._comm is not None:
|
|
||||||
self._comm.send(msg)
|
|
||||||
return True
|
|
||||||
else:
|
|
||||||
return False
|
|
||||||
|
Loading…
Reference in New Issue
Block a user