|
| 1 | +import logging |
| 2 | +import asyncio |
| 3 | +import sys |
| 4 | +import shlex |
| 5 | +from functools import partial |
| 6 | + |
| 7 | +from quamash import QtCore, QtGui, QtWidgets |
| 8 | +from pyqtgraph import dockarea |
| 9 | + |
| 10 | +from artiq.protocols.pipe_ipc import AsyncioParentComm |
| 11 | +from artiq.protocols import pyon |
| 12 | + |
| 13 | + |
| 14 | +logger = logging.getLogger(__name__) |
| 15 | + |
| 16 | + |
| 17 | +class AppletIPCServer(AsyncioParentComm): |
| 18 | + def __init__(self, datasets_sub): |
| 19 | + AsyncioParentComm.__init__(self) |
| 20 | + self.datasets_sub = datasets_sub |
| 21 | + self.datasets = set() |
| 22 | + |
| 23 | + def write_pyon(self, obj): |
| 24 | + self.write(pyon.encode(obj).encode() + b"\n") |
| 25 | + |
| 26 | + async def read_pyon(self): |
| 27 | + line = await self.readline() |
| 28 | + return pyon.decode(line.decode()) |
| 29 | + |
| 30 | + def _synthesize_init(self, data): |
| 31 | + struct = {k: v for k, v in data.items() if k in self.datasets} |
| 32 | + return {"action": "init", |
| 33 | + "struct": struct} |
| 34 | + |
| 35 | + def _on_mod(self, mod): |
| 36 | + if mod["action"] == "init": |
| 37 | + mod = self._synthesize_init(mod["struct"]) |
| 38 | + else: |
| 39 | + if mod["path"]: |
| 40 | + if mod["path"][0] not in self.datasets: |
| 41 | + return |
| 42 | + elif mod["action"] in {"setitem", "delitem"}: |
| 43 | + if mod["key"] not in self.datasets: |
| 44 | + return |
| 45 | + self.write_pyon({"action": "mod", "mod": mod}) |
| 46 | + |
| 47 | + async def serve(self, embed_cb): |
| 48 | + self.datasets_sub.notify_cbs.append(self._on_mod) |
| 49 | + try: |
| 50 | + while True: |
| 51 | + obj = await self.read_pyon() |
| 52 | + try: |
| 53 | + action = obj["action"] |
| 54 | + if action == "embed": |
| 55 | + embed_cb(obj["win_id"]) |
| 56 | + self.write_pyon({"action": "embed_done"}) |
| 57 | + elif action == "subscribe": |
| 58 | + self.datasets = obj["datasets"] |
| 59 | + if self.datasets_sub.model is not None: |
| 60 | + mod = self._synthesize_init( |
| 61 | + self.datasets_sub.model.backing_store) |
| 62 | + self.write_pyon({"action": "mod", "mod": mod}) |
| 63 | + else: |
| 64 | + raise ValueError("unknown action in applet message") |
| 65 | + except: |
| 66 | + logger.warning("error processing applet message", |
| 67 | + exc_info=True) |
| 68 | + self.write_pyon({"action": "error"}) |
| 69 | + except asyncio.CancelledError: |
| 70 | + pass |
| 71 | + except: |
| 72 | + logger.error("error processing data from applet, " |
| 73 | + "server stopped", exc_info=True) |
| 74 | + finally: |
| 75 | + self.datasets_sub.notify_cbs.remove(self._on_mod) |
| 76 | + |
| 77 | + def start(self, embed_cb): |
| 78 | + self.server_task = asyncio.ensure_future(self.serve(embed_cb)) |
| 79 | + |
| 80 | + async def stop(self): |
| 81 | + self.server_task.cancel() |
| 82 | + await asyncio.wait([self.server_task]) |
| 83 | + |
| 84 | + |
| 85 | +class AppletDock(dockarea.Dock): |
| 86 | + def __init__(self, datasets_sub, uid, name, command): |
| 87 | + dockarea.Dock.__init__(self, "applet" + str(uid), |
| 88 | + label="Applet: " + name, |
| 89 | + closable=True) |
| 90 | + self.setMinimumSize(QtCore.QSize(500, 400)) |
| 91 | + self.datasets_sub = datasets_sub |
| 92 | + self.applet_name = name |
| 93 | + self.command = command |
| 94 | + |
| 95 | + def rename(self, name): |
| 96 | + self.applet_name = name |
| 97 | + self.label.setText("Applet: " + name) |
| 98 | + |
| 99 | + async def start(self): |
| 100 | + self.ipc = AppletIPCServer(self.datasets_sub) |
| 101 | + if "{ipc_address}" not in self.command: |
| 102 | + logger.warning("IPC address missing from command for %s", |
| 103 | + self.applet_name) |
| 104 | + command = self.command.format(python=sys.executable, |
| 105 | + ipc_address=self.ipc.get_address()) |
| 106 | + logger.debug("starting command %s for %s", command, self.applet_name) |
| 107 | + try: |
| 108 | + await self.ipc.create_subprocess(*shlex.split(command)) |
| 109 | + except: |
| 110 | + logger.warning("Applet %s failed to start", self.applet_name, |
| 111 | + exc_info=True) |
| 112 | + self.ipc.start(self.embed) |
| 113 | + |
| 114 | + def embed(self, win_id): |
| 115 | + logger.debug("capturing window 0x%x for %s", win_id, self.applet_name) |
| 116 | + embed_window = QtGui.QWindow.fromWinId(win_id) |
| 117 | + embed_widget = QtWidgets.QWidget.createWindowContainer(embed_window) |
| 118 | + self.addWidget(embed_widget) |
| 119 | + |
| 120 | + async def terminate(self): |
| 121 | + if hasattr(self, "ipc"): |
| 122 | + await self.ipc.stop() |
| 123 | + self.ipc.write_pyon({"action": "terminate"}) |
| 124 | + try: |
| 125 | + await asyncio.wait_for(self.ipc.process.wait(), 2.0) |
| 126 | + except: |
| 127 | + logger.warning("Applet %s failed to exit, killing", |
| 128 | + self.applet_name) |
| 129 | + try: |
| 130 | + self.ipc.process.kill() |
| 131 | + except ProcessLookupError: |
| 132 | + pass |
| 133 | + await self.ipc.process.wait() |
| 134 | + del self.ipc |
| 135 | + |
| 136 | + async def restart(self): |
| 137 | + await self.terminate() |
| 138 | + await self.start() |
| 139 | + |
| 140 | + |
| 141 | +_templates = [ |
| 142 | + ("Big number", "{python} -m artiq.applets.big_number " |
| 143 | + "--embed {ipc_address} NUMBER_DATASET"), |
| 144 | + ("Histogram", "{python} -m artiq.applets.plot_hist " |
| 145 | + "--embed {ipc_address} COUNTS_DATASET " |
| 146 | + "--x BIN_BOUNDARIES_DATASET"), |
| 147 | + ("XY", "{python} -m artiq.applets.plot_xy " |
| 148 | + "--embed {ipc_address} Y_DATASET --x X_DATASET " |
| 149 | + "--error ERROR_DATASET --fit FIT_DATASET"), |
| 150 | + ("XY + Histogram", "{python} -m artiq.applets.plot_xy_hist " |
| 151 | + "--embed {ipc_address} X_DATASET " |
| 152 | + "HIST_BIN_BOUNDARIES_DATASET " |
| 153 | + "HISTS_COUNTS_DATASET"), |
| 154 | +] |
| 155 | + |
| 156 | + |
| 157 | +class AppletsDock(dockarea.Dock): |
| 158 | + def __init__(self, dock_area, datasets_sub): |
| 159 | + self.dock_area = dock_area |
| 160 | + self.datasets_sub = datasets_sub |
| 161 | + self.dock_to_checkbox = dict() |
| 162 | + self.applet_uids = set() |
| 163 | + self.workaround_pyqtgraph_bug = False |
| 164 | + |
| 165 | + dockarea.Dock.__init__(self, "Applets") |
| 166 | + self.setMinimumSize(QtCore.QSize(850, 450)) |
| 167 | + |
| 168 | + self.table = QtWidgets.QTableWidget(0, 3) |
| 169 | + self.table.setHorizontalHeaderLabels(["Enable", "Name", "Command"]) |
| 170 | + self.table.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows) |
| 171 | + self.table.setSelectionMode(QtGui.QAbstractItemView.SingleSelection) |
| 172 | + self.table.horizontalHeader().setStretchLastSection(True) |
| 173 | + self.table.horizontalHeader().setResizeMode( |
| 174 | + QtGui.QHeaderView.ResizeToContents) |
| 175 | + self.table.verticalHeader().setResizeMode( |
| 176 | + QtGui.QHeaderView.ResizeToContents) |
| 177 | + self.table.verticalHeader().hide() |
| 178 | + self.table.setTextElideMode(QtCore.Qt.ElideNone) |
| 179 | + self.addWidget(self.table) |
| 180 | + |
| 181 | + self.table.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu) |
| 182 | + new_action = QtGui.QAction("New applet", self.table) |
| 183 | + new_action.triggered.connect(self.new) |
| 184 | + self.table.addAction(new_action) |
| 185 | + templates_menu = QtGui.QMenu() |
| 186 | + for name, template in _templates: |
| 187 | + action = QtGui.QAction(name, self.table) |
| 188 | + action.triggered.connect(partial(self.new_template, template)) |
| 189 | + templates_menu.addAction(action) |
| 190 | + restart_action = QtGui.QAction("New applet from template", self.table) |
| 191 | + restart_action.setMenu(templates_menu) |
| 192 | + self.table.addAction(restart_action) |
| 193 | + restart_action = QtGui.QAction("Restart selected applet", self.table) |
| 194 | + restart_action.setShortcut("CTRL+R") |
| 195 | + restart_action.setShortcutContext(QtCore.Qt.WidgetShortcut) |
| 196 | + restart_action.triggered.connect(self.restart) |
| 197 | + self.table.addAction(restart_action) |
| 198 | + delete_action = QtGui.QAction("Delete selected applet", self.table) |
| 199 | + delete_action.setShortcut("DELETE") |
| 200 | + delete_action.setShortcutContext(QtCore.Qt.WidgetShortcut) |
| 201 | + delete_action.triggered.connect(self.delete) |
| 202 | + self.table.addAction(delete_action) |
| 203 | + |
| 204 | + self.table.cellChanged.connect(self.cell_changed) |
| 205 | + |
| 206 | + def create(self, uid, name, command): |
| 207 | + dock = AppletDock(self.datasets_sub, uid, name, command) |
| 208 | + # If a dock is floated and then dock state is restored, pyqtgraph |
| 209 | + # leaves a "phantom" window open. |
| 210 | + if self.workaround_pyqtgraph_bug: |
| 211 | + self.dock_area.addDock(dock) |
| 212 | + else: |
| 213 | + self.dock_area.floatDock(dock) |
| 214 | + asyncio.ensure_future(dock.start()) |
| 215 | + dock.sigClosed.connect(partial(self.on_dock_closed, dock)) |
| 216 | + return dock |
| 217 | + |
| 218 | + def cell_changed(self, row, column): |
| 219 | + if column == 0: |
| 220 | + item = self.table.item(row, column) |
| 221 | + if item.checkState() == QtCore.Qt.Checked: |
| 222 | + command = self.table.item(row, 2) |
| 223 | + if command: |
| 224 | + command = command.text() |
| 225 | + name = self.table.item(row, 1) |
| 226 | + if name is None: |
| 227 | + name = "" |
| 228 | + else: |
| 229 | + name = name.text() |
| 230 | + dock = self.create(item.applet_uid, name, command) |
| 231 | + item.applet_dock = dock |
| 232 | + self.dock_to_checkbox[dock] = item |
| 233 | + else: |
| 234 | + dock = item.applet_dock |
| 235 | + if dock is not None: |
| 236 | + # This calls self.on_dock_closed |
| 237 | + dock.close() |
| 238 | + elif column == 1 or column == 2: |
| 239 | + new_value = self.table.item(row, column).text() |
| 240 | + dock = self.table.item(row, 0).applet_dock |
| 241 | + if dock is not None: |
| 242 | + if column == 1: |
| 243 | + dock.rename(new_value) |
| 244 | + else: |
| 245 | + dock.command = new_value |
| 246 | + |
| 247 | + def on_dock_closed(self, dock): |
| 248 | + asyncio.ensure_future(dock.terminate()) |
| 249 | + checkbox_item = self.dock_to_checkbox[dock] |
| 250 | + checkbox_item.applet_dock = None |
| 251 | + del self.dock_to_checkbox[dock] |
| 252 | + checkbox_item.setCheckState(QtCore.Qt.Unchecked) |
| 253 | + |
| 254 | + def new(self, uid=None): |
| 255 | + if uid is None: |
| 256 | + uid = next(iter(set(range(len(self.applet_uids) + 1)) |
| 257 | + - self.applet_uids)) |
| 258 | + self.applet_uids.add(uid) |
| 259 | + |
| 260 | + row = self.table.rowCount() |
| 261 | + self.table.insertRow(row) |
| 262 | + checkbox = QtWidgets.QTableWidgetItem() |
| 263 | + checkbox.setFlags(QtCore.Qt.ItemIsSelectable | |
| 264 | + QtCore.Qt.ItemIsUserCheckable | |
| 265 | + QtCore.Qt.ItemIsEnabled) |
| 266 | + checkbox.setCheckState(QtCore.Qt.Unchecked) |
| 267 | + checkbox.applet_uid = uid |
| 268 | + checkbox.applet_dock = None |
| 269 | + self.table.setItem(row, 0, checkbox) |
| 270 | + self.table.setItem(row, 1, QtWidgets.QTableWidgetItem()) |
| 271 | + self.table.setItem(row, 2, QtWidgets.QTableWidgetItem()) |
| 272 | + return row |
| 273 | + |
| 274 | + def new_template(self, template): |
| 275 | + row = self.new() |
| 276 | + self.table.item(row, 2).setText(template) |
| 277 | + |
| 278 | + def restart(self): |
| 279 | + selection = self.table.selectedRanges() |
| 280 | + if selection: |
| 281 | + row = selection[0].topRow() |
| 282 | + dock = self.table.item(row, 0).applet_dock |
| 283 | + if dock is not None: |
| 284 | + asyncio.ensure_future(dock.restart()) |
| 285 | + |
| 286 | + def delete(self): |
| 287 | + selection = self.table.selectedRanges() |
| 288 | + if selection: |
| 289 | + row = selection[0].topRow() |
| 290 | + item = self.table.item(row, 0) |
| 291 | + dock = item.applet_dock |
| 292 | + if dock is not None: |
| 293 | + # This calls self.on_dock_closed |
| 294 | + dock.close() |
| 295 | + self.applet_uids.remove(item.applet_uid) |
| 296 | + self.table.removeRow(row) |
| 297 | + |
| 298 | + |
| 299 | + async def stop(self): |
| 300 | + for row in range(self.table.rowCount()): |
| 301 | + dock = self.table.item(row, 0).applet_dock |
| 302 | + if dock is not None: |
| 303 | + await dock.terminate() |
| 304 | + |
| 305 | + def save_state(self): |
| 306 | + state = [] |
| 307 | + for row in range(self.table.rowCount()): |
| 308 | + uid = self.table.item(row, 0).applet_uid |
| 309 | + enabled = self.table.item(row, 0).checkState() == QtCore.Qt.Checked |
| 310 | + name = self.table.item(row, 1).text() |
| 311 | + command = self.table.item(row, 2).text() |
| 312 | + state.append((uid, enabled, name, command)) |
| 313 | + return state |
| 314 | + |
| 315 | + def restore_state(self, state): |
| 316 | + self.workaround_pyqtgraph_bug = True |
| 317 | + for uid, enabled, name, command in state: |
| 318 | + row = self.new(uid) |
| 319 | + item = QtWidgets.QTableWidgetItem() |
| 320 | + item.setText(name) |
| 321 | + self.table.setItem(row, 1, item) |
| 322 | + item = QtWidgets.QTableWidgetItem() |
| 323 | + item.setText(command) |
| 324 | + self.table.setItem(row, 2, item) |
| 325 | + if enabled: |
| 326 | + self.table.item(row, 0).setCheckState(QtCore.Qt.Checked) |
| 327 | + self.workaround_pyqtgraph_bug = False |
0 commit comments