|
| 1 | +import sys |
| 2 | +from threading import local |
| 3 | +from unittest.mock import Mock |
| 4 | + |
| 5 | +from IPython.core.displaypub import DisplayPublisher |
| 6 | +from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC |
| 7 | +from jupyter_client.session import Session, extract_header |
| 8 | +from traitlets import Any, CBytes, Dict, Instance, Type, default |
| 9 | + |
| 10 | + |
| 11 | +def encode_images(obj): |
| 12 | + # no-op in ipykernel |
| 13 | + return obj |
| 14 | + |
| 15 | + |
| 16 | +def json_clean(obj): |
| 17 | + # no-op in ipykernel |
| 18 | + return obj |
| 19 | + |
| 20 | + |
| 21 | +# based on the zmq display publisher from ipykernel |
| 22 | +# ideally this goes out of ipykernel |
| 23 | +class SolaraDisplayPublisher(DisplayPublisher): |
| 24 | + """A display publisher that publishes data using a ZeroMQ PUB socket.""" |
| 25 | + |
| 26 | + session = Instance(Session, allow_none=True) |
| 27 | + pub_socket = Any(allow_none=True) |
| 28 | + parent_header = Dict({}) |
| 29 | + topic = CBytes(b"display_data") |
| 30 | + |
| 31 | + _thread_local = Any() |
| 32 | + |
| 33 | + def set_parent(self, parent): |
| 34 | + """Set the parent for outbound messages.""" |
| 35 | + self.parent_header = extract_header(parent) |
| 36 | + |
| 37 | + def _flush_streams(self): |
| 38 | + """flush IO Streams prior to display""" |
| 39 | + sys.stdout.flush() |
| 40 | + sys.stderr.flush() |
| 41 | + |
| 42 | + @default("_thread_local") |
| 43 | + def _default_thread_local(self): |
| 44 | + """Initialize our thread local storage""" |
| 45 | + return local() |
| 46 | + |
| 47 | + @property |
| 48 | + def _hooks(self): |
| 49 | + if not hasattr(self._thread_local, "hooks"): |
| 50 | + # create new list for a new thread |
| 51 | + self._thread_local.hooks = [] |
| 52 | + return self._thread_local.hooks |
| 53 | + |
| 54 | + def publish( |
| 55 | + self, |
| 56 | + data, |
| 57 | + metadata=None, |
| 58 | + transient=None, |
| 59 | + update=False, |
| 60 | + ): |
| 61 | + """Publish a display-data message |
| 62 | +
|
| 63 | + Parameters |
| 64 | + ---------- |
| 65 | + data : dict |
| 66 | + A mime-bundle dict, keyed by mime-type. |
| 67 | + metadata : dict, optional |
| 68 | + Metadata associated with the data. |
| 69 | + transient : dict, optional, keyword-only |
| 70 | + Transient data that may only be relevant during a live display, |
| 71 | + such as display_id. |
| 72 | + Transient data should not be persisted to documents. |
| 73 | + update : bool, optional, keyword-only |
| 74 | + If True, send an update_display_data message instead of display_data. |
| 75 | + """ |
| 76 | + self._flush_streams() |
| 77 | + if metadata is None: |
| 78 | + metadata = {} |
| 79 | + if transient is None: |
| 80 | + transient = {} |
| 81 | + self._validate_data(data, metadata) |
| 82 | + content = {} |
| 83 | + content["data"] = encode_images(data) |
| 84 | + content["metadata"] = metadata |
| 85 | + content["transient"] = transient |
| 86 | + |
| 87 | + msg_type = "update_display_data" if update else "display_data" |
| 88 | + |
| 89 | + # Use 2-stage process to send a message, |
| 90 | + # in order to put it through the transform |
| 91 | + # hooks before potentially sending. |
| 92 | + msg = self.session.msg(msg_type, json_clean(content), parent=self.parent_header) |
| 93 | + |
| 94 | + # Each transform either returns a new |
| 95 | + # message or None. If None is returned, |
| 96 | + # the message has been 'used' and we return. |
| 97 | + for hook in self._hooks: |
| 98 | + msg = hook(msg) |
| 99 | + if msg is None: |
| 100 | + return |
| 101 | + |
| 102 | + self.session.send( |
| 103 | + self.pub_socket, |
| 104 | + msg, |
| 105 | + ident=self.topic, |
| 106 | + ) |
| 107 | + |
| 108 | + def clear_output(self, wait=False): |
| 109 | + """Clear output associated with the current execution (cell). |
| 110 | +
|
| 111 | + Parameters |
| 112 | + ---------- |
| 113 | + wait : bool (default: False) |
| 114 | + If True, the output will not be cleared immediately, |
| 115 | + instead waiting for the next display before clearing. |
| 116 | + This reduces bounce during repeated clear & display loops. |
| 117 | +
|
| 118 | + """ |
| 119 | + content = dict(wait=wait) |
| 120 | + self._flush_streams() |
| 121 | + self.session.send( |
| 122 | + self.pub_socket, |
| 123 | + "clear_output", |
| 124 | + content, |
| 125 | + parent=self.parent_header, |
| 126 | + ident=self.topic, |
| 127 | + ) |
| 128 | + |
| 129 | + def register_hook(self, hook): |
| 130 | + """ |
| 131 | + Registers a hook with the thread-local storage. |
| 132 | +
|
| 133 | + Parameters |
| 134 | + ---------- |
| 135 | + hook : Any callable object |
| 136 | +
|
| 137 | + Returns |
| 138 | + ------- |
| 139 | + Either a publishable message, or `None`. |
| 140 | + The DisplayHook objects must return a message from |
| 141 | + the __call__ method if they still require the |
| 142 | + `session.send` method to be called after transformation. |
| 143 | + Returning `None` will halt that execution path, and |
| 144 | + session.send will not be called. |
| 145 | + """ |
| 146 | + self._hooks.append(hook) |
| 147 | + |
| 148 | + def unregister_hook(self, hook): |
| 149 | + """ |
| 150 | + Un-registers a hook with the thread-local storage. |
| 151 | +
|
| 152 | + Parameters |
| 153 | + ---------- |
| 154 | + hook : Any callable object which has previously been |
| 155 | + registered as a hook. |
| 156 | +
|
| 157 | + Returns |
| 158 | + ------- |
| 159 | + bool - `True` if the hook was removed, `False` if it wasn't |
| 160 | + found. |
| 161 | + """ |
| 162 | + try: |
| 163 | + self._hooks.remove(hook) |
| 164 | + return True |
| 165 | + except ValueError: |
| 166 | + return False |
| 167 | + |
| 168 | + |
| 169 | +class SolaraInteractiveShell(InteractiveShell): |
| 170 | + display_pub_class = Type(SolaraDisplayPublisher) |
| 171 | + history_manager = Any() |
| 172 | + |
| 173 | + def set_parent(self, parent): |
| 174 | + """Tell the children about the parent message.""" |
| 175 | + self.display_pub.set_parent(parent) |
| 176 | + |
| 177 | + def init_history(self): |
| 178 | + self.history_manager = Mock() |
| 179 | + |
| 180 | + |
| 181 | +InteractiveShellABC.register(SolaraInteractiveShell) |
0 commit comments