def tab2_add(): shift_time = self.tab2_shift_value.value() shift_direction = self.tab2_fast_radio.isChecked() direction_text = '빠르게' if shift_direction else '느리게' data = [2, shift_time, shift_direction] item = QTreeWidgetItem(self.que_list, [self.tab2_name, '자막 싱크 ' + str(shift_time) + '초 ' + direction_text]) item.setData(2, 2, data)
def populate_result_tree(self, src_idx_selection_ls): self.result_tree.clear() # -- Populate Selection TreeWidget --- trim_items = dict() for model_code in self.wizard.session.data.fakom_selection.keys(): trim = [t for t in self.wizard.session.data.import_data.models if t.model == model_code][0] trim_item_name = f'{trim.model_text} {model_code}' trim_item = QTreeWidgetItem([trim_item_name]) trim_item.setIcon(0, IconRsc.get_icon('car')) trim_items[trim_item_name] = trim_item for src_index in src_idx_selection_ls: trim_idx = self.get_index_group_parent(src_index) model = trim_idx.siblingAtColumn(Kg.VALUE).data(Qt.DisplayRole) trim_item_name = f'{trim_idx.siblingAtColumn(Kg.NAME).data(Qt.DisplayRole)} {model}' trim_item = trim_items.get(trim_item_name) trim_item.setData(0, Qt.UserRole, trim_idx) name = src_index.siblingAtColumn(Kg.NAME).data(Qt.DisplayRole) icon = src_index.siblingAtColumn(Kg.style_column).data(Qt.DecorationRole) or QIcon() item = QTreeWidgetItem(trim_item, [name]) item.setData(0, Qt.UserRole, src_index) item.setIcon(0, icon) # -- Expand DeltaGenResult Tree -- for trim_item in trim_items.values(): self.result_tree.addTopLevelItem(trim_item) self.result_tree.expandItem(trim_item)
def create_node(item: Any) -> QTreeWidgetItem: child_node = QTreeWidgetItem() child_node.setFlags(child_node.flags() | Qt.ItemIsUserCheckable) child_node.setCheckState(0, Qt.CheckState.Checked) child_node.setData(1, 0, item) return child_node
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 _init_widgets(self): self.clear() if self.simgr.am_none: return for stash_name, stash in self.simgr.stashes.items(): if not stash and stash_name not in ('active', 'deadended', 'avoided'): continue item = QTreeWidgetItem(self, ["%s (%d)" % (stash_name, len(stash))]) item.setFlags(item.flags() & ~Qt.ItemIsSelectable) for state in stash: subitem = QTreeWidgetItem(item, [str(state)]) subitem.setData(0, 1, state) item.addChild(subitem) self.addTopLevelItem(item) # errored states if self.simgr.errored: item = QTreeWidgetItem( self, ["%s (%d)" % ('errored', len(self.simgr.errored))]) item.setFlags(item.flags() & ~Qt.ItemIsSelectable) for estate in self.simgr.errored: subitem = QTreeWidgetItem(item, [str(estate)]) subitem.setData(0, 1, estate.state) item.addChild(subitem) self.addTopLevelItem(item)
def populatebomtree(): global bom, assy_top, assy_bot, viewtop, bomcolumns, selectionset bom = pandas.read_csv(os.path.join(BASE_FOLDER, 'Assembly\\bom.csv'), header=0) assy_top = pandas.read_csv(os.path.join(BASE_FOLDER, 'Assembly\\PnP_front.csv'), header=0) assy_bot = pandas.read_csv(os.path.join(BASE_FOLDER, 'Assembly\\PnP_back.csv'), header=0) tw = window.treeWidget_bom tw.clearSelection() tw.clear() assy_side = assy_top if viewtop else assy_bot for index, row in bom.iterrows(): selected = str.split(row['Parts'], ', ') pnp_refdes = assy_side['Name'] pnp_count = 0 parts_thisside = '' for refdes in selected: pnp_row = assy_side[pnp_refdes == refdes] if len(pnp_row) > 0: if (selectionset == None) or (refdes in selectionset): if pnp_count == 0: twi = QTreeWidgetItem(tw, row.filter(bomcolumns).tolist()) parts_thisside = parts_thisside + ',' + refdes if pnp_count > 0 else refdes pnp_count = pnp_count + 1 twi.addChild( QTreeWidgetItem(twi, [pnp_row['Name'].values[0]])) if 0 < pnp_count < len(selected): twi.setData(0, Qt.DisplayRole, parts_thisside) if pnp_count == 1: twi.removeChild(twi.child(0))
def tab1_add(): sponsor_text = self.tab1_search.text() sponsor_time = self.tab1_sponsor_value.value() line_offset = self.tab1_offset_value.value() line_ignore = self.tab1_ignore_value.value() time_ignore = self.tab1_ignore_sec.value() data = [1, sponsor_time, sponsor_text, line_offset, line_ignore, time_ignore] item = QTreeWidgetItem(self.que_list, [self.tab1_name, '스폰서 영상 시간 : ' + str(sponsor_time) + '초, 오프셋 : ' + str(line_offset) + '줄, 시작부터 ' + str(line_ignore) + '번째 줄, ' + str(time_ignore) + '초 무시 - 검색어 : ' + sponsor_text]) item.setData(2, 2, data)
def init_graph_view(self): print("init graph view") start_node = str(self.data["start_node"]) self.startNodeLabel.setText(start_node) for action_name in self.data["nodes"]: actionItem = QTreeWidgetItem(self.graphRootItem, [action_name, "action"]) for mp_id in self.data["nodes"][action_name]: mp_name = self.data["nodes"][action_name][mp_id]["name"] mpItem = QTreeWidgetItem(actionItem, [mp_name, "primitive"]) mpItem.setData(0, Qt.UserRole, int(mp_id))
def add_address_to_list(qtreelist: QTreeWidget, addr): for i in range(qtreelist.topLevelItemCount()): item = qtreelist.topLevelItem(i) # type: QTreeWidgetItem if int(item.text(0), 16) == addr: return None # deduplicate item = QTreeWidgetItem(qtreelist) item.setText(0, "%#x" % addr) item.setFlags(item.flags() | Qt.ItemIsUserCheckable) item.setData(0, Qt.CheckStateRole, Qt.Checked) return item
def down_list(tree: QTreeWidget): selected = tree.currentItem() if selected: index = tree.indexOfTopLevelItem(selected) name = selected.text(0) desc = selected.text(1) data = selected.data(2, 2) new = QTreeWidgetItem([name, desc]) new.setData(2, 2, data) tree.takeTopLevelItem(index) tree.insertTopLevelItem(index + 1, new) tree.setCurrentItem(new)
def fill_tree_widget(self): self.collectionTreeWidget.clear() self.rootItem = QTreeWidgetItem(self.collectionTreeWidget, ["root", "root"]) self.rootItem.setExpanded(True) # root collection has id 0 self.rootItem.setData(0, Qt.UserRole, 0) for action in self.graph_data["nodes"]: actionItem = QTreeWidgetItem(self.rootItem, [action, "action"]) actionItem.setData(0, Qt.UserRole, action) for mp_id in self.graph_data["nodes"][action]: model_name = self.graph_data["nodes"][action][mp_id]["name"] mpItem = QTreeWidgetItem(actionItem, [model_name, "primitive"]) mpItem.setData(0, Qt.UserRole, int(mp_id))
class CopyDBDialog(QDialog, Ui_Dialog): def __init__(self, db_url, parent=None): QDialog.__init__(self, parent) Ui_Dialog.setupUi(self, self) self.db_url = db_url self.selectButton.clicked.connect(self.slot_accept) self.cancelButton.clicked.connect(self.slot_reject) self.success = False self.collection = None t = threading.Thread(target=self.fill_tree_widget) t.start() def slot_accept(self): col = self.get_collection() if col is not None: self.collection, c_name, c_type = col self.success = True self.close() def slot_reject(self): self.close() def fill_tree_widget(self, parent=None): if parent is None: self.collectionTreeWidget.clear() self.rootItem = QTreeWidgetItem(self.collectionTreeWidget, ["root", "root"]) self.rootItem.setExpanded(True) # root collection has id 0 parent_id = 0 parent_item = self.rootItem self.rootItem.setData(0, Qt.UserRole, parent_id) else: parent_id = parent[1] parent_item = parent[0] collection_list = get_collections_by_parent_id_from_remote_db( self.db_url, parent_id) for col in collection_list: colItem = QTreeWidgetItem(parent_item, [col[1], col[2]]) colItem.setData(0, Qt.UserRole, col[0]) self.fill_tree_widget((colItem, col[0])) def get_collection(self): colItem = self.collectionTreeWidget.currentItem() if colItem is None: return return int(colItem.data(0, Qt.UserRole)), str(colItem.text(0)), str( colItem.text(1))
class SelectTransitionDialog(QDialog, Ui_Dialog): def __init__(self, graph_data, parent=None): QDialog.__init__(self, parent) Ui_Dialog.setupUi(self, self) self.graph_data = graph_data self.selectButton.clicked.connect(self.slot_accept) self.cancelButton.clicked.connect(self.slot_reject) self.success = False self.transition_name = "" self.transition_entry = None self.fill_tree_widget() def slot_accept(self): colItem = self.collectionTreeWidget.currentItem() if colItem is None or colItem.parent() is None: return model_name = str(colItem.text(0)) action_name = str(colItem.parent().text(0)) model_id = int(colItem.data(0, Qt.UserRole)) self.transition_name = action_name + ":" + model_name self.transition_entry = { "action_name": action_name, "model_name": model_name, "model_id": model_id } self.success = True self.close() def slot_reject(self): self.close() def fill_tree_widget(self): self.collectionTreeWidget.clear() self.rootItem = QTreeWidgetItem(self.collectionTreeWidget, ["root", "root"]) self.rootItem.setExpanded(True) # root collection has id 0 self.rootItem.setData(0, Qt.UserRole, 0) for action in self.graph_data["nodes"]: actionItem = QTreeWidgetItem(self.rootItem, [action, "action"]) actionItem.setData(0, Qt.UserRole, action) for mp_id in self.graph_data["nodes"][action]: model_name = self.graph_data["nodes"][action][mp_id]["name"] mpItem = QTreeWidgetItem(actionItem, [model_name, "primitive"]) mpItem.setData(0, Qt.UserRole, int(mp_id))
def fill_tree_widget(self, parent=None): if parent is None: self.collectionTreeWidget.clear() self.rootItem = QTreeWidgetItem(self.collectionTreeWidget, ["root", "root"]) self.rootItem.setExpanded(True) # root collection has id 0 parent_id = 0 parent_item = self.rootItem self.rootItem.setData(0, Qt.UserRole, parent_id) else: parent_id = parent[1] parent_item = parent[0] collection_list = get_collections_by_parent_id_from_remote_db(self.db_url, parent_id) for col in collection_list: colItem = QTreeWidgetItem(parent_item, [col[1], col[2]]) colItem.setData(0, Qt.UserRole, col[0]) self.fill_tree_widget((colItem, col[0]))
def _build_item(name: str, data: type = None) -> QTreeWidgetItem: """ Build a tree item with a display name, and sets its data :param data: the class name. If specified it's set at column 1 on Qt.UserRole """ item = QTreeWidgetItem([name]) flags = Qt.ItemIsSelectable | Qt.ItemIsEnabled if data: item.setData(1, Qt.UserRole, data) # Show the short description as tooltip of the items if data.shortDescription(): item.setData(0, Qt.ToolTipRole, data.shortDescription()) flags |= Qt.ItemIsDragEnabled item.setFlags(flags) return item
def slot_add_primitive(self): selected_action = self.graphTreeWidget.currentItem() selected_primitive = self.modelListWidget.currentItem() if selected_action is not None and selected_primitive is not None: action_name = str(selected_action.text(0)) type_str = str(selected_action.text(1)) if type_str == "action": mp_id = int(selected_primitive.data(Qt.UserRole)) mp_name = str(selected_primitive.text()) mp_key = str(mp_id) if mp_key not in self.data["nodes"][action_name]: mpItem = QTreeWidgetItem(selected_action, [mp_name, "primitive"]) mpItem.setData(0, Qt.UserRole, mp_id) mp_dict = dict() mp_dict["transitions"] = dict() mp_dict["type"] = "standard" mp_dict["name"] = mp_name self.data["nodes"][action_name][mp_key] = mp_dict else: print(mp_name, "already part of action", action_name)
def add_list_to_view(self): """ add list to view """ self.window.listWidget.invisibleRootItem().takeChildren() list_data = [] for value in self.list_dict.values(): list_data.append(value) for data in list_data: item_data = [ data["function_name"], (data["count"]), (data["total_time"]), (data["self_time"]), (data["children_time"]) ] item = QTreeWidgetItem(None, item_data) for column_index in [1, 2, 3, 4]: item.setTextAlignment(column_index, Qt.AlignRight) item.setBackground( column_index, get_brush(item_data[column_index], self.total_time)) item.setFont(column_index, self.mono_space_font) item.setData(column_index, Qt.DisplayRole, item_data[column_index]) self.window.listWidget.addTopLevelItem(item) self.window.listWidget.sortItems(2, Qt.DescendingOrder)
def __init__(self): QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.setupUi(self) # Set the headers self.dataTreeWidget.setHeaderLabels(['ID', 'NAME', 'STATUS']) # Create dummy users user_1 = UserData("Alan", "Online", {"Task_A": 25, "Task_B": 60}) user_2 = UserData("Max", "Online", {"Task_A": 68}) user_3 = UserData("Scarlet", "Offline", { "Task_A": 5, "Task_B": 55, "Task_C": 25 }) users_list = [user_1, user_2, user_3] # Loop through users to get the value and insert for each row self.dataTreeWidget.clear() for index, user in enumerate(users_list): self.user_data = QTreeWidgetItem() progress_bar_tracker = TrackUserProgress() self.user_data.setData(0, Qt.DisplayRole, index) self.user_data.setData(1, Qt.DisplayRole, user.name) self.user_data.setData(2, Qt.DisplayRole, user.status) self.dataTreeWidget.addTopLevelItem(self.user_data) # Loop through each user's tasks and display it's progress bar. for user_task in sorted(list(user.tasks.keys())): user_task_child = QTreeWidgetItem() user_task_progress = QProgressBar() user_task_progress.setStyleSheet( (progress_bar_tracker.return_progress_color( user.tasks[user_task]))) user_task_progress.setValue(user.tasks[user_task]) user_task_child.setData(0, Qt.DisplayRole, user_task) self.user_data.addChild(user_task_child) self.dataTreeWidget.setItemWidget(user_task_child, 1, user_task_progress) # Variable that handles when to expand and collapse all the columns self.click_counter = 2 self.treeButton.clicked.connect(self.view_hide_clicked)
def _populate_fields_tree(self, entity, parent=None): if parent is None: parent = self._fields_tree.invisibleRootItem() metadata = EntityMetadata.for_discriminator(entity) for field_name, field in sorted( metadata.all_fields.items(), key=lambda i: underscored_to_words(i[0])): child_metadata = None try: child_metadata = EntityMetadata.for_discriminator( field.type_name) except KeyError: pass if child_metadata: name = get_class_display_name(field.type_name) subparent = QTreeWidgetItem([name]) subparent.setData(0, Qt.UserRole, field_name) parent.addChild(subparent) self._populate_fields_tree(field.type_name, subparent) else: item = QTreeWidgetItem([underscored_to_words(field_name)]) item.setData(0, Qt.UserRole, (field_name, field)) parent.addChild(item)
def handle_packet(self, packet, writer): """ 处理抓到的数据包 :parma packet: 需要处理分类的包 """ unkown = False try: # 如果暂停,则不对列表进行更新操作 if not self.pause_flag and packet.name == "Ethernet": protocol = None if self.packet_id == 1: self.start_timestamp = packet.time packet_time = packet.time - self.start_timestamp # 网络层 net = packet.payload network_layer = net.name version_add = "" # IPv4 if network_layer == "IP": source = packet[IP].src destination = packet[IP].dst self.counter["ipv4"] += 1 # IPv6 elif network_layer == "IPv6": source = packet[IPv6].src destination = packet[IPv6].dst version_add = "v6" self.counter["ipv6"] += 1 # ARP elif network_layer == "ARP": self.counter["arp"] += 1 protocol = network_layer source = packet[Ether].src destination = packet[Ether].dst if destination == "ff:ff:ff:ff:ff:ff": destination = "Broadcast" else: try: protocol = network_layer unkown = True except: # 其他协议不处理 return if network_layer != "ARP" and not unkown: # 传输层 trans = net.payload protocol = trans.name sport = None dport = None if protocol == "TCP": sport = packet[TCP].sport dport = packet[TCP].dport protocol += version_add self.counter["tcp"] += 1 elif protocol == "UDP": sport = packet[UDP].sport dport = packet[UDP].dport protocol += version_add self.counter["udp"] += 1 elif len(protocol) >= 4 and protocol[0:4] == "ICMP": protocol = "ICMP" + version_add self.counter["icmp"] += 1 else: return if trans.haslayer(HTTPRequest) or trans.haslayer( HTTPResponse): protocol = "HTTP" + version_add elif trans.haslayer(TLS): protocol = https_version[trans[TLS].version] if sport and dport: if sport in ports: protocol = ports[sport] + version_add elif dport in ports: protocol = ports[dport] + version_add item = QTreeWidgetItem(self.main_window.packet_tree) # 根据协议类型不同设置颜色 try: color = color_dict[protocol] except: color = "#ff80c0" for i in range(7): item.setBackground(i, QBrush(QColor(color))) # 添加行内容 item.setData(0, Qt.DisplayRole, self.packet_id) item.setText(1, f"{packet_time:.6f}") item.setText(2, source) item.setText(3, destination) item.setText(4, protocol) item.setData(5, Qt.DisplayRole, len(packet)) item.setText(6, packet.summary()) # 时间栏右对齐,为了格式化后不影响排序 # item.setTextAlignment(1, Qt.AlignRight) self.packet_id += 1 if writer: writer.write(packet) except: pass
def __init__(self, parent=None): super(ToolTree, self).__init__(parent) group_names = [] tool_names = [] tool_infos = [] tool_progress = [ ] # 0 = da fare, 1 = iniziato, 2 = funzionante, 3 = completo # [0] group_names.append(self.tr('[General]')) tool_names.append([ self.tr('Original Image'), self.tr('File Digest'), self.tr('Hex Editor'), self.tr('Similar Search') ]) tool_infos.append([ self.tr( 'Display the unaltered reference image for visual inspection'), self. tr('Retrieve physical file information, crypto and perceptual hashes' ), self. tr('Open an external hexadecimal editor to show and edit raw bytes' ), self. tr('Browse online search services to find visually similar images') ]) tool_progress.extend([3, 3, 2, 2]) # [1] group_names.append(self.tr('[Metadata]')) tool_names.append([ self.tr('Header Structure'), self.tr('EXIF Full Dump'), self.tr('Thumbnail Analysis'), self.tr('Geolocation data') ]) tool_infos.append([ self. tr('Dump the file header structure and display an interactive view' ), self. tr('Scan through file metadata and gather all available information' ), self.tr( 'Extract optional embedded thumbnail and compare with original' ), self. tr('Retrieve optional geolocation data and show it on a world map') ]) tool_progress.extend([3, 3, 3, 2]) # [2] group_names.append(self.tr('[Inspection]')) tool_names.append([ self.tr('Enhancing Magnifier'), self.tr('Channel Histogram'), self.tr('Global Adjustments'), self.tr('Reference Comparison') ]) tool_infos.append([ self. tr('Magnifying glass with enhancements for better identifying forgeries' ), self. tr('Display single color channels or RGB composite interactive histogram' ), self. tr('Apply standard image adjustments (brightness, hue, saturation, ...)' ), self. tr('Open a synchronized double view for comparison with another picture' ) ]) tool_progress.extend([3, 3, 3, 3]) # [3] group_names.append(self.tr('[Detail]')) tool_names.append([ self.tr('Luminance Gradient'), self.tr('Echo Edge Filter'), self.tr('Wavelet Threshold'), self.tr('Correlation Plot') ]) tool_infos.append([ self. tr('Analyze horizontal/vertical brightness variations across the image' ), self. tr('Use derivative filters to reveal artificial out-of-focus regions' ), self. tr('Reconstruct image with different wavelet coefficient thresholds' ), self. tr('Exploit spatial correlation patterns among neighboring pixels') ]) tool_progress.extend([3, 3, 3, 0]) # [4] group_names.append(self.tr('[Colors]')) tool_names.append([ self.tr('RGB/HSV Plots'), self.tr('Space Conversion'), self.tr('PCA Projection'), self.tr('Pixel Statistics') ]) tool_infos.append([ self. tr('Display interactive 2D and 3D plots of RGB and HSV pixel values' ), self. tr('Convert RGB channels into HSV/YCbCr/Lab/Luv/CMYK/Gray spaces'), self.tr( 'Use color PCA to project pixel onto most salient components'), self.tr( 'Compute minimum/maximum/average RGB values for every pixel') ]) tool_progress.extend([3, 3, 3, 3]) # [5] group_names.append(self.tr('[Noise]')) tool_names.append([ self.tr('Noise Estimation'), self.tr('Min/Max Deviation'), self.tr('Frequency Split'), self.tr('Bit Plane Values') ]) tool_infos.append([ self.tr( 'Estimate different kind of noise components of the image'), self. tr('Highlight pixels deviating from block-based min/max statistics' ), self. tr('Split image luminance into high and low frequency components'), self. tr('Show individual bit planes to find inconsistent noise patterns' ) ]) tool_progress.extend([3, 3, 3, 3]) # [6] group_names.append(self.tr('[JPEG]')) tool_names.append([ self.tr('Error Level Analysis'), self.tr('Quality Estimation'), self.tr('Multiple Compression'), self.tr('DCT Dimples Map') ]) tool_infos.append([ self. tr('Show pixel-level difference against fixed compression levels'), self. tr('Extract quantization tables and estimate last saved JPEG quality' ), self. tr('Use residuals to detect multiple compressions at different levels' ), self. tr('Analyze periodic quantization artifacts introduced by devices') ]) tool_progress.extend([3, 3, 1, 0]) # [7] group_names.append(self.tr('[Tampering]')) tool_names.append([ self.tr('Contrast Enhancement'), self.tr('Copy-Move Forgery'), self.tr('Image Resampling'), self.tr('Composite Splicing') ]) tool_infos.append([ self.tr( 'Analyze color distributions to detect contrast enhancements'), self.tr( 'Use invariant feature descriptors to detect cloned regions'), self. tr('Estimate 2D pixel interpolation for detecting resampling traces' ), self.tr( 'Exploit DCT statistics for automatic splicing zone detection') ]) tool_progress.extend([3, 3, 0, 0]) # [8] group_names.append(self.tr('[Various]')) tool_names.append([ self.tr('Median Filtering'), self.tr('Illuminant Map'), self.tr('PRNU Identification'), self.tr('Stereogram Decoder') ]) tool_infos.append([ self.tr( 'Detect processing traces left by nonlinear median filtering'), self.tr( 'Estimate scene local light direction on estimated 3D surfaces' ), self. tr('Exploit sensor pattern noise introduced by different cameras'), self. tr('Decode 3D images concealed inside crossed-eye autostereograms') ]) tool_progress.extend([0, 0, 0, 3]) count = 0 for i, group in enumerate(group_names): group_item = QTreeWidgetItem() group_item.setText(0, group) font = group_item.font(0) font.setBold(True) group_item.setFont(0, font) group_item.setData(0, Qt.UserRole, False) group_item.setIcon(0, QIcon('icons/{}.svg'.format(i))) for j, tool in enumerate(tool_names[i]): tool_item = QTreeWidgetItem(group_item) tool_item.setText(0, tool) tool_item.setData(0, Qt.UserRole, True) tool_item.setData(0, Qt.UserRole + 1, i) tool_item.setData(0, Qt.UserRole + 2, j) tool_item.setToolTip(0, tool_infos[i][j]) if tool_progress[count] == 0: modify_font(tool_item, italic=True) count += 1 self.addTopLevelItem(group_item) self.expandAll() self.setColumnCount(1) self.header().setVisible(False) self.setMaximumWidth(300) self.version = '{:.2f}a'.format(sum(tool_progress) / (count * 3))
child7e.setText(0, '为等高线赋Z值') child7f = QTreeWidgetItem(child7) child7f.setText(0, '坡顶坡底赋Z值(最短距离)') child7g = QTreeWidgetItem(child7) child7g.setText(0, '坡顶坡底赋Z值(手工)') child7h = QTreeWidgetItem(child7) child7h.setText(0, '按长度分割线条') child7i = QTreeWidgetItem(child7) child7i.setText(0, '生成示坡线') child7j = QTreeWidgetItem(child7) child7j.setText(0, '生成巷道断面') child7k = QTreeWidgetItem(child7) child7k.setText(0, '以面积求多边形') child7l = QTreeWidgetItem(child7) child7l.setText(0, '将2根线在交点断开') child7l.setData(0,) tree.addTopLevelItem(root) # root.connect(root,SIN) mainFrame.gridLayout.addWidget(tree, 0, 0, 1, 1) # 显示surpac的tab # 设置surpac窗口为主窗口的子窗口 # 方法1 # win32gui.SetParent(hwnds[0], mainWindow.winId()) # 方法2 native_wnd = QWindow.fromWinId(hwnds[0]) surpacWidget = QWidget.createWindowContainer(native_wnd) # 方法2.1 # mainWindow.setCentralWidget(centralWidget) # 方法2.2
def __init__(self, parent=None): super(ToolTree, self).__init__(parent) group_names = [] tool_names = [] tool_infos = [] tool_progress = [ ] # 0 = da fare, 1 = iniziato, 2 = funzionante, 3 = completo # [0] group_names.append(self.tr('[General]')) tool_names.append([ self.tr('Original Image'), self.tr('File Digest'), self.tr('Hex Editor'), self.tr('Reverse Search') ]) tool_infos.append([ self.tr( 'Display the unaltered reference image for visual inspection'), self. tr('Retrieve file information and compute many hashes and ballistics' ), self. tr('Open an external hexadecimal editor to show and edit raw bytes' ), self.tr( 'Use online search services to find visually similar images') ]) tool_progress.extend([3, 3, 2, 2]) # [1] group_names.append(self.tr('[Metadata]')) tool_names.append([ self.tr('Header Structure'), self.tr('Metadata Extraction'), self.tr('Thumbnail Analysis'), self.tr('Geolocation data') ]) tool_infos.append([ self. tr('Dump the physical EXIF structure and display an interactive view' ), self. tr('Scan through file metadata and gather all available information' ), self.tr( 'Extract optional embedded thumbnail and compare with original' ), self. tr('Retrieve optional geo-location data and show it on a world map' ) ]) tool_progress.extend([3, 3, 3, 2]) # [2] group_names.append(self.tr('[Inspection]')) tool_names.append([ self.tr('Enhancing Magnifier'), self.tr('Reference Comparison'), self.tr('Global Adjustments'), self.tr('Fourier Transform') ]) tool_infos.append([ self. tr('Use a loupe with visual enhancement for better identifying forgeries' ), self. tr('Open a synchronized double view to compare two different pictures' ), self. tr('Apply standard adjustments (contrast, brightness, hue, saturation)' ), self. tr('Compute amplitude and phase components of the 2D Fourier Transform' ) ]) tool_progress.extend([2, 2, 2, 3]) # [3] group_names.append(self.tr('[JPEG]')) tool_names.append([ self.tr('Quality Estimation'), self.tr('Error Level Analysis'), self.tr('Multiple Compression'), self.tr('DCT Dimples Map') ]) tool_infos.append([ self. tr('Extract quantization tables and estimate last saved JPEG quality' ), self. tr('Show pixel-level difference against different compression levels' ), self. tr('Use residuals to detect multiple compressions at different levels' ), self. tr('Analyze periodic quantization artifacts to detect manipulations' ) ]) tool_progress.extend([2, 3, 1, 0]) # [4] group_names.append(self.tr('[Colors]')) tool_names.append([ self.tr('RGB/HSV Plots'), self.tr('PCA Projection'), self.tr('Pixel Statistics'), self.tr('Space Conversion') ]) tool_infos.append([ self.tr( 'Display interactive 2D and 3D plots of RGB and HSV pixel data' ), self. tr('Use color PCA to project RGB values onto reduced vector spaces' ), self.tr( 'Compute minimum/maximum/average RGB values for every pixel'), self. tr('Convert color channels into RGB/HSV/YCbCr/Lab/Luv/CMYK spaces') ]) tool_progress.extend([0, 2, 3, 2]) # [5] group_names.append(self.tr('[Tonality]')) tool_names.append([ self.tr('Luminance Gradient'), self.tr('Echo Edge Filter'), self.tr('Correlation Plot'), self.tr('Wavelet Threshold') ]) tool_infos.append([ self. tr('Analyze horizontal/vertical brightness variations across the image' ), self. tr('Use derivative filters to reveal artificial out-of-focus zones' ), self.tr( 'Exploit spatial correlation patterns among neighboring pixels' ), self. tr('Reconstruct image with different wavelet coefficient thresholds' ) ]) tool_progress.extend([2, 3, 0, 0]) # [6] group_names.append(self.tr('[Noise]')) tool_names.append([ self.tr('Noise Estimation'), self.tr('Min/Max Deviation'), self.tr('Image Bit Planes'), self.tr('Frequency Separation') ]) tool_infos.append([ self.tr( 'Estimate and visualize gaussian noise components of the image' ), self. tr('Highlight pixels deviating from block-based min/max statistics' ), self. tr('Visualize bit planes values to find different noise patterns'), self. tr('Estimate high/low frequency components of the luminance channel' ) ]) tool_progress.extend([3, 2, 3, 0]) # [7] group_names.append(self.tr('[Tampering]')) tool_names.append([ self.tr('Contrast Enhancement'), self.tr('Region Cloning'), self.tr('Image Resampling'), self.tr('Composite Splicing') ]) tool_infos.append([ self.tr( 'Analyze color distribuions to detect contrast enhancements'), self. tr('Use feature descriptors for copy/rotate clone area detection'), self. tr('Analyze 2D pixel interpolation for detecting resampling traces' ), self.tr( 'Exploit DCT statistics for automatic splicing zone detection') ]) tool_progress.extend([0, 0, 0, 0]) count = 0 for i, group in enumerate(group_names): group_item = QTreeWidgetItem() group_item.setText(0, group) font = group_item.font(0) font.setBold(True) group_item.setFont(0, font) group_item.setData(0, Qt.UserRole, False) group_item.setIcon(0, QIcon('icons/{}.svg'.format(i))) for j, tool in enumerate(tool_names[i]): tool_item = QTreeWidgetItem(group_item) tool_item.setText(0, tool) tool_item.setData(0, Qt.UserRole, True) tool_item.setData(0, Qt.UserRole + 1, i) tool_item.setData(0, Qt.UserRole + 2, j) tool_item.setToolTip(0, tool_infos[i][j]) if tool_progress[count] == 0: modify_font(tool_item, italic=True) count += 1 self.addTopLevelItem(group_item) self.expandAll() self.setColumnCount(1) self.header().setVisible(False) self.setMaximumWidth(300) self.version = '{:.2f}a'.format(sum(tool_progress) / (count * 3))
def tab3_add(): speed_rate = self.tab3_speed_value.value() data = [3, speed_rate] item = QTreeWidgetItem(self.que_list, [self.tab3_name, '자막 속도 ' + str(speed_rate) + '%']) item.setData(2, 2, data)
def __init__(self, parent=None): super(ToolTree, self).__init__(parent) group_names = [] tool_names = [] tool_infos = [] tool_progress = [ ] # 0 = da fare, 1 = debug, 2 = funzionante, 3 = completo # [0] group_names.append(self.tr("[General]")) tool_names.append([ self.tr("Original Image"), self.tr("File Digest"), self.tr("Hex Editor"), self.tr("Similar Search") ]) tool_infos.append([ self.tr( "Display the unaltered reference image for visual inspection"), self. tr("Retrieve physical file information, crypto and perceptual hashes" ), self. tr("Open an external hexadecimal editor to show and edit raw bytes" ), self.tr( "Browse online search services to find visually similar images" ), ]) tool_progress.extend([3, 3, 2, 2]) # [1] group_names.append(self.tr("[Metadata]")) tool_names.append([ self.tr("Header Structure"), self.tr("EXIF Full Dump"), self.tr("Thumbnail Analysis"), self.tr("Geolocation data"), ]) tool_infos.append([ self. tr("Dump the file header structure and display an interactive view" ), self. tr("Scan through file metadata and gather all available information" ), self.tr( "Extract optional embedded thumbnail and compare with original" ), self.tr( "Retrieve optional geolocation data and show it on a world map" ), ]) tool_progress.extend([3, 3, 3, 2]) # [2] group_names.append(self.tr("[Inspection]")) tool_names.append([ self.tr("Enhancing Magnifier"), self.tr("Channel Histogram"), self.tr("Global Adjustments"), self.tr("Reference Comparison"), ]) tool_infos.append([ self. tr("Magnifying glass with enhancements for better identifying forgeries" ), self. tr("Display single color channels or RGB composite interactive histogram" ), self. tr("Apply standard image adjustments (brightness, hue, saturation, ...)" ), self. tr("Open a synchronized double view for comparison with another picture" ), ]) tool_progress.extend([3, 3, 3, 3]) # [3] group_names.append(self.tr("[Detail]")) tool_names.append([ self.tr("Luminance Gradient"), self.tr("Echo Edge Filter"), self.tr("Wavelet Threshold"), self.tr("Frequency Split"), ]) tool_infos.append([ self. tr("Analyze horizontal/vertical brightness variations across the image" ), self. tr("Use derivative filters to reveal artificial out-of-focus regions" ), self. tr("Reconstruct image with different wavelet coefficient thresholds" ), self.tr( "Divide image luminance into high and low frequency components" ), ]) tool_progress.extend([3, 3, 3, 3]) # [4] group_names.append(self.tr("[Colors]")) tool_names.append([ self.tr("RGB/HSV Plots"), self.tr("Space Conversion"), self.tr("PCA Projection"), self.tr("Pixel Statistics"), ]) tool_infos.append([ self. tr("Display interactive 2D and 3D plots of RGB and HSV pixel values" ), self. tr("Convert RGB channels into HSV/YCbCr/Lab/Luv/CMYK/Gray spaces"), self.tr( "Use color PCA to project pixel onto most salient components"), self.tr( "Compute minimum/maximum/average RGB values for every pixel"), ]) tool_progress.extend([3, 3, 3, 3]) # [5] group_names.append(self.tr("[Noise]")) tool_names.append([ self.tr("Noise Separation"), self.tr("Min/Max Deviation"), self.tr("Bit Plane Values"), self.tr("PRNU Identification"), ]) tool_infos.append([ self.tr( "Estimate and extract different kind of image noise components" ), self. tr("Highlight pixels deviating from block-based min/max statistics" ), self. tr("Show individual bit planes to find inconsistent noise patterns" ), self. tr("Exploit sensor pattern noise introduced by different cameras"), ]) tool_progress.extend([3, 3, 3, 0]) # [6] group_names.append(self.tr("[JPEG]")) tool_names.append([ self.tr("Quality Estimation"), self.tr("Error Level Analysis"), self.tr("Multiple Compression"), self.tr("JPEG Ghost Maps"), ]) tool_infos.append([ self. tr("Extract quantization tables and estimate last saved JPEG quality" ), self.tr( "Show pixel-wise differences against a fixed compression level" ), self.tr( "Use a machine learning model to detect multiple compression"), self. tr("Highlight traces of different compressions in difference images" ), ]) tool_progress.extend([3, 3, 0, 0]) # [7] group_names.append(self.tr("[Tampering]")) tool_names.append([ self.tr("Contrast Enhancement"), self.tr("Copy-Move Forgery"), self.tr("Composite Splicing"), self.tr("Image Resampling"), ]) tool_infos.append([ self.tr( "Analyze color distributions to detect contrast enhancements"), self.tr( "Use invariant feature descriptors to detect cloned regions"), self. tr("Exploit DCT statistics for automatic splicing zone detection"), self. tr("Estimate 2D pixel interpolation for detecting resampling traces" ), ]) tool_progress.extend([3, 2, 3, 0]) # [8] group_names.append(self.tr("[Various]")) tool_names.append([ self.tr("Median Filtering"), self.tr("Illuminant Map"), self.tr("Dead/Hot Pixels"), self.tr("Stereogram Decoder"), ]) tool_infos.append([ self.tr( "Detect nonlinear processing traces left by median filtering"), self.tr( "Estimate scene local light direction on estimated 3D surfaces" ), self.tr( "Detect and fix dead/hot pixels caused by sensor imperfections" ), self.tr( "Decode 3D images concealed inside crossed-eye autostereograms" ), ]) tool_progress.extend([2, 0, 0, 3]) count = 0 for i, group in enumerate(group_names): group_item = QTreeWidgetItem() group_item.setText(0, group) font = group_item.font(0) font.setBold(True) group_item.setFont(0, font) group_item.setData(0, Qt.UserRole, False) group_item.setIcon(0, QIcon(f"icons/{i}.svg")) for j, tool in enumerate(tool_names[i]): tool_item = QTreeWidgetItem(group_item) tool_item.setText(0, tool) tool_item.setData(0, Qt.UserRole, True) tool_item.setData(0, Qt.UserRole + 1, i) tool_item.setData(0, Qt.UserRole + 2, j) tool_item.setToolTip(0, tool_infos[i][j]) if tool_progress[count] == 0: modify_font(tool_item, italic=True) count += 1 self.addTopLevelItem(group_item) self.expandAll() self.setColumnCount(1) self.header().setVisible(False) self.setMaximumWidth(300) self.version = f"{sum(tool_progress) / 100:.2f}a"
def __init__(self): super(TreeWidget, self).__init__() self.setColumnCount(3) self.setColumnWidth(0, 80) self.setColumnWidth(1, 80) self.setColumnWidth(2, 80) self.setIndentation(0) self.setHeaderHidden(True) self.foreground_font = QFont() self.foreground_font.setBold(True) self.normal_font = QFont() self.normal_font.setBold(False) self.setExpandsOnDoubleClick(False) p = QTreeWidgetItem(self) font = QFont() font.setPointSize(10) font.setBold(True) p.setFont(0, font) p.setText(0, "父级1父级1父级1父级1父级1父级1") p.setIcon(0, QIcon("icons/arrow_right.png")) p.setFirstColumnSpanned(True) c = QTreeWidgetItem(p) c.setText(0, "子级1") c.setText(1, "子级2") c.setText(2, "子级3") c.setTextAlignment(0, Qt.AlignCenter) c.setTextAlignment(1, Qt.AlignCenter) c.setTextAlignment(2, Qt.AlignCenter) c.setData(0, Qt.UserRole, "c_00") c.setData(1, Qt.UserRole, "c_01") c.setData(2, Qt.UserRole, "c_02") c = QTreeWidgetItem(p) c.setText(0, "子级1") c.setText(1, "子级2") c.setTextAlignment(0, Qt.AlignCenter) c.setTextAlignment(1, Qt.AlignCenter) c.setData(0, Qt.UserRole, "c_03") c.setData(1, Qt.UserRole, "c_04") p.addChild(c) p = QTreeWidgetItem(self) p.setText(0, "父级2父级2父级2父级2父级2父级2") p.setIcon(0, QIcon("icons/arrow_right.png")) p.setFirstColumnSpanned(True) p.setFont(0, font) c = QTreeWidgetItem(p) c.setText(0, "子级2") c.setText(1, "子级22") c.setText(2, "子级23") c.setTextAlignment(0, Qt.AlignCenter) c.setTextAlignment(1, Qt.AlignCenter) c.setTextAlignment(2, Qt.AlignCenter) c.setData(0, Qt.UserRole, "c_10") c.setData(1, Qt.UserRole, "c_11") c.setData(2, Qt.UserRole, "c_12") p.addChild(c) self.itemClicked.connect(self.click) self.setFocusPolicy(Qt.NoFocus) self.setObjectName("tree") self.setStyleSheet( "#tree::item:selected{background-color:rgb(255,255,255);color:rgb(180,12,34);}" "#tree::item:hover{background-color:rgb(255,255,255);color:rgb(10,160,10)}" ) self.setAnimated(True) self.setSelectionBehavior(QAbstractItemView.SelectItems) self.setSelectionMode(QAbstractItemView.SingleSelection)
class EditCollectionDialog(QDialog, Ui_Dialog): def __init__(self, collection_id, parent_name, parent_id, default_name="", col_type="", owner=0, parent=None): QDialog.__init__(self, parent) Ui_Dialog.setupUi(self, self) self.acceptButton.clicked.connect(self.slot_accept) self.rejectButton.clicked.connect(self.slot_reject) self.parent_name = parent_name self.collection_id = collection_id #self.parentLabel.setText("Parent: "+parent_name) self.parent_id = parent_id self.db_url = DB_URL self.success = False self.name = default_name self.nameLineEdit.setText(default_name) self.col_type = col_type self.typeLineEdit.setText(col_type) self.ownerLineEdit.setText(str(owner)) t = threading.Thread(target=self.fill_tree_widget) t.start() def fill_tree_widget(self, parent=None): if parent is None: self.collectionTreeWidget.clear() self.rootItem = QTreeWidgetItem(self.collectionTreeWidget, ["root", "root"]) self.rootItem.setExpanded(True) # root collection has id 0 parent_id = 0 parent_item = self.rootItem self.rootItem.setData(0, Qt.UserRole, parent_id) else: parent_id = parent[1] parent_item = parent[0] collection_list = get_collections_by_parent_id_from_remote_db( self.db_url, parent_id) for col in collection_list: if col[0] == self.collection_id: self.select_tree_node(parent_item) continue colItem = QTreeWidgetItem(parent_item, [col[1], col[2]]) colItem.setData(0, Qt.UserRole, col[0]) self.fill_tree_widget((colItem, col[0])) def select_tree_node(self, node): node.setSelected(True) while node is not None: node.setExpanded(True) node = node.parent() def get_collection(self): colItem = self.collectionTreeWidget.currentItem() if colItem is None: return return int(colItem.data(0, Qt.UserRole)), str(colItem.text(0)), str( colItem.text(1)) def slot_accept(self): col = self.get_collection() if col is not None: self.parent_id, self.parent_name, c_type = col self.success = True self.name = str(self.nameLineEdit.text()) self.col_type = str(self.typeLineEdit.text()) self.owner = int(self.ownerLineEdit.text()) self.success = True self.close() def slot_reject(self): self.close()
class RetargetDBDialog(QDialog, Ui_Dialog): def __init__(self, db_url, parent=None): QDialog.__init__(self, parent) Ui_Dialog.setupUi(self, self) self.db_url = db_url self.selectButton.clicked.connect(self.slot_accept) self.cancelButton.clicked.connect(self.slot_reject) self.success = False self.scale_factor = 1.0 self.place_on_ground = False self.fill_combo_box_with_skeletons() t = threading.Thread(target=self.fill_tree_widget) t.start() self.src_model = None self.target_model = None self.collection = None def fill_combo_box_with_skeletons(self): skeleton_list = get_skeletons_from_remote_db(self.db_url) for idx, skel, owner in skeleton_list: self.sourceModelComboBox.addItem(skel, idx) self.targetModelComboBox.addItem(skel, idx) def slot_accept(self): self.scale_factor = float(self.scaleLineEdit.text()) self.src_model = str(self.sourceModelComboBox.currentText()) self.target_model = str(self.targetModelComboBox.currentText()) self.place_on_ground = self.placeOnGroundRadioButton.isChecked() col = self.get_collection() if col is not None: self.collection, c_name, c_type = col self.success = True self.close() def slot_reject(self): self.close()# def fill_tree_widget(self, parent=None): if parent is None: self.collectionTreeWidget.clear() self.rootItem = QTreeWidgetItem(self.collectionTreeWidget, ["root", "root"]) self.rootItem.setExpanded(True) # root collection has id 0 parent_id = 0 parent_item = self.rootItem self.rootItem.setData(0, Qt.UserRole, parent_id) else: parent_id = parent[1] parent_item = parent[0] collection_list = get_collections_by_parent_id_from_remote_db(self.db_url, parent_id) for col in collection_list: colItem = QTreeWidgetItem(parent_item, [col[1], col[2]]) colItem.setData(0, Qt.UserRole, col[0]) self.fill_tree_widget((colItem, col[0])) def get_collection(self): colItem = self.collectionTreeWidget.currentItem() if colItem is None: return return int(colItem.data(0, Qt.UserRole)), str(colItem.text(0)), str(colItem.text(1))
class GraphDefinitionDialog(QDialog, Ui_Dialog): def __init__(self, db_url, skeleton, graph_data=None, name="",parent=None): QDialog.__init__(self, parent) Ui_Dialog.setupUi(self, self) self.skeleton = skeleton self.db_url = db_url self.selectButton.clicked.connect(self.slot_accept) self.cancelButton.clicked.connect(self.slot_reject) self.success = False t = threading.Thread(target=self.fill_tree_widget) t.start() self.graphRootItem = QTreeWidgetItem(self.graphTreeWidget, ["root", "root"]) self.graphRootItem.setExpanded(True) self.data = graph_data if self.data is not None: if "start_node" not in self.data: self.data["start_node"] = "" self.init_graph_view() else: self.data = dict() self.data["nodes"] = dict() self.data["start_node"] = "" self.name = name self.nameLineEdit.setText(name) self.collectionTreeWidget.itemClicked.connect(self._fill_model_list_from_db) self.modelListWidget.itemClicked.connect(self.update_selected_model) self.graphTreeWidget.itemClicked.connect(self.update_model_info) self.addModelButton.clicked.connect(self.slot_add_primitive) self.replaceModelButton.clicked.connect(self.slot_replace_primitive) self.addActionButton.clicked.connect(self.slot_add_action) self.removeGraphItemButton.clicked.connect(self.slot_remove_graph_item) self.setToStartNodeButton.clicked.connect(self.slot_set_to_start_node) self.addTransitionButton.clicked.connect(self.slot_add_transition) self.removeTransitionButton.clicked.connect(self.slot_remove_transition) self.fill_node_type_combobox() self.nodeTypeComboBox.currentIndexChanged.connect(self.update_node_type) self._fill_model_list_from_db() def init_graph_view(self): print("init graph view") start_node = str(self.data["start_node"]) self.startNodeLabel.setText(start_node) for action_name in self.data["nodes"]: actionItem = QTreeWidgetItem(self.graphRootItem, [action_name, "action"]) for mp_id in self.data["nodes"][action_name]: mp_name = self.data["nodes"][action_name][mp_id]["name"] mpItem = QTreeWidgetItem(actionItem, [mp_name, "primitive"]) mpItem.setData(0, Qt.UserRole, int(mp_id)) def slot_accept(self): self.name = str(self.nameLineEdit.text()) self.success = self.name != "" self.close() def slot_reject(self): self.close() def slot_add_primitive(self): selected_action = self.graphTreeWidget.currentItem() selected_primitive = self.modelListWidget.currentItem() if selected_action is not None and selected_primitive is not None: action_name = str(selected_action.text(0)) type_str = str(selected_action.text(1)) if type_str == "action": mp_id = int(selected_primitive.data(Qt.UserRole)) mp_name = str(selected_primitive.text()) mp_key = str(mp_id) if mp_key not in self.data["nodes"][action_name]: mpItem = QTreeWidgetItem(selected_action, [mp_name, "primitive"]) mpItem.setData(0, Qt.UserRole, mp_id) mp_dict = dict() mp_dict["transitions"] = dict() mp_dict["type"] = "standard" mp_dict["name"] = mp_name self.data["nodes"][action_name][mp_key] = mp_dict else: print(mp_name, "already part of action", action_name) def slot_replace_primitive(self): selected_graph_node = self.graphTreeWidget.currentItem() selected_primitive = self.modelListWidget.currentItem() if selected_graph_node is not None and selected_primitive is not None: type_str = str(selected_graph_node.text(1)) if type_str == "primitive": action_node = selected_graph_node.parent() action_name = str(action_node.text(0)) if action_name in self.data["nodes"]: old_mp_id = int(selected_graph_node.data(0, Qt.UserRole)) old_mp_name = str(selected_graph_node.text(0)) old_key = str(old_mp_id) new_mp_id = int(selected_primitive.data(Qt.UserRole)) new_mp_name = str(selected_primitive.text()) new_key = str(new_mp_id) if old_key in self.data["nodes"][action_name]: old_transitions = self.data["nodes"][action_name][old_key]["transitions"] old_type = self.data["nodes"][action_name][old_key]["type"] del self.data["nodes"][action_name][old_key] selected_graph_node.setText(0, new_mp_name) selected_graph_node.setData(0, Qt.UserRole, new_mp_id) mp_dict = dict() mp_dict["transitions"] = old_transitions mp_dict["type"] = old_type mp_dict["name"] = new_mp_name self.data["nodes"][action_name][new_key] = mp_dict self.replace_transitions(action_name, old_mp_name, old_mp_id, new_mp_name, new_mp_id) self.update_model_info() print("replaced", old_mp_id, "with", new_mp_id) else: print(old_mp_name, "not part of action", action_name) def replace_transitions(self, action_name, old_model_name, old_model_id, new_model_name, new_model_id): old_key = action_name+":"+old_model_name new_key = action_name+":"+new_model_name new_entry = dict() new_entry["model_name"] = new_model_name new_entry["model_id"] = new_model_id for a in self.data["nodes"]: for mp in self.data["nodes"][a]: if old_key in self.data["nodes"][a][mp]["transitions"]: del self.data["nodes"][a][mp]["transitions"][old_key] self.data["nodes"][a][mp]["transitions"][new_key] = copy(new_entry) def slot_remove_graph_item(self): item = self.graphTreeWidget.currentItem() if item is not None: #and item != self.graphRootItem parent_item = item.parent() item_name = str(item.text(0)) parent_name = str(parent_item.text(0)) if parent_name in self.data["nodes"]: mp_id = str(item.data(0, Qt.UserRole)) if mp_id in self.data["nodes"][parent_name]: del self.data["nodes"][parent_name][mp_id] elif item_name in self.data["nodes"]: del self.data["nodes"][item_name] parent_item.removeChild(item) def slot_set_to_start_node(self): item = self.graphTreeWidget.currentItem() if item is not None: #and item != self.graphRootItem parent_item = item.parent() if parent_item is not None: item_name = str(item.text(0)) parent_name = str(parent_item.text(0)) start_node = [parent_name, item_name] start_node_str = str(start_node) self.data["start_node"] = [parent_name, item_name] self.startNodeLabel.setText(start_node_str) def slot_add_action(self): dialog = EnterNameDialog() dialog.exec_() if dialog.success: action_name = dialog.name if action_name not in self.data["nodes"]: actionItem = QTreeWidgetItem(self.graphRootItem, [action_name, "action"]) self.data["nodes"][action_name] = dict() def slot_add_transition(self): item = self.graphTreeWidget.currentItem() if item is not None: parent_item = item.parent() item_name = str(item.text(0)) type_name = str(item.text(1)) parent_name = str(parent_item.text(0)) if type_name == "primitive": mp_id = str(item.data(0, Qt.UserRole)) if mp_id in self.data["nodes"][parent_name]: dialog = SelectTransitionDialog(self.data) dialog.exec_() if dialog.success and dialog.transition_entry is not None: action_name = str(dialog.transition_entry["action_name"]) model_name = str(dialog.transition_entry["model_name"]) name = action_name+":"+model_name self.data["nodes"][parent_name][mp_id]["transitions"][name] = dialog.transition_entry self.update_model_info() def slot_remove_transition(self): selected_transition = self.transitionListWidget.currentItem() if selected_transition is not None: self.transitionListWidget.takeItem(self.transitionListWidget.row(selected_transition)) transiton_name = str(selected_transition.text()) selected_item = self.graphTreeWidget.currentItem() action_name = str(selected_item.parent().text(0)) #mp_name = str(selected_item.text(0)) mp_id = str(selected_item.data(0, Qt.UserRole)) del self.data["nodes"][action_name][mp_id]["transitions"][transiton_name] self.update_model_info() def fill_tree_widget(self, parent=None): if parent is None: self.collectionTreeWidget.clear() self.rootItem = QTreeWidgetItem(self.collectionTreeWidget, ["root", "root"]) self.rootItem.setExpanded(True) # root collection has id 0 parent_id = 0 parent_item = self.rootItem self.rootItem.setData(0, Qt.UserRole, parent_id) else: parent_id = parent[1] parent_item = parent[0] collection_list = get_collections_by_parent_id_from_remote_db(self.db_url, parent_id) for col in collection_list: colItem = QTreeWidgetItem(parent_item, [col[1], col[2]]) colItem.setData(0, Qt.UserRole, col[0]) self.fill_tree_widget((colItem, col[0])) def get_collection(self): colItem = self.collectionTreeWidget.currentItem() if colItem is None: return return int(colItem.data(0, Qt.UserRole)), str(colItem.text(0)), str(colItem.text(1)) def _fill_model_list_from_db(self, idx=None): self.modelListWidget.clear() col = self.get_collection() if col is None: return c_id, c_name, c_type = col model_list = get_model_list_from_remote_db(self.db_url, c_id, self.skeleton) print("model list", model_list) if model_list is None: return for node_id, name in model_list: item = QListWidgetItem() item.setText(name) item.setData(Qt.UserRole, node_id) self.modelListWidget.addItem(item) self.update_selected_model() def update_selected_model(self): selected_action = self.graphTreeWidget.currentItem() selected_primitive = self.modelListWidget.currentItem() if selected_action is not None and selected_primitive is not None: self.selectedModelLabel.setText(selected_primitive.text()) else: self.selectedModelLabel.setText("None") def update_model_info(self, idx=None): self.transitionListWidget.clear() self.nodeTypeComboBox.setCurrentIndex(0) selected_item = self.graphTreeWidget.currentItem() if selected_item is None: return item_type = str(selected_item.text(1)) if item_type != "primitive": return item_name = str(selected_item.text(0)) mp_id = str(selected_item.data(0, Qt.UserRole)) action_name = str(selected_item.parent().text(0)) if action_name not in self.data["nodes"]: return if mp_id not in self.data["nodes"][action_name]: print("mp id not in nodes", mp_id) return for transiton_key in self.data["nodes"][action_name][mp_id]["transitions"]: item = QListWidgetItem() item.setText(transiton_key) self.transitionListWidget.addItem(item) node_type = self.data["nodes"][action_name][mp_id]["type"] index = self.nodeTypeComboBox.findText(node_type, Qt.MatchFixedString) if index >= 0: self.nodeTypeComboBox.setCurrentIndex(index) print("node_type", node_type, index, mp_id) def fill_node_type_combobox(self): self.nodeTypeComboBox.clear() self.nodeTypeComboBox.addItem("", 0) self.nodeTypeComboBox.addItem("standard", 1) self.nodeTypeComboBox.addItem("start", 2) self.nodeTypeComboBox.addItem("end", 3) self.nodeTypeComboBox.addItem("single", 4) self.nodeTypeComboBox.addItem("idle", 5) def update_node_type(self): selected_item = self.graphTreeWidget.currentItem() if selected_item is None: return item_type = str(selected_item.text(1)) if item_type != "primitive": return item_name = str(selected_item.text(0)) mp_id = str(selected_item.data(0, Qt.UserRole)) action_name = str(selected_item.parent().text(0)) if action_name not in self.data["nodes"]: return if mp_id not in self.data["nodes"][action_name]: return node_type = str(self.nodeTypeComboBox.currentText()) if node_type != "": self.data["nodes"][action_name][mp_id]["type"] = node_type print("set node type", item_name, node_type)
def _add_msg_object(self, parent, path, name, obj, obj_type): label = name if hasattr(obj, '__slots__'): subobjs = [(slot, getattr(obj, slot)) for slot in obj.__slots__] elif type(obj) in [list, tuple]: len_obj = len(obj) if len_obj == 0: subobjs = [] else: w = int(math.ceil(math.log10(len_obj))) subobjs = [('[%*d]' % (w, i), subobj) for (i, subobj) in enumerate(obj)] else: subobjs = [] plotitem=False if type(obj) in [int, long, float]: plotitem=True if type(obj) == float: obj_repr = '%.6f' % obj else: obj_repr = str(obj) if obj_repr[0] == '-': label += ': %s' % obj_repr else: label += ': %s' % obj_repr elif type(obj) in [str, bool, int, long, float, complex, rospy.Time]: # Ignore any binary data obj_repr = codecs.utf_8_decode(str(obj), 'ignore')[0] # Truncate long representations if len(obj_repr) >= 50: obj_repr = obj_repr[:50] + '...' label += ': ' + obj_repr item = QTreeWidgetItem([label]) if name == '': pass elif path.find('.') == -1 and path.find('[') == -1: self.addTopLevelItem(item) else: parent.addChild(item) if plotitem == True: if path.replace(' ', '') in self._checked_states: item.setCheckState (0, Qt.Checked) else: item.setCheckState (0, Qt.Unchecked) item.setData(0, Qt.UserRole, (path, obj_type)) for subobj_name, subobj in subobjs: if subobj is None: continue if path == '': subpath = subobj_name # root field elif subobj_name.startswith('['): subpath = '%s%s' % (path, subobj_name) # list, dict, or tuple else: subpath = '%s.%s' % (path, subobj_name) # attribute (prefix with '.') if hasattr(subobj, '_type'): subobj_type = subobj._type else: subobj_type = type(subobj).__name__ self._add_msg_object(item, subpath, subobj_name, subobj, subobj_type)