def start_cube_extraction(viewer): """Extract cubes for training""" if not output_filename.exists(): print("No curation results have been saved. " "Please save before extracting cubes") else: print(f"Saving cubes to: {output_directory}") run_extraction( output_filename, output_directory, args.signal_image_paths, args.background_image_paths, args.cube_depth, args.cube_width, args.cube_height, args.x_pixel_um, args.y_pixel_um, args.z_pixel_um, args.x_pixel_um_network, args.y_pixel_um_network, args.z_pixel_um_network, args.max_ram, args.n_free_cpus, args.save_empty_cubes, ) print("Saving yaml file to use for training") save_yaml_file(output_directory) print("Closing window") QApplication.closeAllWindows() print("Finished! You may now annotate more " "datasets, or go straight to training")
def powrot(self): self.window = QtWidgets.QMainWindow() self.ui = main.Ui_MainWindow() self.ui.setupUi(self.window) QApplication.closeAllWindows() self.qt2_app = oknoAdmin.App() self.qt2_app.show()
def close(self) -> None: try: self.stop_music() QApplication.closeAllWindows() except Exception as e: sys.exit(1) if DEBUG: print(e) else: print('App closed')
def testQPushButtonQLabel(self): button = QPushButton() label = QLabel() button.pressed.connect(lambda: label.setText("Hello!")) self.assertTrue(label.text() == '') QTest.mouseClick(button, Qt.LeftButton) self.assertTrue(label.text() == "Hello!") QApplication.closeAllWindows()
def testQPushButton(self): button = QPushButton() button.setCheckable(True) button.setChecked(False) QTest.mouseClick(button, Qt.LeftButton) self.assertTrue(button.isChecked()) QTest.mouseClick(button, Qt.LeftButton) self.assertFalse(button.isChecked()) QApplication.closeAllWindows()
def conv_to_b(v): selected_points = v.layers[-1].selected_data if len(selected_points) == 1: print(f"labeled point at {v.layers[-1].data}") z = int(v.layers[-1].data[0][0]) y = int(v.layers[-1].data[0][1]) x = int(v.layers[-1].data[0][2]) seed_point = (x, y, z) seed_point_str = f"{x}_{y}_{z}" print(f"{seed_point} extracted, getting fiber track from this") get_fiber_track( reg_dir / atlas_name, reg_dir / background_channel_name, seed_point, reg_dir / output_name.format(seed_point_str), ) print("closing application...") QApplication.closeAllWindows()
class QtFrontend(ViewSBFrontend): """ Qt Frontend that consumes packets for display. """ UI_NAME = 'qt' UI_DESCRIPTION = 'unstable GUI in Qt' # So, Qt's tree widgets require that column 0 have the expand arrow, but you _can_ change # where column 0 is displayed. # We want the summary column to have the expand arrow, so we'll swap it # with the timestamp column in __init__(). COLUMN_TIMESTAMP = 5 COLUMN_DEVICE = 1 COLUMN_ENDPOINT = 2 COLUMN_DIRECTION = 3 COLUMN_LENGTH = 4 COLUMN_SUMMARY = 0 COLUMN_STATUS = 6 COLUMN_DATA = 7 @staticmethod def reason_to_be_disabled(): try: import PySide2 except ImportError: return "PySide2 (Qt library) not available." return None @staticmethod def _stringify_list(lst): """ Tiny helper than runs the str constructor on every item in a list, but specifically handles two cases: 1) the object in question is None, which we instead want to display as an empty string, 2) the resulting string contains a null character, which Qt doesn't like, so we'll represent it to the user as, literally, \0. """ return [ str(x).replace('\0', r'\0') if x is not None else '' for x in lst ] def _create_item_for_packet(self, viewsb_packet): """ Creates a QTreeWidgetItem for a given ViewSBPacket. Args: viewsb_packet -- The ViewSBPacket to create the QTreeWidgetItem from. Returns a QTreeWidgetItem. """ def get_packet_string_array(viewsb_packet): """ Tiny helper to return and stringify the common fields used for the columns of tree items. """ direction = viewsb_packet.direction.name if viewsb_packet.direction is not None else '' length = len( viewsb_packet.data) if viewsb_packet.data is not None else '' return self._stringify_list([ viewsb_packet.summarize(), viewsb_packet.device_address, viewsb_packet.endpoint_number, direction, length, viewsb_packet.timestamp, viewsb_packet.summarize_status(), viewsb_packet.summarize_data() ]) + [viewsb_packet] item = QTreeWidgetItem(get_packet_string_array(viewsb_packet)) # Give the item a reference to the original packet object. item.setData(0, QtCore.Qt.UserRole, viewsb_packet) return item def _recursively_walk_packet(self, viewsb_packet): """ Recursively walks packet subordinates, batching QTreeWidgetItem.addChildren as much as possible. Args: viewsb_packet -- The top-level packet (as far as the caller's context is concerned). """ packet_item = self._create_item_for_packet(viewsb_packet) packet_children_list = [] for sub_packet in viewsb_packet.subordinate_packets: # Create the item for this packet, and recursively fill its children. packet_children_list.append( self._recursively_walk_packet(sub_packet)) packet_item.addChildren(packet_children_list) return packet_item def __init__(self): """ Sets up the Qt UI. """ QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts) signal.signal( signal.SIGINT, signal.SIG_DFL) # fix SIGINT handling - cleanly exit on ctrl+c self.app = QApplication([]) self.ui_file = QtCore.QFile( os.path.dirname(os.path.realpath(__file__)) + '/qt.ui') self.loader = QUiLoader() self.loader.registerCustomWidget(ViewSBQTreeWidget) self.loader.registerCustomWidget(ViewSBHexView) self.window = self.loader.load(self.ui_file) # type: QMainWindow # Swap columns 0 and 5 to put the expand arrow on the summary column. self.window.usb_tree_widget.header().swapSections(0, 5) self.window.usb_tree_widget.setColumnWidth(self.COLUMN_TIMESTAMP, 120) self.window.usb_tree_widget.setColumnWidth(self.COLUMN_DEVICE, 32) self.window.usb_tree_widget.setColumnWidth(self.COLUMN_ENDPOINT, 24) self.window.usb_tree_widget.setColumnWidth(self.COLUMN_DIRECTION, 42) self.window.usb_tree_widget.setColumnWidth(self.COLUMN_LENGTH, 60) self.window.usb_tree_widget.setColumnWidth(self.COLUMN_SUMMARY, 500) self.window.update_timer = QtCore.QTimer() self.window.update_timer.timeout.connect(self._update) self.window.usb_tree_widget.currentItemChanged.connect( self._tree_current_item_changed) self.window.usb_tree_widget = self.window.usb_tree_widget self.window.usb_tree_widget.sortByColumn(0) self.window.showMaximized() def _update(self): """ Called by the QTimer `update_timer`; collects packets the queue and adds them to the tree view. We use this instead of calling `handle_communications` and defining `handle_incoming_packet`, because adding items one at a time as we receive them is slower than batching them. Note: Since this is called via a QTimer signal, this method runs in the UI thread. """ # If the process manager told us to stop (which might happen if e.g. the backend exits), # then stop and exit. if self.termination_event.is_set(): self.app.closeAllWindows() packet_list = [] try: # Get as many packets as we can as quick as we can. while True: packet = self.data_queue.get_nowait() packet_list.append(packet) # But the instant it's empty, don't wait for any more; just send them to be processed. except multiprocessing.queues.Empty: pass finally: self.add_packets(packet_list) def _tree_current_item_changed(self, current_item, _previous_item): """ Handler for the QTreeWidget.currentItemChanged() signal that populates the side panels with detail fields and a hex representation of the current packet. """ # Clear the details widget. self.window.usb_details_tree_widget.clear() current_packet = current_item.data(0, QtCore.Qt.UserRole) # A list of 2-tuples: first element is a table title, and the second is usually a string:string dict. detail_fields = current_packet.get_detail_fields() if detail_fields: self.update_detail_fields(detail_fields) self.window.usb_hex_view.populate(current_packet.get_raw_data()) def update_detail_fields(self, detail_fields): """ Populates the detail view with the relevant fields for the selected packet. """ # Each table will have a root item in the details view. root_items = [] for table in detail_fields: title = table[0] root = QTreeWidgetItem([title]) children = [] fields = table[1] # The usual case: a str:str dict. if isinstance(fields, dict): for key, value in fields.items(): children.append( QTreeWidgetItem(self._stringify_list([key, value]))) # Sometimes it'll just be a 1-column list. elif isinstance(fields, list): for item in fields: children.append( QTreeWidgetItem(self._stringify_list([item]))) # Sometimes it'll just be a string, or a `bytes` instance. else: children.append(QTreeWidgetItem(self._stringify_list([fields ]))) root.addChildren(children) # Add an empty "item" between each table. root_items.extend([root, QTreeWidgetItem([])]) self.window.usb_details_tree_widget.addTopLevelItems(root_items) self.window.usb_details_tree_widget.expandAll() self.window.usb_details_tree_widget.resizeColumnToContents(0) self.window.usb_details_tree_widget.resizeColumnToContents(1) def add_packets(self, viewsb_packets): """ Adds a list of top-level ViewSB packets to the tree. We're in the UI thread; every bit of overhead counts, so let's batch as much as possible. """ top_level_items_list = [] for viewsb_packet in viewsb_packets: # Create the item for this packet, and recursively fill its children. top_level_items_list.append( self._recursively_walk_packet(viewsb_packet)) self.window.usb_tree_widget.addTopLevelItems(top_level_items_list) def run(self): """ Overrides ViewSBFrontend.run(). """ # TODO: is there a better value than 100 ms? Should it be configurable by the Analyzer? self.window.update_timer.start(100) self.app.exec_() self.stop() def stop(self): self.app.closeAllWindows() self.termination_event.set()
def close_viewer(viewer): print("\nClosing viewer") QApplication.closeAllWindows()
def quit(v): QApplication.closeAllWindows()
class QtFrontend(ViewSBFrontend): """ Qt Frontend that consumes packets for display. """ UI_NAME = 'qt' UI_DESCRIPTION = 'proof-of-concept, unstable GUI in Qt' @staticmethod def reason_to_be_disabled(): # If we weren't able to import pyside2, disable the library. if 'QWidget' not in globals(): return "pyside2 (qt library) not available" return None def __init__(self): """ Sets up the Qt UI. """ QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts) self.app = QApplication([]) self.ui_file = QtCore.QFile('viewsb/frontends/qt.ui') self.loader = QUiLoader() self.window: QtWidgets.QMainWindow = self.loader.load(self.ui_file) # The default column size of 100 is too small for the summary column. self.window.usb_tree_widget.setColumnWidth(1, 400) self.window.update_timer = QtCore.QTimer() self.window.update_timer.timeout.connect(self.update) self.window.usb_tree_widget.currentItemChanged.connect( self.tree_current_item_changed) self.window.usb_tree_widget: QtWidgets.QTreeWidget = self.window.usb_tree_widget self.window.usb_tree_widget.sortByColumn(0) self.window.showMaximized() def update(self): """ Called by the QTimer `update_timer`, collects packets waiting the queue and adds them to the tree view. Note: Since this is called via a QTimer signal, this method runs in the UI thread. """ packet_list = [] try: # Get as many packets as we can as quick as we can. while (True): packet = self.data_queue.get_nowait() packet_list.append(packet) # But the instant it's empty, don't wait for any more; just send them to be processed. except multiprocessing.queues.Empty: pass finally: # In case the queue was empty in the first place and didn't have anything ready. if len(packet_list) > 0: self.add_packets(packet_list) def add_packets(self, viewsb_packets: []): """ Adds a list of top-level ViewSB packets to the tree. We're in the UI thread; every bit of overhead counts, so let's batch as much as possible. """ for viewsb_packet in viewsb_packets: top_level_item = QtWidgets.QTreeWidgetItem( get_packet_string_array(viewsb_packet)) top_level_item.setData(0, QtCore.Qt.UserRole, viewsb_packet) list_of_children = [] recursive_packet_walk(viewsb_packet, list_of_children) top_level_item.addChildren(list_of_children) self.window.usb_tree_widget.addTopLevelItem(top_level_item) def tree_current_item_changed(self, current_item, previous_item): """ Use the side panel to show a detailed view of the current item. """ # Clear the details widget. self.window.usb_details_tree_widget.clear() self.window.usb_details_tree_widget.setColumnCount(2) current_packet: ViewSBPacket = current_item.data(0, QtCore.Qt.UserRole) # A list of 2-tuples: first element is a table title, and the second is usually a string: string dict detail_fields = current_packet.get_detail_fields() # Each table will have a root item in the details view. root_items = [] for table in detail_fields: title: str = table[0] root = QtWidgets.QTreeWidgetItem([title]) children = [] fields = table[1] # The usual case: a str: str dict. if type(fields) == type({}): for key, value in fields.items(): children.append( QtWidgets.QTreeWidgetItem(stringify_list([key, value]))) # Sometimes a descriptor will just be a 1-column list. elif type(fields) == type([]): for item in fields: children.append(QtWidgets.QTreeWidgetItem([str(item)])) # Sometimes it'll just be a string, or, if it's an unknown descriptor, a `bytes` instance. else: children.append(QtWidgets.QTreeWidgetItem([str(fields)])) root.addChildren(children) # Add an empty "item" between each table root_items += [root, QtWidgets.QTreeWidgetItem([])] self.window.usb_details_tree_widget.addTopLevelItems(root_items) self.window.usb_details_tree_widget.expandAll() self.window.usb_details_tree_widget.resizeColumnToContents(0) self.window.usb_details_tree_widget.resizeColumnToContents(1) def run(self): """ Overrides `ViewSBFrontend.run()` """ # TODO: is there a better value than 100 ms? Should it be configurable by the Analyzer? self.window.update_timer.start(100) self.app.exec_() self.stop() def stop(self): self.app.closeAllWindows() self.termination_event.set()