def __changeDirectory(self, path): for c in self.filesview: c.setParent(None) c.deleteLater() self.filesview = [] self.checkBox_2.setChecked(False) self.progressBars = {} for f in self.__getFiles(path): try: group = QGroupBox(f, self) group.setGeometry(QRect(20, 20, 100, 150)) group.setCheckable(True) group.setChecked(False) group.setFixedSize(100, 150) group.setFlat(True) group.setToolTip(f) label = QLabel(group) label.setScaledContents(True) label.setGeometry(QRect(5, 25, 90, 90)) label.setToolTip(f) progressBar = QProgressBar(group) progressBar.setGeometry(QRect(0, 70, 111, 10)) progressBar.setProperty("value", 0) progressBar.setTextVisible(False) progressBar.setToolTip('0%') progressBar.setVisible(False) self.progressBars[f] = progressBar self.filesview.append(group) from os.path import isfile if isfile(path + '/' + f): ext = f.split('.')[-1] if isfile('icons/' + ext.lower() + '.png'): label.setPixmap( QPixmap('icons/' + ext.lower() + '.png')) else: label.setPixmap(QPixmap('icons/default.png')) else: label.setPixmap(QPixmap('icons/folder.png')) self.connect(group, SIGNAL("clicked()"), self.__deselectFile) except ValueError: pass i = 0 for x in list(range(len(self.filesview))): if (x % 4) == 0: i = i + 1 self.rowsview[i].addWidget(self.filesview[x])
class PropertyEditor(QWidget): # Signals insertionModeStarted = pyqtSignal(str) insertionModeEnded = pyqtSignal() insertionPropertiesChanged = pyqtSignal(object) editPropertiesChanged = pyqtSignal(object) def __init__(self, config, parent=None): QWidget.__init__(self, parent) self._class_config = {} self._class_items = {} self._class_prototypes = {} self._attribute_handlers = {} self._handler_factory = AttributeHandlerFactory() self._setupGUI() self._parea.setGeometry(0, 0, 200, 0) # (快捷键,button) self.shortcut2button = {} # (button,快捷键) self.label2shortcut = {} # Add label classes from config for label in config: self.addLabelClass(label) self.image_path = None def addLabelClassByPath(self, configs_path): # 读配置文件 with open(configs_path, 'r') as f: configs = json5.load(f) # 写入当前配置文件的路径 direct = os.path.dirname(sys.argv[0]) with open(os.path.join(direct, 'sloth.txt'), 'w') as f: f.write(configs_path) self._parea.setGeometry(0, 0, 200, 0) for temp_json in configs: self.addLabelClass(temp_json) # 注册 self._register('inserter', temp_json['attributes']['class'], temp_json['inserter']) self._register('item', temp_json['attributes']['class'], temp_json['item']) # add_txt的下拉框里也要添加 self.combo_box.addItem(temp_json['attributes']['class']) self.items.append(temp_json['attributes']['class']) cf.LABELS.append(temp_json) def onModelChanged(self, new_model): attrs = set([ k for k, v in self._attribute_handlers.items() if v.autoAddEnabled() ]) if len(attrs) > 0: start = time.time() attr2vals = {} for item in new_model.iterator(AnnotationModelItem): for attr in attrs: if attr in item: if attr not in attr2vals: attr2vals[attr] = set((item[attr], )) else: attr2vals[attr] |= set((item[attr], )) diff = time.time() - start LOG.info("Extracted annotation values from model in %.2fs" % diff) for attr, vals in attr2vals.items(): h = self._attribute_handlers[attr] for val in vals: h.addValue(val, True) # 设置右键菜单所在位置 def showContextMenu(self, label_class): self.label_menu[label_class].exec_(QCursor.pos()) # 删除所有的item def remove_all_item(self): for v in self.shortcut2button.values(): v.setShortcut(QKeySequence()) self.shortcut2button.clear() self.label2shortcut.clear() self.label_menu.clear() self.label_action.clear() self._class_config.clear() self.combo_box.clear() self.items.clear() temp_dict = copy.copy(self._class_buttons) for k, v in temp_dict.items(): self._classbox_layout.removeWidget(v) # 下面这句很重要,不然相当于没删 self._class_buttons[k].deleteLater() self._class_buttons.clear() cf.LABELS.clear() self._parea.setGeometry(0, 0, 200, 60) # 删除标签 def remove_item(self, label_class): """ 删除标签 :param label_class: 删除的标签名字 """ try: # 删除快捷键 self.endInsertionMode() shortcut = self.label2shortcut[label_class] if shortcut in self.shortcut2button and \ self.shortcut2button[shortcut] is not None and \ self.shortcut2button[shortcut] == self._class_buttons[label_class]: self.shortcut2button[shortcut].setShortcut(QKeySequence()) del self.shortcut2button[shortcut] # 删除菜单 del self.label_menu[label_class] # 删除菜单的动作 del self.label_action[label_class] # 删除视图中的按钮 self._classbox_layout.removeWidget( self._class_buttons[label_class]) self._class_buttons[label_class].deleteLater() self._class_buttons[label_class] = None del self._class_config[label_class] # 写回json direct = os.path.dirname(sys.argv[0]) with open(os.path.join(direct, 'sloth.txt'), 'r') as f: label_path = f.read() try: with open(label_path, 'r') as f: temp = json5.load(f) for i, current_json in enumerate(temp): if current_json['attributes']['class'] == label_class: temp.remove(current_json) # 遍历combo box 找到要删的 for i in range(len(self.combo_box)): current_label = self.combo_box.itemText(i) if current_label == label_class: print('removed', label_class) self.combo_box.removeItem(i) self.items.pop(i) break self._class_buttons.pop(label_class) break with open(label_path, 'w') as f: json5.dump(temp, f, quote_keys=True, trailing_commas=False, indent=4, separators=(',', ': '), sort_keys=True, ensure_ascii=False) self._parea.setGeometry( 0, 0, 200, max(self._parea.geometry().height() - 40, 60)) except Exception as e: print(e) except Exception as e: print(e) # 添加标签 def addLabelClass(self, label_config): """ 添加标签 :param label_config: 标签的json """ # Check label configuration if 'attributes' not in label_config: raise ImproperlyConfigured("Label with no 'attributes' dict found") attrs = label_config['attributes'] if 'class' not in attrs: raise ImproperlyConfigured("Labels must have an attribute 'class'") label_class = attrs['class'] if label_class in self._class_config: raise ImproperlyConfigured( "Label with class '%s' defined more than once" % label_class) # Store config self._class_config[label_class] = label_config # Parse configuration and create handlers and item self.parseConfiguration(label_class, label_config) # Add label class button button_text = label_config['text'] button = QPushButton(button_text) button.setCheckable(True) button.setFlat(True) button.clicked.connect(bind(self.onClassButtonPressed, label_class)) self._class_buttons[label_class] = button self._parea.setGeometry(0, 0, 200, self._parea.geometry().height() + 40) self._classbox_layout.addWidget(button) # 添加右键菜单 self.label_menu[label_class] = QtGui.QMenu(self) self.label_action[label_class] = self.label_menu[ label_class].addAction('删除') self.label_action[label_class].triggered.connect( bind(self.remove_item, label_class)) self._class_buttons[label_class].setContextMenuPolicy( QtCore.Qt.CustomContextMenu) self._class_buttons[label_class].customContextMenuRequested.connect( bind(self.showContextMenu, label_class)) # Add hotkey if 'hotkey' in label_config: # 快捷键 hotkey = label_config['hotkey'] # 快捷键已经存在,那就去掉原来的 if hotkey in self.shortcut2button and self.shortcut2button[ hotkey] is not None: self.shortcut2button[hotkey].setShortcut(QKeySequence()) # 设置快捷键 button.setShortcut(QKeySequence(hotkey)) self.shortcut2button[hotkey] = button self.label2shortcut[label_class] = hotkey def parseConfiguration(self, label_class, label_config): attrs = label_config['attributes'] # Add prototype item for insertion self._class_items[label_class] = AnnotationModelItem( {'class': label_class}) # Create attribute handler widgets or update their values for attr, vals in attrs.items(): if attr in self._attribute_handlers: self._attribute_handlers[attr].updateValues(vals) else: handler = self._handler_factory.create(attr, vals) if handler is None: self._class_items[label_class][attr] = vals else: self._attribute_handlers[attr] = handler for attr in attrs: if attr in self._attribute_handlers: self._class_items[label_class].update( self._attribute_handlers[attr].defaults()) def getHandler(self, attribute): if attribute in self._attribute_handlers: return self._attribute_handlers[attribute] else: return None def getLabelClassAttributes(self, label_class): return self._class_config[label_class]['attributes'].keys() def onClassButtonPressed(self, label_class): if self._class_buttons[label_class].isChecked(): self.startInsertionMode(label_class) else: self.endInsertionMode() def startInsertionMode(self, label_class): self.endInsertionMode(False) for lc, button in self._class_buttons.items(): button.setChecked(lc == label_class) LOG.debug("Starting insertion mode for %s" % label_class) self._label_editor = LabelEditor([self._class_items[label_class]], self, True) # self._layout.insertWidget(1, self._label_editor, 0) self.insertionModeStarted.emit(label_class) def endInsertionMode(self, uncheck_buttons=True): if self._label_editor is not None: LOG.debug("Ending insertion/edit mode") self._label_editor.hide() # self._layout.removeWidget(self._label_editor) self._label_editor = None if uncheck_buttons: self.uncheckAllButtons() self.insertionModeEnded.emit() def uncheckAllButtons(self): for lc, button in self._class_buttons.items(): button.setChecked(False) def markEditButtons(self, label_classes): for lc, button in self._class_buttons.items(): button.setFlat(lc not in label_classes) def currentEditorProperties(self): if self._label_editor is None: return None else: return self._label_editor.currentProperties() def startEditMode(self, model_items): # If we're in insertion mode, ignore empty edit requests if self._label_editor is not None and self._label_editor.insertionMode() \ and len(model_items) == 0: return self.endInsertionMode() LOG.debug("Starting edit mode for items: %s" % model_items) self._label_editor = LabelEditor(model_items, self) self.markEditButtons(self._label_editor.labelClasses()) self._layout.insertWidget(1, self._label_editor, 0) # 添加txt def add_txt(self): if not Main.isConfig(Main.get_json()): QMessageBox.warning(self, "Warning", '当前的配置文件错误或者为空,无法添加txt', QMessageBox.Ok) defect = self.combo_box.currentText() if defect is None or defect == '': return dir_path = QFileDialog.getExistingDirectory(self) Main.write_txt(dir_path, {defect}, 'defect') # 选择图片 def select_image(self): image_types = [ '*.jpg', '*.bmp', '*.png', '*.pgm', '*.ppm', '*.tiff', '*.tif', '*.gif' ] format_str = ' '.join(image_types) fname = QFileDialog.getOpenFileName( self, "select training source", '.', "Media files (%s)" % (format_str, )) if fname is None or fname == '': return self.image_path = os.path.abspath(fname) self._image_label.setText(os.path.basename(self.image_path)) # 获得图片路径对应的json路径 def image2json(self, path): temp = path.split('.') return ''.join(temp[:-1]) + '.json' # 获得图片路径转成的训练图片路径 def image2cpimage(self, path, id, length): length = max(length, 5) temp = path.split('.') return ''.join(temp[:-1]) + str(id).zfill(length) + '.' + temp[-1] # 判断是否包含瑕疵 def contains_defect(self, annotations, defect_type): defects = set() for annotation in annotations: if 'class' in annotation: defects.add(annotation['class']) return defect_type.issubset(defects) # 生成训练数据 def generate(self): if not Main.isConfig(Main.get_json()): QMessageBox.warning(self, "Warning", '配置文件错误或者为空,无法生成训练数据', QMessageBox.Ok) return a = TrainDialog(self) a.exec_() # 从labeltool中设置搜索按钮 def setFunction(self, func): self._search_btn.clicked.connect(func) # 获得关键字 def get_key_word(self): key_word = self._key_word.text() if key_word is None or key_word == '': key_word = self._key_word.placeholderText() return key_word # 获得文件类型 def get_extension(self): extension = self._extension.text() # 为空则用默认的,否则用输入的 if extension is None or extension == '': extension = self._extension.placeholderText() return extension # 返回一个含有权限类型的list def get_attributes_type(self): ''' 'Rect':('sloth.items.RectItem','sloth.items.RectItemInserter'), 'Point':('sloth.items.PointItem','sloth.items.PointItemInserter'), 'Polygon':('sloth.items.PolygonItem','sloth.items.PolygonItemInserter') ''' return ['Rect', 'Point', 'Polygon'] # 写回json def rewrite_json(self, temp_json): # json所在的txt direct = os.path.dirname(sys.argv[0]) with open(os.path.join(direct, 'sloth.txt'), 'r') as f: label_path = f.read() try: # 读取旧json with open(label_path, 'r') as f: temp = json5.load(f) # 追加我们要写入的json temp.append(temp_json) # 写入 with open(label_path, 'w') as f: json5.dump(temp, f, quote_keys=True, trailing_commas=False, indent=4, separators=(',', ': '), sort_keys=True, ensure_ascii=False) except Exception as e: print(e) # 添加标签 def add_attributes(self): if not Main.isConfig(Main.get_json()): QMessageBox.warning(self, "Warning", '当前配置文件错误或者为空,不能添加标签', QMessageBox.Ok) return # 转换dict type_dict = { 'Rect': ('sloth.items.RectItem', 'sloth.items.RectItemInserter'), 'Point': ('sloth.items.PointItem', 'sloth.items.PointItemInserter'), 'Polygon': ('sloth.items.PolygonItem', 'sloth.items.PolygonItemInserter') } # 获取添加的标签信息 attributes = {'class': self.attributes_LineEdit.text()} attributes_item, attributes_inserter = type_dict[ self.attributes_type.currentText()] attributes_hotkey = self.hotkey.text() attributes_text = self.text_LineEdit.text() global brush2idx brush_idx = str(brush2idx[self.brush_combo_box.currentText()]) temp_json = { 'attributes': attributes, 'inserter': attributes_inserter, 'item': attributes_item, 'color': ','.join(map(str, self.color_info)), 'brush': brush_idx, 'text': attributes_text } # 快捷键 if attributes_hotkey is not None and attributes_hotkey != '': temp_json['hotkey'] = attributes_hotkey print(temp_json) try: # 加入标签 self.addLabelClass(temp_json) print(self._class_buttons.keys()) # 注册 self._register('inserter', temp_json['attributes']['class'], temp_json['inserter']) self._register('item', temp_json['attributes']['class'], temp_json['item']) # add_txt的下拉框里也要添加 self.combo_box.addItem(temp_json['attributes']['class']) self.items.append(temp_json['attributes']['class']) cf.LABELS.append(temp_json) # 写回json self.rewrite_json(temp_json) except Exception as e: print(e) # 颜色对话框 def color_dialog(self): col = QtGui.QColorDialog.getColor() if col.isValid(): self.color_label.setStyleSheet("QWidget { background-color: %s }" % col.name()) self.color_info = col.getRgb()[:-1] # 设置控件的隐藏状态 def component_visible(self, component_name, state): if component_name == '添加标签': self._group_box_add_label.setVisible(state) elif component_name == 'add_txt': self._group_box_add_txt.setVisible(state) elif component_name == 'add_files': self._group_box_add_files.setVisible(state) def _setupGUI(self): self._class_buttons = {} self.label_menu = {} self.label_action = {} self._label_editor = None # Label class buttons self._parea = QGroupBox("Labels") self._classbox = QScrollArea() self._classbox_layout = FloatingLayout() self._parea.setLayout(self._classbox_layout) self._parea.setGeometry(0, 0, 200, 200) self._classbox.setWidget(self._parea) self._classbox.setGeometry(0, 0, 100, 100) # 添加txt模块 self.combo_box = QComboBox() self._group_box_add_txt = QGroupBox('add_txt', self) self._group_box_add_txt_layout = QVBoxLayout() self._group_box_add_txt.setLayout(self._group_box_add_txt_layout) temp = cf.LABELS self.items = [] # 获取所有的标签 for i in temp: self.items.append(i['attributes']['class']) # 假如下拉框 self.combo_box.addItems(self.items) self.add_txt_btn = QPushButton('add txt') self.add_txt_btn.clicked.connect(self.add_txt) # 加入下拉框和按钮 self._group_box_add_txt_layout.addWidget(self.combo_box, 0) self._group_box_add_txt_layout.addWidget(self.add_txt_btn, 1) # 根据关键字搜索图片模块 self._group_box_add_files = QGroupBox('add files', self) # 文件名包含的 self._key_word = QLineEdit('') self._key_word.setPlaceholderText('Second') # 文件类型 self._extension = QLineEdit('') self._extension.setPlaceholderText('bmp') self._search_btn = QPushButton('search files') self._group_box_add_files_layout = QVBoxLayout() # 加入控件 self._group_box_add_files_layout.addWidget(self._key_word, 0) self._group_box_add_files_layout.addWidget(self._extension, 1) self._group_box_add_files_layout.addWidget(self._search_btn, 2) self._group_box_add_files.setLayout(self._group_box_add_files_layout) # 添加标签模块 self._group_box_add_label = QGroupBox("添加标签", self) self._add_label_group_layout = QVBoxLayout() self._group_box_add_label.setLayout(self._add_label_group_layout) # 标签的class self.attributes_LineEdit = QLineEdit('') self.attributes_LineEdit.setPlaceholderText('attributes') # 标签画出来的类型 self.attributes_type = QComboBox() self.attributes_type.addItems(self.get_attributes_type()) # 快捷键,目前设置了只允许一个键 self.hotkey = QLineEdit('') self.hotkey.setPlaceholderText('hotkey') self.regx = QRegExp("[a-z0-9]$") self.validator = QRegExpValidator(self.regx, self.hotkey) self.hotkey.setValidator(self.validator) # 标签显示 self.text_LineEdit = QLineEdit('') self.text_LineEdit.setPlaceholderText('text') # 颜色 color = QtGui.QColor(0, 0, 0) self.color_label = QtGui.QWidget() self.color_label.setStyleSheet("QWidget { background-color: %s }" % color.name()) self.color_info = [0, 0, 0] self.color_layout = QtGui.QHBoxLayout() self.color_btn = QPushButton('选择颜色') self.color_btn.clicked.connect(self.color_dialog) self.color_layout.addWidget(self.color_label) self.color_layout.addWidget(self.color_btn) # 笔刷 global brush2idx self.brush_combo_box = QComboBox() self.brush_combo_box.addItems(list(brush2idx.keys())) # 按钮 self.attributes_add_btn = QPushButton('添加标签') self.attributes_add_btn.clicked.connect(self.add_attributes) # 加入控件 self._add_label_group_layout.addWidget(self.attributes_LineEdit, 0) self._add_label_group_layout.addWidget(self.attributes_type, 1) self._add_label_group_layout.addWidget(self.hotkey, 2) self._add_label_group_layout.addWidget(self.text_LineEdit, 3) self._label_widget = QWidget() self._label_widget.setLayout(self.color_layout) self._add_label_group_layout.addWidget(self._label_widget, 4) self._add_label_group_layout.addWidget(self.brush_combo_box, 5) self._add_label_group_layout.addWidget(self.attributes_add_btn, 6) # 生成训练数据按钮 self._file_button = QPushButton('生成训练数据') self._file_button.clicked.connect(self.generate) # Global widget self._layout = MyVBoxLayout() self.setLayout(self._layout) self._layout.addWidget(self._classbox, 1) self._layout.insertWidget(-1, self._group_box_add_label, 1) self._layout.insertWidget(-1, self._group_box_add_txt, 1) self._layout.insertWidget(-1, self._group_box_add_files, 1) self._layout.insertWidget(-1, self._file_button, 1)
class ViewDataToolsHistory(QMainWindow): def __init__(self, parent=None): super(ViewDataToolsHistory, self).__init__(parent) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # DATATOOLS HISTORY WINDOWS: # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ self.setWindowTitle(ui_strings.DATATOOLS_HISTORY_TITLE) self._width = 700 self._height = 380 self._left_margin = 10 self.resize(self._width, self._height) size_policy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) size_policy.setHorizontalStretch(0) size_policy.setVerticalStretch(0) size_policy.setHeightForWidth(self.sizePolicy().hasHeightForWidth()) self.setSizePolicy(size_policy) self.setMinimumSize(QtCore.QSize(self._width, self._height)) self.setMaximumSize(QtCore.QSize(self._width, self._height)) self.setWindowIcon(QIcon(resources.ICON_LOGO)) # central widget self.central_widget = QWidget(self) # toolbar # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # add toolbar options self.export_action = QAction(QIcon(resources.ICON_EXPORT), 'Export (Ctrl+E)', self) self.export_action.setShortcut('Ctrl+E') self.print_action = QAction(QIcon(resources.ICON_PRINT), 'Print (Ctrl+P)', self) self.print_action.setShortcut('Ctrl+P') self.toolbar = self.addToolBar('Options') self.toolbar.addAction(self.export_action) self.toolbar.addAction(self.print_action) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # group input files self.group_period = QGroupBox(self.central_widget) self.group_period.setGeometry( QtCore.QRect(self._left_margin, 10, 250, 50)) self.group_period.setTitle(ui_strings.DATATOOLS_HISTORY_FILTER) # group by: self.group_group_by = QGroupBox(self.central_widget) self.group_group_by.setGeometry(QtCore.QRect(270, 10, 250, 50)) self.group_group_by.setTitle(ui_strings.DATATOOLS_HISTORY_GROUP) # group by: errors self.rbtn_by_errors = QRadioButton( ui_strings.DATATOOLS_HISTORY_GROUP_ERROR, self.group_group_by) self.rbtn_by_errors.setGeometry(QtCore.QRect(10, 10, 80, 50)) # group by: status #self.group_by_status = QRadioButton(ui_strings.DATATOOLS_HISTORY_GROUP_STATUS, self.group_group_by) #self.group_by_status.setGeometry(QtCore.QRect(100, 10, 80, 50)) # group by: no group #self.group_by_no = QRadioButton(ui_strings.DATATOOLS_HISTORY_GROUP_NO, self.group_group_by) #self.group_by_no.setGeometry(QtCore.QRect(190, 10, 80, 50)) # push button to update table #self.btn_view_group = QPushButton(self.group_group_by) #self.btn_view_group.setGeometry(QtCore.QRect(160, 20, 50, 20)) #self.btn_view_group.setText(ui_strings.DATATOOLS_HISTORY_VIEW) # combobox periods self.cbo_period = QComboBox(self.group_period) self.cbo_period.setGeometry( QtCore.QRect(self._left_margin, 20, 130, 20)) # push button to update table #self.btn_view = QPushButton(self.group_period) #self.btn_view.setGeometry(QtCore.QRect(160, 20, 50, 20)) #self.btn_view.setText(ui_strings.DATATOOLS_HISTORY_VIEW) # table history self.tbl_uploads = QTableWidget(self.central_widget) self.tbl_uploads.setGeometry( QtCore.QRect(self._left_margin, 70, 680, 120)) # chart self.plot_widget = PlotWidget(self.central_widget, 8, 2) self.plot_widget.setGeometry( QtCore.QRect(self._left_margin, 200, 680, 130)) # records - "x records found" self.setCentralWidget(self.central_widget)
class urlgroup(QGroupBox): def __init__(self, parent=None): super(urlgroup, self).__init__(parent) self.setGeometry(10,30,500,80) self.setObjectName('urlgroup') self.urlbar = QLineEdit() self.urlbar.setObjectName('urlbar') self.urlbar.setText('Collez votre URL içi') self.urlbar.setStyleSheet('font-weight:lighter;color:gray;') self.urlbar.show() self.parsebutton = QPushButton('Go !!') self.parsebutton.setObjectName('parsebutton') self.parsebutton.show() layout = QBoxLayout(QBoxLayout.LeftToRight, self) layout.addWidget(self.urlbar) layout.addWidget(self.parsebutton) self.show() self.group2 = QGroupBox(parent) self.group2.setObjectName('core') self.group2.setGeometry(10,120,500,280) self.group2.show() self.group3 = QGroupBox(self.group2) self.group3.setObjectName('albuminfos') self.group3.setGeometry(10,15,200,245) self.group3.show() self.itemlist = QListWidget(self.group2) self.itemlist.setGeometry(250,15,230,245) self.itemlist.show() self.dlgroup = QGroupBox(parent) self.dlgroup.setObjectName('dlgroup') self.dlgroup.setGeometry(10,420,500,100) self.dlgroup.show() self.dlgroup.dlbutton = QPushButton('Download', self.dlgroup) self.dlgroup.dlbutton.setObjectName('dlbutton') self.dlgroup.dlbutton.move(10,20) self.dlgroup.dlbutton.show() self.dlgroup.progressbar = QProgressBar(self.dlgroup) self.dlgroup.progressbar.setObjectName('progressbar') self.dlgroup.progressbar.setGeometry(100,21,380,21) self.dlgroup.progressbar.show() self.dlgroup.dlinfos = QLabel(self.dlgroup) self.dlgroup.dlinfos.setGeometry(100,70,200,21) self.dlgroup.dlinfos.show() self.dlgroup.dledfile = QLabel(self.dlgroup) self.dlgroup.dledfile.setGeometry(300,70,200,21) self.dlgroup.dledfile.show() self.dlgroup.dlto = QLineEdit('C:\\', self.dlgroup) self.dlgroup.dlto.setGeometry(100,50,350,21) self.dlgroup.dlto.show() self.dlgroup.dlto.changebt = QToolButton(self.dlgroup) self.dlgroup.dlto.changebt.setObjectName('dltobt') self.dlgroup.dlto.changebt.setGeometry(10,50,75,21) self.dlgroup.dlto.changebt.setText('To') self.dlgroup.dlto.changebt.show() self.dlgroup.dlto.openf = QPushButton('Open', self.dlgroup) self.dlgroup.dlto.openf.setGeometry(455,50,35,21) self.dlgroup.dlto.openf.setObjectName('openfolder') self.dlgroup.dlto.openf.show() self.album = QLabel(self.group3) self.artist = QLabel(self.group3) self.year = QLabel(self.group3) self.tracks = QLabel(self.group3) self.coverart = QLabel(self.group3) self.urlbar.setFocus(True) self.connect(self.parsebutton, SIGNAL('clicked()'), self.parseclicked ) self.connect(self.dlgroup.dlbutton, SIGNAL('clicked()'), self.launchdl) self.connect(self.dlgroup.dlto.changebt, SIGNAL('clicked()'), self.changedir) self.connect(self.dlgroup.dlto.openf, SIGNAL('clicked()'), self.openfolder) def parseclicked(self): self.itemlist.clear() url = str(self.urlbar.text()) self.infos = getsonglist(url) if (self.infos == 'connexion impossible') or (self.infos == 'unsupported'): self.error = QMessageBox() if self.infos == 'connexion impossible': self.error.setText('Connexion Impossible !') elif self.infos == 'unsupported': self.error.setText('Site Unsupported !!') self.error.setWindowTitle('Erreur!') self.error.setIcon(QMessageBox.Warning) self.icon = QIcon('images/mainwindowicon.png') self.error.setWindowIcon(self.icon) self.error.exec_() else: self.artist.setText('Artiste : ' + self.infos['artist']) self.artist.move(40,175) self.artist.show() self.album.setText('Album : ' + self.infos['albumname']) self.album.move(40,190) self.album.show() try: self.year.setText('Annee : ' + self.infos['year']) except KeyError: self.year.setText('Annee : ' + 'N/A') self.year.move(40,205) self.year.show() self.tracks.setText('Tracks : ' + str(self.infos['tracks'])) self.tracks.move(40,220) self.tracks.show() coverartpix = QPixmap(self.infos['coverart']) coverartpix = coverartpix.scaled(178,135,) self.coverart.setPixmap(coverartpix) self.coverart.move(10,10) self.coverart.show() self.list2 = [] for item in self.infos['titles']: item = tracklistitems(item) self.list2.append(item) for item in self.list2: self.itemlist.addItem(item) def launchdl(self): if self.dlgroup.dlbutton.text() == 'Download': try: self.itemlist.item(self.currentitem).setText(self.text) except: pass self.dlgroup.dlbutton.setText('Stop') rmtree('tmpimg', True) i= 0 dllist = [] for item in self.list2: if item.eligible() =='Checked': dllist.append(i) i= i+1 self.stritemlist = [] for i in range(0,self.infos['tracks']): #print i #print self.itemlist.item(i).text() #TODO: hamida album breaks, recheck regexes self.stritemlist.append(str(self.itemlist.item(i).text())) dlto = self.dlgroup.dlto.text() self.thread = dlThread(dllist, self.infos, dlto, self.stritemlist) self.connect(self.thread, SIGNAL('progress(PyQt_PyObject)'), self.updateProgress) self.connect(self.thread, SIGNAL('dledfile(PyQt_PyObject)'), self.updateDlednow) self.thread.start() else: self.dlgroup.dlbutton.setText('Download') self.thread.terminate() def updateProgress(self, progress): self.dlgroup.progressbar.setValue(progress['bar']) self.dlgroup.dlinfos.setText(progress['info']) self.text = self.stritemlist[progress['item']] self.currentitem = progress['item'] self.percent = str(progress['bar']) + ' % - ' self.percent = QString(self.percent) self.dlingicon = QIcon('images/dling.png') self.doneicon = QIcon('images/done.png') self.itemlist.item(progress['item']).setIcon(self.dlingicon) self.itemlist.item(progress['item']).setText(self.percent + self.text) if progress['bar'] >= 98: self.itemlist.item(progress['item']).setIcon(self.doneicon) self.itemlist.item(progress['item']).setText(self.text) self.itemlist.item(progress['item']).setCheckState(Qt.Unchecked) self.itemlist.item(progress['item']).setFlags(Qt.ItemIsEnabled | Qt.ItemIsEditable | Qt.ItemIsSelectable) def updateDlednow(self, dledfile): self.dlgroup.dledfile.setText(dledfile) def changedir(self): self.dir = QFileDialog.getExistingDirectory() self.dlgroup.dlto.setText(self.dir + '/') def openfolder(self): startfile(self.dlgroup.dlto.text()) def stopdl(self): pass
class ViewDataTools(QMainWindow): def __init__(self, parent=None): super(ViewDataTools, self).__init__(parent) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # DATATOOLS WINDOWS: # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ self.setWindowTitle(ui_strings.DATATOOLS_TITLE) self._width = 680 self._height = 560 self._left_margin = 10 self.resize(self._width, self._height) size_policy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) size_policy.setHorizontalStretch(0) size_policy.setVerticalStretch(0) size_policy.setHeightForWidth(self.sizePolicy().hasHeightForWidth()) self.setSizePolicy(size_policy) self.setMinimumSize(QtCore.QSize(self._width, self._height)) self.setMaximumSize(QtCore.QSize(self._width, self._height)) self.setWindowIcon(QIcon(resources.ICON_LOGO)) # central widget self.central_widget = QWidget(self) # DataTools description self.lbl_description = QLabel(self.central_widget) self.lbl_description.setGeometry(QtCore.QRect(0, 0, self._width, 30)) self.lbl_description.setAlignment(QtCore.Qt.AlignCenter) self.lbl_description.setText(ui_strings.DATATOOLS_DESCRIPTION) # group input files self.group_input_file = QGroupBox(self.central_widget) self.group_input_file.setGeometry(QtCore.QRect(self._left_margin, 30, 660, 80)) self.group_input_file.setTitle(ui_strings.DATATOOLS_GROUP_INPUT) # frame input files self.frame_inputs = QFrame(self.group_input_file) self.frame_inputs.setGeometry(QtCore.QRect(self._left_margin, 0, 270, 80)) self.frame_inputs.setFrameShape(QFrame.StyledPanel) self.frame_inputs.setFrameShadow(QFrame.Raised) # label input type self.lbl_input_type = QLabel(self.frame_inputs) self.lbl_input_type.setGeometry(QtCore.QRect(20, 20, 60, 15)) self.lbl_input_type.setText(ui_strings.DATATOOLS_INPUT_TYPE) # button xls self.btn_xls = QToolButton(self.frame_inputs) self.btn_xls.setGeometry(QtCore.QRect(20, 35, 35, 35)) icon_xls = QIcon() icon_xls.addPixmap(QPixmap(resources.ICON_XLS), QIcon.Normal, QIcon.Off) self.btn_xls.setIcon(icon_xls) self.btn_xls.setIconSize(QtCore.QSize(24, 24)) self.btn_xls.setCheckable(True) self.btn_xls.setAutoExclusive(True) self.btn_xls.setObjectName("xls_button") # button csv self.btn_csv = QToolButton(self.frame_inputs) self.btn_csv.setGeometry(QtCore.QRect(60, 35, 35, 35)) icon_csv = QIcon() icon_csv.addPixmap(QPixmap(resources.ICON_CSV), QIcon.Normal, QIcon.Off) self.btn_csv.setIcon(icon_csv) self.btn_csv.setIconSize(QtCore.QSize(24, 24)) self.btn_csv.setCheckable(True) self.btn_csv.setAutoExclusive(True) self.btn_csv.setObjectName("csv_button") # checkbox csv with headers self.chk_csv_headers = QCheckBox(ui_strings.DATATOOLS_WITH_HEADERS, self.frame_inputs) self.chk_csv_headers.setGeometry(QtCore.QRect(100, 45, 110, 15)) self.chk_csv_headers.setEnabled(False) # TextEdit + PushButton (FindFolder) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # lbl sheet name self.lbl_file_path = QLabel(self.group_input_file) self.lbl_file_path.setGeometry(QtCore.QRect(250, 20, 120, 15)) self.lbl_file_path.setText(ui_strings.DATATOOLS_SELECT_FILE) self.txt_file = QLineEdit(self.group_input_file) self.txt_file.setGeometry(QtCore.QRect(250, 35, 160, 20)) self.txt_file.setReadOnly(True) self.btn_path = QPushButton(self.group_input_file) self.btn_path.setGeometry(QtCore.QRect(410, 34, 50, 22)) self.btn_path.setText(ui_strings.DATATOOLS_SELECT_BUTTON) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # lbl sheet name self.lbl_sheet_name = QLabel(self.group_input_file) self.lbl_sheet_name.setGeometry(QtCore.QRect(500, 20, 120, 15)) self.lbl_sheet_name.setText(ui_strings.DATATOOLS_SHEET_NAME) # Combobox select sheet - initially does not contain values self.cbo_sheet = QComboBox(self.group_input_file) self.cbo_sheet.setGeometry(QtCore.QRect(500, 35, 130, 20)) # data grid to visualize error messages self.tbl_errors = QTableWidget(self.central_widget) self.tbl_errors.setGeometry(QtCore.QRect(self._left_margin, 420, 660, 100)) # data grid to visualize those records with errors. self.tbl_uploaded_data = QTableWidget(self.central_widget) self.tbl_uploaded_data.setGeometry(QtCore.QRect(self._left_margin, 120, 500, 220)) # group run options self.group_run_options = QGroupBox(self.central_widget) self.group_run_options.setGeometry(QtCore.QRect(520, 120, 150, 220)) self.group_run_options.setTitle(ui_strings.DATATOOLS_GROUP_RUN) # Errors summary: # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # group summary errors self.group_errors = QGroupBox(self.central_widget) self.group_errors.setGeometry(QtCore.QRect(self._left_margin, 350, 660, 60)) self.group_errors.setTitle(ui_strings.DATATOOLS_HEADER_ERRORS) # lbl records self.lbl_records = QLabel(self.group_errors) self.lbl_records.setGeometry(QtCore.QRect(165, 15, 80, 15)) self.lbl_records.setAlignment(QtCore.Qt.AlignCenter) self.lbl_records.setText(ui_strings.DATATOOLS_RECORDS) self.txt_records = QLineEdit(self.group_errors) self.txt_records.setGeometry(QtCore.QRect(165, 30, 80, 20)) self.txt_records.setAlignment(QtCore.Qt.AlignCenter) self.txt_records.setReadOnly(True) # lbl errors self.lbl_errors = QLabel(self.group_errors) self.lbl_errors.setGeometry(QtCore.QRect(275, 15, 80, 15)) self.lbl_errors.setAlignment(QtCore.Qt.AlignCenter) self.lbl_errors.setText(ui_strings.DATATOOLS_ERRORS) self.txt_errors = QLineEdit(self.group_errors) self.txt_errors.setGeometry(QtCore.QRect(275, 30, 80, 20)) self.txt_errors.setAlignment(QtCore.Qt.AlignCenter) self.txt_errors.setReadOnly(True) # lbl time self.lbl_time = QLabel(self.group_errors) self.lbl_time.setGeometry(QtCore.QRect(385, 15, 80, 15)) self.lbl_time.setAlignment(QtCore.Qt.AlignCenter) self.lbl_time.setText(ui_strings.DATATOOLS_TIME) self.txt_time = QLineEdit(self.group_errors) self.txt_time.setGeometry(QtCore.QRect(385, 30, 80, 20)) self.txt_time.setAlignment(QtCore.Qt.AlignCenter) self.txt_time.setReadOnly(True) # history button self.btn_history = QToolButton(self.group_errors) self.btn_history.setGeometry(QtCore.QRect(500, 25, 100, 25)) icon_history = QIcon() icon_history.addPixmap(QPixmap(resources.ICON_HISTORY), QIcon.Normal, QIcon.Off) self.btn_history.setIcon(icon_history) self.btn_history.setIconSize(QtCore.QSize(20, 20)) self.btn_history.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon) self.btn_history.setText(ui_strings.DATATOOLS_HISTORY) self.btn_history.setCheckable(True) self.btn_history.setAutoExclusive(True) self.btn_history.setObjectName("history_button") # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # btn data uploader self.btn_data_uploader = QPushButton(ui_strings.DATATOOLS_DATA_UPLOADER, self.group_run_options) self.btn_data_uploader.setGeometry(QtCore.QRect(10, 120, 90, 25)) self.btn_data_uploader.setCheckable(True) self.btn_data_uploader.setAutoExclusive(True) self.btn_data_uploader.setFlat(False) # btn data testing self.btn_data_testing = QPushButton(ui_strings.DATATOOLS_DATA_TESTING, self.group_run_options) self.btn_data_testing.setEnabled(False) self.btn_data_testing.setGeometry(QtCore.QRect(10, 150, 90, 25)) self.btn_data_testing.setCheckable(True) self.btn_data_testing.setAutoExclusive(True) # btn data to database self.btn_data_db = QPushButton(ui_strings.DATATOOLS_DATA_DB, self.group_run_options) self.btn_data_db.setEnabled(False) self.btn_data_db.setGeometry(QtCore.QRect(10, 179, 91, 23)) self.btn_data_db.setCheckable(True) self.btn_data_db.setAutoExclusive(True) # frame run options self.frame_run = QFrame(self.group_run_options) self.frame_run.setGeometry(QtCore.QRect(10, 30, 130, 80)) self.frame_run.setFrameShape(QFrame.StyledPanel) self.frame_run.setFrameShadow(QFrame.Raised) # option process until first error self.rbtn_process_error = QRadioButton(ui_strings.DATATOOLS_PROCESS_ERROR, self.frame_run) self.rbtn_process_error.setGeometry(QtCore.QRect(0, 0, 150, 20)) # option process all data self.rbtn_process_all = QRadioButton(ui_strings.DATATOOLS_PROCESS_ALL, self.frame_run) self.rbtn_process_all.setGeometry(QtCore.QRect(0, 20, 150, 30)) # checkbox to filter by records with errors. #self.chk_filter_errors = QCheckBox(ui_strings.DATATOOLS_FILTER_ERRORS, self.frame_run) #self.chk_filter_errors.setGeometry(QtCore.QRect(0, 50, 100, 15)) #self.chk_filter_errors.setEnabled(False) # icons -> pass - error: Initially are empty labels # if not started -> ICON_MINI_WAIT # if error -> ICON_DELETE # if pass -> ICON_CHECK # state icon data uploader self.lbl_state_du = QLabel(self.group_run_options) self.lbl_state_du.setGeometry(QtCore.QRect(110, 120, 20, 20)) self.lbl_state_du.setPixmap(QPixmap(resources.ICON_MINI_WAIT)) self.lbl_state_du.setScaledContents(True) # state icon data to database self.lbl_state_dt = QLabel(self.group_run_options) self.lbl_state_dt.setGeometry(QtCore.QRect(110, 150, 20, 20)) self.lbl_state_dt.setPixmap(QPixmap(resources.ICON_MINI_WAIT)) self.lbl_state_dt.setScaledContents(True) # state icon data testing self.lbl_state_db = QLabel(self.group_run_options) self.lbl_state_db.setGeometry(QtCore.QRect(110, 180, 20, 20)) self.lbl_state_db.setPixmap(QPixmap(resources.ICON_MINI_WAIT)) self.lbl_state_db.setScaledContents(True) # progress bar self.progress_bar = QProgressBar(self.central_widget) self.progress_bar.setGeometry(QtCore.QRect(self._left_margin, 530, 660, 15)) self.progress_bar.setMaximum(100) self.progress_bar.setProperty("value", 0) self.progress_bar.setTextVisible(True) self.progress_bar.setOrientation(QtCore.Qt.Horizontal) self.progress_bar.setInvertedAppearance(False) self.progress_bar.setTextDirection(QProgressBar.TopToBottom) self.setCentralWidget(self.central_widget)
class EncryptDialog(QDialog): def __init__(self): self.techniquesClass = { 'caesar cipher': caesarCipher, 'mono alphabetic cipher': monoAlphabeticCipher, 'vigenere cipher': vigenereCipher, 'vernan cipher': vernanCipher, 'one time pad': oneTimePad } self.rowsview = [] self.filesview = [] self.techniques = [] QDialog.__init__(self) self.setWindowTitle("CryptoSystems") self.resize(1024, 600) self.setMinimumSize(QSize(1024, 600)) self.setMaximumSize(QSize(1024, 600)) self.checkBox_2 = QCheckBox(self) self.checkBox_2.setGeometry(QRect(620, 10, 130, 20)) self.checkBox_2.setText('Select All') self.checkBox_2.clicked.connect(self.__selectAllFiles) self.treeView = QTreeView(self) self.treeView.setGeometry(QRect(10, 10, 230, 580)) self.treeView.setObjectName("treeView") self.fileSystemModel = QFileSystemModel(self.treeView) self.fileSystemModel.setReadOnly(False) self.fileSystemModel.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot) root = self.fileSystemModel.setRootPath("/") self.treeView.setModel(self.fileSystemModel) self.treeView.setRootIndex(root) self.treeView.hideColumn(1) self.treeView.hideColumn(2) self.treeView.hideColumn(3) self.treeView.clicked.connect(self.__eventDirectoryChanged) self.mygroupbox = QGroupBox(self) self.mygroupbox.setGeometry(QRect(0, 0, 1000, 1000)) self.myform = QFormLayout() for j in list(range(100)): horizontalLayout = QHBoxLayout() self.myform.addRow(horizontalLayout) self.rowsview.append(horizontalLayout) self.mygroupbox.setLayout(self.myform) scroll = QScrollArea(self) scroll.setWidget(self.mygroupbox) scroll.setWidgetResizable(True) scroll.setGeometry(QRect(250, 30, 500, 580)) scroll.setWidgetResizable(True) self.label_4 = QLabel(self) self.label_4.setGeometry(QRect(780, 30, 31, 16)) self.label_4.setPixmap(QPixmap("images/key.png")) self.label_4.setScaledContents(True) self.lineEdit = QLineEdit(self) self.lineEdit.setGeometry(QRect(820, 30, 180, 20)) self.lineEdit.setObjectName("lineEdit") self.lineEdit.setPlaceholderText(_fromUtf8('write your password')) self.lineEdit.setEchoMode(QLineEdit.Password) self.techniquesGroup = QGroupBox(self) self.tecniquesform = QFormLayout() self.techniquesGroup.setLayout(self.tecniquesform) self.techniquesScroll = QScrollArea(self) self.techniquesScroll.setGeometry(QRect(770, 100, 230, 300)) self.techniquesScroll.setWidget(self.techniquesGroup) self.techniquesScroll.setWidgetResizable(True) self.rowsTechiques = [] for i in list(range(8)): horizontalLayout = QHBoxLayout() self.tecniquesform.addRow(horizontalLayout) self.rowsTechiques.append(horizontalLayout) techniquesCombo = QComboBox() techniquesCombo.setGeometry(QRect(10, 50, 171, 22)) techniquesCombo.addItems(self.techniquesClass.keys()) self.techniques.append(techniquesCombo) self.rowsTechiques[0].addWidget(techniquesCombo) self.techniquesNumber = 1 self.addTechnique = QPushButton() self.addTechnique.setGeometry(QRect(90, 90, 31, 21)) self.addTechnique.setFixedSize(31, 21) self.addTechnique.setText('+') self.connect(self.addTechnique, SIGNAL("clicked()"), self.__eventAddTechnique) self.rowsTechiques[len(self.rowsTechiques) - 1].addWidget( self.addTechnique) self.okButton = QPushButton(self) self.okButton.setGeometry(QRect(920, 560, 80, 20)) self.okButton.setText('Start...') self.connect(self.okButton, SIGNAL("clicked()"), self.__eventInitEncryption) def __eventAddTechnique(self): techniquesCombo = QComboBox() techniquesCombo.setGeometry(QRect(10, 50, 171, 22)) techniquesCombo.addItems(self.techniquesClass.keys()) self.techniques.append(techniquesCombo) self.rowsTechiques[self.techniquesNumber].addWidget(techniquesCombo) self.techniquesNumber = self.techniquesNumber + 1 if ((len(self.rowsTechiques) - 1) == self.techniquesNumber): self.addTechnique.setEnabled(False) def __eventDirectoryChanged(self): index = self.treeView.currentIndex() self.__changeDirectory(self.fileSystemModel.filePath(index)) def __changeDirectory(self, path): for c in self.filesview: c.setParent(None) c.deleteLater() self.filesview = [] self.checkBox_2.setChecked(False) self.progressBars = {} for f in self.__getFiles(path): try: group = QGroupBox(f, self) group.setGeometry(QRect(20, 20, 100, 150)) group.setCheckable(True) group.setChecked(False) group.setFixedSize(100, 150) group.setFlat(True) group.setToolTip(f) label = QLabel(group) label.setScaledContents(True) label.setGeometry(QRect(5, 25, 90, 90)) label.setToolTip(f) progressBar = QProgressBar(group) progressBar.setGeometry(QRect(0, 70, 111, 10)) progressBar.setProperty("value", 0) progressBar.setTextVisible(False) progressBar.setToolTip('0%') progressBar.setVisible(False) self.progressBars[f] = progressBar self.filesview.append(group) from os.path import isfile if isfile(path + '/' + f): ext = f.split('.')[-1] if isfile('icons/' + ext.lower() + '.png'): label.setPixmap( QPixmap('icons/' + ext.lower() + '.png')) else: label.setPixmap(QPixmap('icons/default.png')) else: label.setPixmap(QPixmap('icons/folder.png')) self.connect(group, SIGNAL("clicked()"), self.__deselectFile) except ValueError: pass i = 0 for x in list(range(len(self.filesview))): if (x % 4) == 0: i = i + 1 self.rowsview[i].addWidget(self.filesview[x]) def __selectAllFiles(self): for o in self.filesview: o.setChecked(self.checkBox_2.isChecked()) def __deselectFile(self): #print 'deselect' self.checkBox_2.setChecked(False) def __arrozconpollo(self): self.__obtainSelectedFIles() def __obtainSelectedFIles(self): files = [] for o in self.filesview: if o.isChecked(): files.append(str(o.title())) self.progressBars[str(o.title())].setVisible(True) return files def __getFiles(self, path): from os import listdir from os.path import isfile f = [] for base in listdir(path): try: if isfile(path + '/' + base): f.append(base) except ValueError: pass f.sort() return f def __eventInitEncryption(self): if len(self.__obtainSelectedFIles()) == 0: msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("You must specify the files you want to encrypt") msg.setWindowTitle("CryptoSystems") msg.setStandardButtons(QMessageBox.Ok) msg.exec_() return if str(self.lineEdit.text()).strip() == '': msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("You must specify a key") msg.setWindowTitle("CryptoSystems") msg.setStandardButtons(QMessageBox.Ok) msg.exec_() return self.okButton.setEnabled(False) self.techniquesGroup.setEnabled(False) self.lineEdit.setEnabled(False) index = self.treeView.currentIndex() path = self.fileSystemModel.filePath(index) selectedFiles = self.__obtainSelectedFIles() from os.path import getsize blockSize = 4096 from hashlib import md5 Hash = md5() Hash.update(str(self.lineEdit.text())) key = Hash.hexdigest() for f in selectedFiles: f_in = open(path + '/' + f, 'rb') f_out = open( path + '/' + reduceMd5(checksum(path + '/' + f)) + '.cry', 'wb') f_out.write('CRYOGENESIS' + unhexlify('00') + 'ARCHIVE' + unhexlify('01')) header_list = '' techniquesObjects = [] for t in self.techniques: header_list = header_list + t.currentText() + ':' techniquesObjects.append(self.techniquesClass[str( t.currentText())](key)) file_header = str('header|' + str(f_in.name.split('/')[-1]) + '|' + str(header_list) + '|' + str(checksum(path + '/' + f))) aes = AES(key) f_out.write(aes.encrypt(file_header)) f_out.write(unhexlify('02')) in_size = getsize(path + '/' + f) in_progress = 0.0 block = f_in.read(blockSize) while (block): block_c = block for t in techniquesObjects: block_c = t.encrypt(block_c) f_out.write(block_c) in_progress = in_progress + blockSize progress = (in_progress / in_size) * 100 #print progress self.progressBars[str(f)].setProperty("value", int(progress)) self.progressBars[str(f)].setToolTip(str(progress) + '%') block = f_in.read(blockSize) f_in.close() f_out.close() msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setText("Encryption has successfully concluded") msg.setWindowTitle("CryptoSystems") msg.setStandardButtons(QMessageBox.Ok) msg.exec_() self.hide()
class DecryptDialog(QDialog): def __init__(self): self.techniquesClass = { 'caesar cipher': caesarCipher, 'mono alphabetic cipher': monoAlphabeticCipher, 'vigenere cipher': vigenereCipher, 'vernan cipher': vernanCipher, 'one time pad': oneTimePad } self.rowsview = [] self.filesview = [] #self.techniques = [] QDialog.__init__(self) self.setWindowTitle("Desencriptador de Cryogenesis Systems.") self.resize(1024, 600) self.setMinimumSize(QSize(1024, 600)) self.setMaximumSize(QSize(1024, 600)) self.checkBox_2 = QCheckBox(self) self.checkBox_2.setGeometry(QRect(620, 10, 130, 20)) self.checkBox_2.setText('seleccionar todos') self.checkBox_2.clicked.connect(self.__selectAllFiles) self.treeView = QTreeView(self) self.treeView.setGeometry(QRect(10, 10, 230, 580)) self.treeView.setObjectName("treeView") self.fileSystemModel = QFileSystemModel(self.treeView) self.fileSystemModel.setReadOnly(False) self.fileSystemModel.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot) root = self.fileSystemModel.setRootPath("/") self.treeView.setModel(self.fileSystemModel) self.treeView.setRootIndex(root) self.treeView.hideColumn(1) self.treeView.hideColumn(2) self.treeView.hideColumn(3) self.treeView.clicked.connect(self.__eventDirectoryChanged) self.mygroupbox = QGroupBox(self) self.mygroupbox.setGeometry(QRect(0, 0, 1000, 1000)) self.myform = QFormLayout() for j in list(range(100)): horizontalLayout = QHBoxLayout() self.myform.addRow(horizontalLayout) self.rowsview.append(horizontalLayout) self.mygroupbox.setLayout(self.myform) scroll = QScrollArea(self) scroll.setWidget(self.mygroupbox) scroll.setWidgetResizable(True) scroll.setGeometry(QRect(250, 30, 500, 580)) scroll.setWidgetResizable(True) self.label_4 = QLabel(self) self.label_4.setGeometry(QRect(780, 30, 31, 16)) self.label_4.setPixmap(QPixmap("images/key.png")) self.label_4.setScaledContents(True) self.lineEdit = QLineEdit(self) self.lineEdit.setGeometry(QRect(820, 30, 180, 20)) self.lineEdit.setObjectName("lineEdit") self.lineEdit.setPlaceholderText(_fromUtf8('escriba su contraseña')) self.lineEdit.setEchoMode(QLineEdit.Password) self.okButton = QPushButton(self) self.okButton.setGeometry(QRect(920, 560, 80, 20)) self.okButton.setText('Iniciar...') self.connect(self.okButton, SIGNAL("clicked()"), self.__eventInitDecryption) def __eventDirectoryChanged(self): index = self.treeView.currentIndex() self.__changeDirectory(self.fileSystemModel.filePath(index)) def __changeDirectory(self, path): for c in self.filesview: c.setParent(None) c.deleteLater() self.filesview = [] self.checkBox_2.setChecked(False) self.progressBars = {} for f in self.__getFiles(path): try: group = QGroupBox(f, self) group.setGeometry(QRect(20, 20, 100, 150)) group.setCheckable(True) group.setChecked(False) group.setFixedSize(100, 150) group.setFlat(True) group.setToolTip(f) label = QLabel(group) label.setScaledContents(True) label.setGeometry(QRect(5, 25, 90, 90)) label.setToolTip(f) progressBar = QProgressBar(group) progressBar.setGeometry(QRect(0, 70, 111, 10)) progressBar.setProperty("value", 0) progressBar.setTextVisible(False) progressBar.setToolTip('0%') progressBar.setVisible(False) self.progressBars[f] = progressBar self.filesview.append(group) from os.path import isfile if isfile(path + '/' + f): ext = f.split('.')[-1] if isfile('icons/' + ext.lower() + '.png'): label.setPixmap( QPixmap('icons/' + ext.lower() + '.png')) else: label.setPixmap(QPixmap('icons/default.png')) else: label.setPixmap(QPixmap('icons/folder.png')) self.connect(group, SIGNAL("clicked()"), self.__deselectFile) except ValueError: pass i = 0 for x in list(range(len(self.filesview))): if (x % 4) == 0: i = i + 1 self.rowsview[i].addWidget(self.filesview[x]) def __selectAllFiles(self): for o in self.filesview: o.setChecked(self.checkBox_2.isChecked()) def __deselectFile(self): #print 'deselect' self.checkBox_2.setChecked(False) def __arrozconpollo(self): self.__obtainSelectedFIles() def __obtainSelectedFIles(self): files = [] for o in self.filesview: if o.isChecked(): files.append(str(o.title())) self.progressBars[str(o.title())].setVisible(True) return files def __getFiles(self, path): from os import listdir from os.path import isfile f = [] for base in listdir(path): try: if isfile(path + '/' + base) and base.split('.')[-1] == 'cry': f.append(base) except ValueError: pass f.sort() return f def __eventInitDecryption(self): if len(self.__obtainSelectedFIles()) == 0: msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText( "Debes especificar los archivos que quieres desencriptar") msg.setWindowTitle("Cryosystems") msg.setStandardButtons(QMessageBox.Ok) msg.exec_() return if str(self.lineEdit.text()).strip() == '': msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("Debes especificar una clave") msg.setWindowTitle("Cryosystems") msg.setStandardButtons(QMessageBox.Ok) msg.exec_() return self.okButton.setEnabled(False) self.lineEdit.setEnabled(False) index = self.treeView.currentIndex() path = self.fileSystemModel.filePath(index) selectedFiles = self.__obtainSelectedFIles() from hashlib import md5 Hash = md5() Hash.update(str(self.lineEdit.text())) key = Hash.hexdigest() errors = 0 from os.path import getsize blockSize = 4096 for f in selectedFiles: f_in = open(path + '/' + f, 'rb') print path + '/' + f header = '' if (f_in.read(20) == ('CRYOGENESIS' + unhexlify('00') + 'ARCHIVE' + unhexlify('01'))): while (True): c = f_in.read(1) if c == unhexlify('02'): break else: header = header + c else: print 'esto no es un archivo cifradodo de Cryogenesis Systems' #print key aes = AES(key) #print aes.decrypt(header) header_sections = aes.decrypt(header).split('|') if header_sections[0] != 'header': msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("La clave no es correcta para el archivo:" + f) msg.setWindowTitle("Cryosystems") msg.setStandardButtons(QMessageBox.Ok) msg.exec_() errors = errors + 1 continue f_out = open(path + '/' + header_sections[1], 'wb') techniques = header_sections[2].split(':')[:-1] techniquesObjects = [] for t in techniques: techniquesObjects.append(self.techniquesClass[t](key)) techniquesObjects.reverse() in_size = getsize(path + '/' + f) in_progress = 0.0 block = f_in.read(blockSize) while (block): block_p = block for t in techniquesObjects: block_p = t.decrypt(block_p) f_out.write(block_p) in_progress = in_progress + blockSize progress = (in_progress / in_size) * 100 self.progressBars[str(f)].setProperty("value", int(progress)) self.progressBars[str(f)].setToolTip(str(progress) + '%') block = f_in.read(blockSize) f_in.close() f_out.close() if (checksum(path + '/' + header_sections[1]) != header_sections[3]): msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("El archivo" + f + 'se ha corrompido') msg.setWindowTitle("Cryosystems") msg.setStandardButtons(QMessageBox.Ok) msg.exec_() errors = errors + 1 from os import remove remove(header_sections[1]) msg = QMessageBox() msg.setWindowTitle("Cryosystems") msg.setStandardButtons(QMessageBox.Ok) if (errors == 0): msg.setIcon(QMessageBox.Information) msg.setText("La desencriptacion ha concluido exitosamente") else: msg.setIcon(QMessageBox.Warning) msg.setText("La desencriptacion ha concluido con " + str(errors) + ' error(es)') msg.exec_() self.hide()
class ViewDataToolsHistory(QMainWindow): def __init__(self, parent=None): super(ViewDataToolsHistory, self).__init__(parent) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # DATATOOLS HISTORY WINDOWS: # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ self.setWindowTitle(ui_strings.DATATOOLS_HISTORY_TITLE) self._width = 700 self._height = 380 self._left_margin = 10 self.resize(self._width, self._height) size_policy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) size_policy.setHorizontalStretch(0) size_policy.setVerticalStretch(0) size_policy.setHeightForWidth(self.sizePolicy().hasHeightForWidth()) self.setSizePolicy(size_policy) self.setMinimumSize(QtCore.QSize(self._width, self._height)) self.setMaximumSize(QtCore.QSize(self._width, self._height)) self.setWindowIcon(QIcon(resources.ICON_LOGO)) # central widget self.central_widget = QWidget(self) # toolbar # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # add toolbar options self.export_action = QAction(QIcon(resources.ICON_EXPORT), 'Export (Ctrl+E)', self) self.export_action.setShortcut('Ctrl+E') self.print_action = QAction(QIcon(resources.ICON_PRINT), 'Print (Ctrl+P)', self) self.print_action.setShortcut('Ctrl+P') self.toolbar = self.addToolBar('Options') self.toolbar.addAction(self.export_action) self.toolbar.addAction(self.print_action) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # group input files self.group_period = QGroupBox(self.central_widget) self.group_period.setGeometry(QtCore.QRect(self._left_margin, 10, 250, 50)) self.group_period.setTitle(ui_strings.DATATOOLS_HISTORY_FILTER) # group by: self.group_group_by = QGroupBox(self.central_widget) self.group_group_by.setGeometry(QtCore.QRect(270, 10, 250, 50)) self.group_group_by.setTitle(ui_strings.DATATOOLS_HISTORY_GROUP) # group by: errors self.rbtn_by_errors = QRadioButton(ui_strings.DATATOOLS_HISTORY_GROUP_ERROR, self.group_group_by) self.rbtn_by_errors.setGeometry(QtCore.QRect(10, 10, 80, 50)) # group by: status #self.group_by_status = QRadioButton(ui_strings.DATATOOLS_HISTORY_GROUP_STATUS, self.group_group_by) #self.group_by_status.setGeometry(QtCore.QRect(100, 10, 80, 50)) # group by: no group #self.group_by_no = QRadioButton(ui_strings.DATATOOLS_HISTORY_GROUP_NO, self.group_group_by) #self.group_by_no.setGeometry(QtCore.QRect(190, 10, 80, 50)) # push button to update table #self.btn_view_group = QPushButton(self.group_group_by) #self.btn_view_group.setGeometry(QtCore.QRect(160, 20, 50, 20)) #self.btn_view_group.setText(ui_strings.DATATOOLS_HISTORY_VIEW) # combobox periods self.cbo_period = QComboBox(self.group_period) self.cbo_period.setGeometry(QtCore.QRect(self._left_margin, 20, 130, 20)) # push button to update table #self.btn_view = QPushButton(self.group_period) #self.btn_view.setGeometry(QtCore.QRect(160, 20, 50, 20)) #self.btn_view.setText(ui_strings.DATATOOLS_HISTORY_VIEW) # table history self.tbl_uploads = QTableWidget(self.central_widget) self.tbl_uploads.setGeometry(QtCore.QRect(self._left_margin, 70, 680, 120)) # chart self.plot_widget = PlotWidget(self.central_widget, 8, 2) self.plot_widget.setGeometry(QtCore.QRect(self._left_margin, 200, 680, 130)) # records - "x records found" self.setCentralWidget(self.central_widget)
class urlgroup(QGroupBox): def __init__(self, parent=None): super(urlgroup, self).__init__(parent) self.setGeometry(10, 30, 500, 80) self.setObjectName('urlgroup') self.urlbar = QLineEdit() self.urlbar.setObjectName('urlbar') self.urlbar.setText('Collez votre URL i�i') self.urlbar.setStyleSheet('font-weight:lighter;color:gray;') self.urlbar.show() self.parsebutton = QPushButton('Go !!') self.parsebutton.setObjectName('parsebutton') self.parsebutton.show() layout = QBoxLayout(QBoxLayout.LeftToRight, self) layout.addWidget(self.urlbar) layout.addWidget(self.parsebutton) self.show() self.group2 = QGroupBox(parent) self.group2.setObjectName('core') self.group2.setGeometry(10, 120, 500, 280) self.group2.show() self.group3 = QGroupBox(self.group2) self.group3.setObjectName('albuminfos') self.group3.setGeometry(10, 15, 200, 245) self.group3.show() self.itemlist = QListWidget(self.group2) self.itemlist.setGeometry(250, 15, 230, 245) self.itemlist.show() self.dlgroup = QGroupBox(parent) self.dlgroup.setObjectName('dlgroup') self.dlgroup.setGeometry(10, 420, 500, 100) self.dlgroup.show() self.dlgroup.dlbutton = QPushButton('Download', self.dlgroup) self.dlgroup.dlbutton.setObjectName('dlbutton') self.dlgroup.dlbutton.move(10, 20) self.dlgroup.dlbutton.show() self.dlgroup.progressbar = QProgressBar(self.dlgroup) self.dlgroup.progressbar.setObjectName('progressbar') self.dlgroup.progressbar.setGeometry(100, 21, 380, 21) self.dlgroup.progressbar.show() self.dlgroup.dlinfos = QLabel(self.dlgroup) self.dlgroup.dlinfos.setGeometry(100, 70, 200, 21) self.dlgroup.dlinfos.show() self.dlgroup.dledfile = QLabel(self.dlgroup) self.dlgroup.dledfile.setGeometry(300, 70, 200, 21) self.dlgroup.dledfile.show() self.dlgroup.dlto = QLineEdit('C:\\', self.dlgroup) self.dlgroup.dlto.setGeometry(100, 50, 350, 21) self.dlgroup.dlto.show() self.dlgroup.dlto.changebt = QToolButton(self.dlgroup) self.dlgroup.dlto.changebt.setObjectName('dltobt') self.dlgroup.dlto.changebt.setGeometry(10, 50, 75, 21) self.dlgroup.dlto.changebt.setText('To') self.dlgroup.dlto.changebt.show() self.dlgroup.dlto.openf = QPushButton('Open', self.dlgroup) self.dlgroup.dlto.openf.setGeometry(455, 50, 35, 21) self.dlgroup.dlto.openf.setObjectName('openfolder') self.dlgroup.dlto.openf.show() self.album = QLabel(self.group3) self.artist = QLabel(self.group3) self.year = QLabel(self.group3) self.tracks = QLabel(self.group3) self.coverart = QLabel(self.group3) self.urlbar.setFocus(True) self.connect(self.parsebutton, SIGNAL('clicked()'), self.parseclicked) self.connect(self.dlgroup.dlbutton, SIGNAL('clicked()'), self.launchdl) self.connect(self.dlgroup.dlto.changebt, SIGNAL('clicked()'), self.changedir) self.connect(self.dlgroup.dlto.openf, SIGNAL('clicked()'), self.openfolder) def parseclicked(self): self.itemlist.clear() url = str(self.urlbar.text()) self.infos = getsonglist(url) if (self.infos == 'connexion impossible') or (self.infos == 'unsupported'): self.error = QMessageBox() if self.infos == 'connexion impossible': self.error.setText('Connexion Impossible !') elif self.infos == 'unsupported': self.error.setText('Site Unsupported !!') self.error.setWindowTitle('Erreur!') self.error.setIcon(QMessageBox.Warning) self.icon = QIcon('images/mainwindowicon.png') self.error.setWindowIcon(self.icon) self.error.exec_() else: self.artist.setText('Artiste : ' + self.infos['artist']) self.artist.move(40, 175) self.artist.show() self.album.setText('Album : ' + self.infos['albumname']) self.album.move(40, 190) self.album.show() try: self.year.setText('Annee : ' + self.infos['year']) except KeyError: self.year.setText('Annee : ' + 'N/A') self.year.move(40, 205) self.year.show() self.tracks.setText('Tracks : ' + str(self.infos['tracks'])) self.tracks.move(40, 220) self.tracks.show() coverartpix = QPixmap(self.infos['coverart']) coverartpix = coverartpix.scaled( 178, 135, ) self.coverart.setPixmap(coverartpix) self.coverart.move(10, 10) self.coverart.show() self.list2 = [] for item in self.infos['titles']: item = tracklistitems(item) self.list2.append(item) for item in self.list2: self.itemlist.addItem(item) def launchdl(self): if self.dlgroup.dlbutton.text() == 'Download': try: self.itemlist.item(self.currentitem).setText(self.text) except: pass self.dlgroup.dlbutton.setText('Stop') rmtree('tmpimg', True) i = 0 dllist = [] for item in self.list2: if item.eligible() == 'Checked': dllist.append(i) i = i + 1 self.stritemlist = [] for i in range(0, self.infos['tracks']): #print i #print self.itemlist.item(i).text() #TODO: hamida album breaks, recheck regexes self.stritemlist.append(str(self.itemlist.item(i).text())) dlto = self.dlgroup.dlto.text() self.thread = dlThread(dllist, self.infos, dlto, self.stritemlist) self.connect(self.thread, SIGNAL('progress(PyQt_PyObject)'), self.updateProgress) self.connect(self.thread, SIGNAL('dledfile(PyQt_PyObject)'), self.updateDlednow) self.thread.start() else: self.dlgroup.dlbutton.setText('Download') self.thread.terminate() def updateProgress(self, progress): self.dlgroup.progressbar.setValue(progress['bar']) self.dlgroup.dlinfos.setText(progress['info']) self.text = self.stritemlist[progress['item']] self.currentitem = progress['item'] self.percent = str(progress['bar']) + ' % - ' self.percent = QString(self.percent) self.dlingicon = QIcon('images/dling.png') self.doneicon = QIcon('images/done.png') self.itemlist.item(progress['item']).setIcon(self.dlingicon) self.itemlist.item(progress['item']).setText(self.percent + self.text) if progress['bar'] >= 98: self.itemlist.item(progress['item']).setIcon(self.doneicon) self.itemlist.item(progress['item']).setText(self.text) self.itemlist.item(progress['item']).setCheckState(Qt.Unchecked) self.itemlist.item( progress['item']).setFlags(Qt.ItemIsEnabled | Qt.ItemIsEditable | Qt.ItemIsSelectable) def updateDlednow(self, dledfile): self.dlgroup.dledfile.setText(dledfile) def changedir(self): self.dir = QFileDialog.getExistingDirectory() self.dlgroup.dlto.setText(self.dir + '/') def openfolder(self): startfile(self.dlgroup.dlto.text()) def stopdl(self): pass
class ViewDataTools(QMainWindow): def __init__(self, parent=None): super(ViewDataTools, self).__init__(parent) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # DATATOOLS WINDOWS: # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ self.setWindowTitle(ui_strings.DATATOOLS_TITLE) self._width = 680 self._height = 560 self._left_margin = 10 self.resize(self._width, self._height) size_policy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) size_policy.setHorizontalStretch(0) size_policy.setVerticalStretch(0) size_policy.setHeightForWidth(self.sizePolicy().hasHeightForWidth()) self.setSizePolicy(size_policy) self.setMinimumSize(QtCore.QSize(self._width, self._height)) self.setMaximumSize(QtCore.QSize(self._width, self._height)) self.setWindowIcon(QIcon(resources.ICON_LOGO)) # central widget self.central_widget = QWidget(self) # DataTools description self.lbl_description = QLabel(self.central_widget) self.lbl_description.setGeometry(QtCore.QRect(0, 0, self._width, 30)) self.lbl_description.setAlignment(QtCore.Qt.AlignCenter) self.lbl_description.setText(ui_strings.DATATOOLS_DESCRIPTION) # group input files self.group_input_file = QGroupBox(self.central_widget) self.group_input_file.setGeometry( QtCore.QRect(self._left_margin, 30, 660, 80)) self.group_input_file.setTitle(ui_strings.DATATOOLS_GROUP_INPUT) # frame input files self.frame_inputs = QFrame(self.group_input_file) self.frame_inputs.setGeometry( QtCore.QRect(self._left_margin, 0, 270, 80)) self.frame_inputs.setFrameShape(QFrame.StyledPanel) self.frame_inputs.setFrameShadow(QFrame.Raised) # label input type self.lbl_input_type = QLabel(self.frame_inputs) self.lbl_input_type.setGeometry(QtCore.QRect(20, 20, 60, 15)) self.lbl_input_type.setText(ui_strings.DATATOOLS_INPUT_TYPE) # button xls self.btn_xls = QToolButton(self.frame_inputs) self.btn_xls.setGeometry(QtCore.QRect(20, 35, 35, 35)) icon_xls = QIcon() icon_xls.addPixmap(QPixmap(resources.ICON_XLS), QIcon.Normal, QIcon.Off) self.btn_xls.setIcon(icon_xls) self.btn_xls.setIconSize(QtCore.QSize(24, 24)) self.btn_xls.setCheckable(True) self.btn_xls.setAutoExclusive(True) self.btn_xls.setObjectName("xls_button") # button csv self.btn_csv = QToolButton(self.frame_inputs) self.btn_csv.setGeometry(QtCore.QRect(60, 35, 35, 35)) icon_csv = QIcon() icon_csv.addPixmap(QPixmap(resources.ICON_CSV), QIcon.Normal, QIcon.Off) self.btn_csv.setIcon(icon_csv) self.btn_csv.setIconSize(QtCore.QSize(24, 24)) self.btn_csv.setCheckable(True) self.btn_csv.setAutoExclusive(True) self.btn_csv.setObjectName("csv_button") # checkbox csv with headers self.chk_csv_headers = QCheckBox(ui_strings.DATATOOLS_WITH_HEADERS, self.frame_inputs) self.chk_csv_headers.setGeometry(QtCore.QRect(100, 45, 110, 15)) self.chk_csv_headers.setEnabled(False) # TextEdit + PushButton (FindFolder) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # lbl sheet name self.lbl_file_path = QLabel(self.group_input_file) self.lbl_file_path.setGeometry(QtCore.QRect(250, 20, 120, 15)) self.lbl_file_path.setText(ui_strings.DATATOOLS_SELECT_FILE) self.txt_file = QLineEdit(self.group_input_file) self.txt_file.setGeometry(QtCore.QRect(250, 35, 160, 20)) self.txt_file.setReadOnly(True) self.btn_path = QPushButton(self.group_input_file) self.btn_path.setGeometry(QtCore.QRect(410, 34, 50, 22)) self.btn_path.setText(ui_strings.DATATOOLS_SELECT_BUTTON) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # lbl sheet name self.lbl_sheet_name = QLabel(self.group_input_file) self.lbl_sheet_name.setGeometry(QtCore.QRect(500, 20, 120, 15)) self.lbl_sheet_name.setText(ui_strings.DATATOOLS_SHEET_NAME) # Combobox select sheet - initially does not contain values self.cbo_sheet = QComboBox(self.group_input_file) self.cbo_sheet.setGeometry(QtCore.QRect(500, 35, 130, 20)) # data grid to visualize error messages self.tbl_errors = QTableWidget(self.central_widget) self.tbl_errors.setGeometry( QtCore.QRect(self._left_margin, 420, 660, 100)) # data grid to visualize those records with errors. self.tbl_uploaded_data = QTableWidget(self.central_widget) self.tbl_uploaded_data.setGeometry( QtCore.QRect(self._left_margin, 120, 500, 220)) # group run options self.group_run_options = QGroupBox(self.central_widget) self.group_run_options.setGeometry(QtCore.QRect(520, 120, 150, 220)) self.group_run_options.setTitle(ui_strings.DATATOOLS_GROUP_RUN) # Errors summary: # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # group summary errors self.group_errors = QGroupBox(self.central_widget) self.group_errors.setGeometry( QtCore.QRect(self._left_margin, 350, 660, 60)) self.group_errors.setTitle(ui_strings.DATATOOLS_HEADER_ERRORS) # lbl records self.lbl_records = QLabel(self.group_errors) self.lbl_records.setGeometry(QtCore.QRect(165, 15, 80, 15)) self.lbl_records.setAlignment(QtCore.Qt.AlignCenter) self.lbl_records.setText(ui_strings.DATATOOLS_RECORDS) self.txt_records = QLineEdit(self.group_errors) self.txt_records.setGeometry(QtCore.QRect(165, 30, 80, 20)) self.txt_records.setAlignment(QtCore.Qt.AlignCenter) self.txt_records.setReadOnly(True) # lbl errors self.lbl_errors = QLabel(self.group_errors) self.lbl_errors.setGeometry(QtCore.QRect(275, 15, 80, 15)) self.lbl_errors.setAlignment(QtCore.Qt.AlignCenter) self.lbl_errors.setText(ui_strings.DATATOOLS_ERRORS) self.txt_errors = QLineEdit(self.group_errors) self.txt_errors.setGeometry(QtCore.QRect(275, 30, 80, 20)) self.txt_errors.setAlignment(QtCore.Qt.AlignCenter) self.txt_errors.setReadOnly(True) # lbl time self.lbl_time = QLabel(self.group_errors) self.lbl_time.setGeometry(QtCore.QRect(385, 15, 80, 15)) self.lbl_time.setAlignment(QtCore.Qt.AlignCenter) self.lbl_time.setText(ui_strings.DATATOOLS_TIME) self.txt_time = QLineEdit(self.group_errors) self.txt_time.setGeometry(QtCore.QRect(385, 30, 80, 20)) self.txt_time.setAlignment(QtCore.Qt.AlignCenter) self.txt_time.setReadOnly(True) # history button self.btn_history = QToolButton(self.group_errors) self.btn_history.setGeometry(QtCore.QRect(500, 25, 100, 25)) icon_history = QIcon() icon_history.addPixmap(QPixmap(resources.ICON_HISTORY), QIcon.Normal, QIcon.Off) self.btn_history.setIcon(icon_history) self.btn_history.setIconSize(QtCore.QSize(20, 20)) self.btn_history.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon) self.btn_history.setText(ui_strings.DATATOOLS_HISTORY) self.btn_history.setCheckable(True) self.btn_history.setAutoExclusive(True) self.btn_history.setObjectName("history_button") # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # btn data uploader self.btn_data_uploader = QPushButton( ui_strings.DATATOOLS_DATA_UPLOADER, self.group_run_options) self.btn_data_uploader.setGeometry(QtCore.QRect(10, 120, 90, 25)) self.btn_data_uploader.setCheckable(True) self.btn_data_uploader.setAutoExclusive(True) self.btn_data_uploader.setFlat(False) # btn data testing self.btn_data_testing = QPushButton(ui_strings.DATATOOLS_DATA_TESTING, self.group_run_options) self.btn_data_testing.setEnabled(False) self.btn_data_testing.setGeometry(QtCore.QRect(10, 150, 90, 25)) self.btn_data_testing.setCheckable(True) self.btn_data_testing.setAutoExclusive(True) # btn data to database self.btn_data_db = QPushButton(ui_strings.DATATOOLS_DATA_DB, self.group_run_options) self.btn_data_db.setEnabled(False) self.btn_data_db.setGeometry(QtCore.QRect(10, 179, 91, 23)) self.btn_data_db.setCheckable(True) self.btn_data_db.setAutoExclusive(True) # frame run options self.frame_run = QFrame(self.group_run_options) self.frame_run.setGeometry(QtCore.QRect(10, 30, 130, 80)) self.frame_run.setFrameShape(QFrame.StyledPanel) self.frame_run.setFrameShadow(QFrame.Raised) # option process until first error self.rbtn_process_error = QRadioButton( ui_strings.DATATOOLS_PROCESS_ERROR, self.frame_run) self.rbtn_process_error.setGeometry(QtCore.QRect(0, 0, 150, 20)) # option process all data self.rbtn_process_all = QRadioButton(ui_strings.DATATOOLS_PROCESS_ALL, self.frame_run) self.rbtn_process_all.setGeometry(QtCore.QRect(0, 20, 150, 30)) # checkbox to filter by records with errors. #self.chk_filter_errors = QCheckBox(ui_strings.DATATOOLS_FILTER_ERRORS, self.frame_run) #self.chk_filter_errors.setGeometry(QtCore.QRect(0, 50, 100, 15)) #self.chk_filter_errors.setEnabled(False) # icons -> pass - error: Initially are empty labels # if not started -> ICON_MINI_WAIT # if error -> ICON_DELETE # if pass -> ICON_CHECK # state icon data uploader self.lbl_state_du = QLabel(self.group_run_options) self.lbl_state_du.setGeometry(QtCore.QRect(110, 120, 20, 20)) self.lbl_state_du.setPixmap(QPixmap(resources.ICON_MINI_WAIT)) self.lbl_state_du.setScaledContents(True) # state icon data to database self.lbl_state_dt = QLabel(self.group_run_options) self.lbl_state_dt.setGeometry(QtCore.QRect(110, 150, 20, 20)) self.lbl_state_dt.setPixmap(QPixmap(resources.ICON_MINI_WAIT)) self.lbl_state_dt.setScaledContents(True) # state icon data testing self.lbl_state_db = QLabel(self.group_run_options) self.lbl_state_db.setGeometry(QtCore.QRect(110, 180, 20, 20)) self.lbl_state_db.setPixmap(QPixmap(resources.ICON_MINI_WAIT)) self.lbl_state_db.setScaledContents(True) # progress bar self.progress_bar = QProgressBar(self.central_widget) self.progress_bar.setGeometry( QtCore.QRect(self._left_margin, 530, 660, 15)) self.progress_bar.setMaximum(100) self.progress_bar.setProperty("value", 0) self.progress_bar.setTextVisible(True) self.progress_bar.setOrientation(QtCore.Qt.Horizontal) self.progress_bar.setInvertedAppearance(False) self.progress_bar.setTextDirection(QProgressBar.TopToBottom) self.setCentralWidget(self.central_widget)
class MainWindow(QMainWindow): def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowMinimizeButtonHint) self.setWindowTitle(u"鱿鱼") self.setFixedSize(800, 600) self.setObjectName('principal') self.createGUI() def createGUI(self): self.frame_window = QWidget(self) self.frame_window.setGeometry(0, 0, 800, 40) self.frame_window.setObjectName('frame_window') self.title_frame = QLabel(self.frame_window) self.title_frame.setGeometry(0, 0, 800, 40) self.title_frame.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self.title_frame.setFont(QFont("微软雅黑", 20, QFont.Bold)) self.title_frame.setText(u" 鱿鱼-阿里云白名单设置") self.title_frame.setObjectName('title_frame') # buttons clsfont = self.font() or QFont() clsfont.setFamily('Webdings') self.button_close = QPushButton('r', self.frame_window, font=clsfont) self.button_close.setGeometry(760, 0, 40, 40) self.button_close.setObjectName('button_close') self.button_close.setToolTip(u'关闭') self.button_close.enterEvent( self.button_close.setCursor(Qt.PointingHandCursor)) self.button_min = QPushButton('0', self.frame_window, font=clsfont) self.button_min.setGeometry(720, 0, 40, 40) self.button_min.setObjectName('button_min') self.button_min.setToolTip(u'最小化') self.button_min.enterEvent( self.button_min.setCursor(Qt.PointingHandCursor)) ###左边选择栏部分 self.GroupBox_checkbox = QGroupBox(self) self.GroupBox_checkbox.setTitle(u'选择白名单组') self.GroupBox_checkbox.setGeometry(10, 50, 200, 540) self.ecs_test = QCheckBox(u'测试环境服务器', self.GroupBox_checkbox) self.ecs_test.enterEvent(self.ecs_test.setCursor( Qt.PointingHandCursor)) self.ecs_test.setChecked(True) self.ecs_test.setGeometry(20, 30, 150, 30) self.rds_mysql = QCheckBox(u'MySQL数据库', self.GroupBox_checkbox) self.rds_mysql.enterEvent( self.rds_mysql.setCursor(Qt.PointingHandCursor)) self.rds_mysql.setChecked(True) self.rds_mysql.setGeometry(20, 60, 150, 30) self.rds_sqlserver = QCheckBox(u'SQLServer数据库', self.GroupBox_checkbox) self.rds_sqlserver.enterEvent( self.rds_sqlserver.setCursor(Qt.PointingHandCursor)) self.rds_sqlserver.setChecked(True) self.rds_sqlserver.setGeometry(20, 90, 150, 30) ###右边IP设置部分 self.GroupBox_ipset = QGroupBox(self) self.GroupBox_ipset.setTitle(u'公网IP配置') self.GroupBox_ipset.setGeometry(220, 50, 570, 200) self.label_outip = QLabel(self.GroupBox_ipset, objectName="label_outip") self.label_outip.setText(u'公网IP:') self.label_outip.setGeometry(15, 30, 75, 30) self.line_outip = QLineEdit(self.GroupBox_ipset) self.line_outip.setMinimumWidth(200) self.line_outip.setGeometry(85, 30, 150, 30) self.line_outip.setFont(QFont("Timers", 13, QFont.Bold)) self.line_outip.setStyleSheet("color:green") self.button_getip = QPushButton(u'自动获取公网IP', self.GroupBox_ipset, objectName="button_getip") self.button_getip.setToolTip(u'从ip138上抓取本机公网IP') self.button_getip.enterEvent( self.button_getip.setCursor(Qt.PointingHandCursor)) self.button_getip.setGeometry(300, 30, 110, 30) self.button_setup = QPushButton(u'添加', self.GroupBox_ipset, objectName="button_setup") self.button_setup.enterEvent( self.button_setup.setCursor(Qt.PointingHandCursor)) self.button_setup.setToolTip(u'将该IP添加至已选白名单组中') self.button_setup.setGeometry(430, 30, 110, 30) ###右边消息输出部分 self.GroupBox_text = QGroupBox(self) self.GroupBox_text.setGeometry(220, 260, 570, 330) self.browser_text = QTextBrowser(self.GroupBox_text) self.browser_text.setGeometry(0, 0, 570, 330) self.browser_text.setFont(QFont("Roman times", 12)) self.browser_text.setObjectName('browser_text') # conexiones self.button_close.clicked.connect(self.close) self.button_min.clicked.connect(self.showMinimized) self.button_getip.clicked.connect(self.auto_ip) self.button_setup.clicked.connect(self.setup) def auto_ip(self): self.line_outip.clear() self.button_getip.setEnabled(False) self.th_get_ip = GETIP() self.th_get_ip.ip_line_Signal.connect(self.show_ip_info) self.th_get_ip.start() def show_ip_info(self, ip=None, status=1): self.button_getip.setEnabled(True) if status: self.line_outip.setText(ip) else: self.browser_text.append(ip) def setup(self): myip = self.line_outip.text() if myip and validate_ip(myip): check_list = [] if self.ecs_test.isChecked(): check_list.append('ecs_test') if self.rds_mysql.isChecked(): check_list.append('rds_mysql') if self.rds_sqlserver.isChecked(): check_list.append('rds_sqlserver') if len(check_list) == 0: self.browser_text.append(u'没什么事可做的~') else: self.button_setup.setEnabled(False) self.th_setup = SETIP(myip, check_list) self.th_setup.text_browser_Signal.connect(self.show_text) self.th_setup.start() else: self.browser_text.append(u'请填入正确的IP地址!') def show_text(self, text=None, end=0): if end: self.button_setup.setEnabled(True) if text: self.browser_text.append(text) def mousePressEvent(self, event): self.offset = event.pos() def mouseMoveEvent(self, event): x = event.globalX() y = event.globalY() x_w = self.offset.x() y_w = self.offset.y() self.move(x - x_w, y - y_w)