def get_dirnames(app=None): from PySide2.QtCore import Qt, QCoreApplication from PySide2.QtWidgets import QApplication, QFileDialog, QTreeView, QListView, QAbstractItemView from pathlib import Path if not app: app = QApplication(sys.argv) # file_dialog = QFileDialog() # file_dialog.setWindowFlags(Qt.WindowStaysOnTopHint) # file_location = file_dialog.getOpenFileNames() file_dialog = QFileDialog() file_dialog.setFileMode(QFileDialog.DirectoryOnly) file_dialog.setOption(QFileDialog.DontUseNativeDialog, True) file_view = file_dialog.findChild(QListView, 'listView') # to make it possible to select multiple directories: if file_view: file_view.setSelectionMode(QAbstractItemView.MultiSelection) f_tree_view = file_dialog.findChild(QTreeView) if f_tree_view: f_tree_view.setSelectionMode(QAbstractItemView.MultiSelection) if file_dialog.exec(): paths = file_dialog.selectedFiles() QCoreApplication.processEvents() for path in paths: yield Path(path)
def _on_import_button_click(self): import_dialog = QFileDialog(self, 'Import icon') import_dialog.setFileMode(QFileDialog.ExistingFile) import_dialog.setNameFilter('Images (*.png *.jpg)') if import_dialog.exec(): if len(import_dialog.selectedFiles()) == 0: self._import_file_name = import_dialog.selectedFiles()[0]
def saveTemplate(self): dialog = QFileDialog(self, "Save File", "", "Templates (*.ez)") dialog.setDefaultSuffix(".ez") dialog.setAcceptMode(QFileDialog.AcceptSave) fileName = "" if dialog.exec(): fileName = dialog.selectedFiles()[0] if fileName != "": with open(fileName, 'w') as outfile: json.dump(self.filterModel.displayed, outfile) outfile.write("\n") json.dump(self.filterModel.fileType, outfile) outfile.write("\n") self.createtablemodel.editableList = [] for i in range(len(self.createtablemodel.metadataList)): if self.createtablemodel.metadataList[i][ "Editable"] == 2 and ( self.createtablemodel.metadataList[i] ["Checked"] == 2 or self.createtablemodel. metadataList[i]["Checked"] == 1): self.createtablemodel.editableList.append( self.createtablemodel.metadataList[i]["Key"]) json.dump(self.createtablemodel.editableList, outfile) outfile.write("\n") json.dump(self.createtablemodel.metadataList, outfile) outfile.write("\n") json.dump(self.treeModel.treeDict, outfile)
def open_dir(self): """ show open dir dialog and open repo """ last_dir = self.settings.value('last_fileopen_dir', '') fd = QFileDialog(self, 'Open .git', last_dir) fd.setFileMode(QFileDialog.DirectoryOnly) fd.setFilter( QDir.Filters(QDir.Dirs | QDir.Hidden | QDir.NoDot | QDir.NoDotDot)) while True: if not fd.exec(): return self.dir_name = fd.selectedFiles()[0] parent = os.path.dirname(self.dir_name) self.settings.setValue('last_fileopen_dir', parent) self.settings.setValue('last_opened_repo', self.dir_name) try: pygit2.Repository(self.dir_name) break except pygit2.GitError: QMessageBox(self, text='Cannot open repo: ' + self.dir_name).exec() self.open_repo()
def set_label_dir(self): dialog = QFileDialog(self, 'Select Label Directory') dialog.setFileMode(QFileDialog.Directory) dialog.setNameFilters(["Any Files (*)"]) dialog.setViewMode(QFileDialog.List) if dialog.exec(): selected_dir = dialog.selectedFiles()[0] if not os.path.isdir(selected_dir): selected_dir = os.path.dirname(selected_dir) self.active_label_dir = selected_dir self.current_label_dir.setText(self.active_label_dir) with open(self.meta_file, 'a+') as f: f.write('Set Label Dir: ' + self.active_label_dir + '\n') self.label_dir = ensure_dir( os.path.join( self.active_label_dir, self.label_options.currentText().replace(' ', '_'))) if self.active_image_dir is not None: image_name = os.path.basename(self.src_paths[self.current_idx]) image_name, suff = os.path.splitext(image_name) self.current_label_path = os.path.join( self.label_dir, image_name + '_label.png') if os.path.exists(self.current_label_path): self.viewer.setSegLayer(QPixmap(self.current_label_path)) else: self.viewer.resetSegLayer() self.viewer.changed = False
def set_image_dir(self): dialog = QFileDialog(self, 'Select Image Directory') dialog.setFileMode(QFileDialog.Directory) dialog.setNameFilters(["Any Files (*)"]) dialog.setViewMode(QFileDialog.List) if dialog.exec(): selected_dir = dialog.selectedFiles()[0] if not os.path.isdir(selected_dir): selected_dir = os.path.dirname(selected_dir) self.active_image_dir = selected_dir with open(self.meta_file, 'a+') as f: f.write('Set Image Dir: ' + self.active_image_dir + '\n') if self.active_label_dir is None: self.active_label_dir = self.active_image_dir self.current_label_dir.setText(self.active_label_dir) with open(self.meta_file, 'a+') as f: f.write('Set Label Dir: ' + self.active_label_dir + '\n') self.label_dir = ensure_dir( os.path.join( self.active_label_dir, self.label_options.currentText().replace(' ', '_'))) # image_paths = glob.glob(os.path.join(self.active_image_dir, '*.png')) + glob.glob(os.path.join(self.active_image_dir, '*.jpg')) paths = glob.glob(os.path.join(self.active_image_dir, '*')) image_paths = [] for path in paths: if os.path.isdir(path): continue if imghdr.what(path) in ['jpeg', 'png', 'jpg']: image_paths.append(path) self.src_paths = sorted(image_paths) self.current_dir.setText(self.active_image_dir) self.image_idx.setRange(1, len(self.src_paths)) self.goto_image(1)
def on_import(self): # TODO: if changes are present, ask if it's okay to override dialog = QFileDialog(self.tool) dialog.selectFile(config.config_path) dialog.setAcceptMode(QFileDialog.AcceptOpen) dialog.setFileMode(QFileDialog.ExistingFile) path = dialog.exec()
def get_nifti_file(self): filter = "NiFti (*.nii)" dialog = QFileDialog() dialog.setFileMode(QFileDialog.ExistingFiles) dialog.setNameFilter(filter) if dialog.exec(): files = dialog.selectedFiles()[0] return files return ''
def openFileWithDialog(self): self.logger.debug("Opening file dialog...") dialog = QFileDialog(self) dialog.setFileMode(QFileDialog.AnyFile) dialog.setViewMode(QFileDialog.Detail) if dialog.exec(): for file in dialog.selectedFiles(): self.openFile(file)
def open_dcm(self): filter = "DICOM (*.dcm)" dialog = QFileDialog(self) dialog.setFileMode(QFileDialog.ExistingFiles) dialog.setNameFilter(filter) if dialog.exec(): files = dialog.selectedFiles() try: self.main_widget.send_file_to_browser(files) finally: return
class FileLoaderGroup(QGroupBox): def __init__( self, title: str, parent: "QWidget" = None, filter: str = "", pick_directories: bool = False, ): super().__init__(title, parent) self._file_picker_dialog = QFileDialog( caption=f'Picking a "{title}" file...', filter=filter ) self._file_picker_dialog.setFileMode( QFileDialog.DirectoryOnly if pick_directories else QFileDialog.ExistingFile ) self._pick_file_text = QLineEdit() self._pick_file_text.setReadOnly(True) self._pick_file_text.setPlaceholderText("Path...") self._pick_file_button = QPushButton("Load") self._pick_file_layout = QHBoxLayout() self._pick_file_layout.addWidget(self._pick_file_text) self._pick_file_layout.addWidget(self._pick_file_button) self._main_layout = QVBoxLayout() self._main_layout.addLayout(self._pick_file_layout) self.setLayout(self._main_layout) self._pick_file_button.clicked.connect(self._load_from_filesystem) @property def layout(self) -> "QVBoxLayout": return self._main_layout @property def path(self) -> str: return self._pick_file_text.text() @path.setter def path(self, path: str): self._pick_file_text.setText(path) def _load_from_filesystem(self): LOGGER.debug("Picking file...") if self._file_picker_dialog.exec(): self._pick_file_text.setText(self._file_picker_dialog.selectedFiles()[0])
def on_action_save_config_dir_triggered(self): dialog = QFileDialog(self.ui, 'Save Configuration', HexrdConfig().working_dir, 'HEXRD directories (*)') dialog.setFileMode(QFileDialog.Directory) dialog.setAcceptMode(QFileDialog.AcceptSave) # We connect up the curentChanged signal, so we can save a listing # before the QFileDialog creates a directory, so we can determine if # the directory already existed, see below. listing = [] def _current_changed(p): nonlocal listing listing = [str(p) for p in Path(p).parent.iterdir()] dialog.currentChanged.connect(_current_changed) selected_files = [] if dialog.exec(): selected_files = dialog.selectedFiles() if len(selected_files) == 0: return else: selected_file = selected_files[0] # The QFileDialog will create the directory for us. However, if # the user didn't us a .hexrd suffix we need to add it, but only if is # didn't exist before. This is hack to get around the fact that we # can't easily stop QFileDialog from creating the directory. if Path(selected_file).suffix != '.hexrd': # if it wasn't in the listing before the QFileDialog, we can # be pretty confident that is was create by the QFileDialog. if selected_file not in listing: selected_file = Path(selected_file).rename( f'{selected_file}.hexrd') # else just added the suffix else: selected_file = Path(selected_file).with_suffix('.hexrd') if selected_file: path = Path(selected_file) HexrdConfig().working_dir = str(path.parent) path.mkdir(parents=True, exist_ok=True) path = path / 'config.yml' return HexrdConfig().save_instrument_config(str(path))
def save_text(self): frmat = '.txt' initial_path = QStandardPaths.writableLocation( QStandardPaths.DocumentsLocation) if not initial_path: initial_path = QDir.currentPath() initial_path += '/Screenshot_Text-' + \ str(datetime.now()).replace(' ', '_') + frmat file_dialog = QFileDialog(self, "Save as", initial_path) file_dialog.setAcceptMode(QFileDialog.AcceptSave) file_dialog.setFileMode(QFileDialog.AnyFile) if file_dialog.exec() != QDialog.Accepted: return file_name = file_dialog.selectedFiles()[0] with open(file_name, 'w') as wf: wf.write(self.text_edit.toPlainText())
def file_dialog(self): filedialog = QFileDialog(caption='Select Data File') filedialog.setFileMode(QFileDialog.ExistingFile) if filedialog.exec(): self.file = filedialog.selectedFiles()[0] self.filename.setText(self.file) lines = [] with open(self.file) as fd: for _ in range(10): lines.append(fd.readline()) self.preview.setText(''.join(lines)) reader = DataFrameReader(self.file) self.tablemodel.set_df(reader.df) self.tablemodel.set_columns(self.columnsbox.columns) self.tableview.resizeRowsToContents() self.update_ok()
def getMultipleSelected(self, init_text): file_dialog = QFileDialog() file_dialog.setFileMode(QFileDialog.DirectoryOnly) file_dialog.setOption(QFileDialog.DontUseNativeDialog, True) file_view = file_dialog.findChild(QListView, 'listView') # to make it possible to select multiple directories: if file_view: file_view.setSelectionMode(QAbstractItemView.ExtendedSelection) f_tree_view = file_dialog.findChild(QTreeView) if f_tree_view: f_tree_view.setSelectionMode(QAbstractItemView.ExtendedSelection) if file_dialog.exec(): self.source = file_dialog.selectedFiles() eval("self." + init_text + "FilePath").setText(",".join( self.source)) print(self.source)
def save_screenshot(self): frmat = '.png' initial_path = QStandardPaths.writableLocation( QStandardPaths.PicturesLocation) if not initial_path: initial_path = QDir.currentPath() initial_path += '/Screenshot-' + \ str(datetime.now()).replace(' ', '_') + frmat file_dialog = QFileDialog(self, "Save as", initial_path) file_dialog.setAcceptMode(QFileDialog.AcceptSave) file_dialog.setFileMode(QFileDialog.AnyFile) if file_dialog.exec() != QDialog.Accepted: return file_name = file_dialog.selectedFiles()[0] if not self.original_pixmap.save(file_name): logger.error("The image could not be saved to \"{}\".".format( QDir.toNativeSeparators(file_name))) QMessageBox.warning(self, "Save Error", "The image could not be saved to \"{}\".".format( QDir.toNativeSeparators(file_name)))
def open_folder(self, path=None): self.current_index = 0 self.path = path if path is None: dialog = QFileDialog(self) dialog.setAcceptMode(QFileDialog.AcceptOpen) dialog.setFileMode(QFileDialog.DirectoryOnly) if dialog.exec(): self.path = dialog.selectedFiles()[0] if not self.path: return list_ = os.listdir(self.path) list_ = sorted(list_) self.file_list = OrderedDict() for item in list_: if item.split(".")[-1] in QImageReader.supportedImageFormats(): self.file_list[item] = False self.show_image(self.current_index)
def select_new_folder(): dialog = QFileDialog(self) dialog.setAcceptMode(QFileDialog.AcceptSave) dialog.setFileMode(QFileDialog.DirectoryOnly) if dialog.exec(): return dialog.selectedFiles()[0]
def openMenu(position): # Создание PopupMenu menu = QMenu() if mode > 0: addAction = menu.addAction('Добавить фото') addAction2 = menu.addAction('Добавить видео') menu.addSeparator() nextAction = menu.addAction('Следующий') #editAction = menu.addAction('Переименовать событие') menu.addSeparator() delAction = menu.addAction('Удалить фото') delAllAction = menu.addAction('Удалить все фото') menu.addSeparator() else: addAction, addAction2, delAction, delAllAction = QAction(), QAction(), QAction(), QAction() quitAction = menu.addAction('Выход') action = menu.exec_(self.mapToGlobal(position)) # Привязка событий к Actions if action == addAction: res = [] dialog = QFileDialog() dialog.setFileMode(QFileDialog.ExistingFiles) img_filter = 'Изображения (*.png *.bmp *.jpg);' dialog.setNameFilter(img_filter) fileNames = [] if (dialog.exec()): fileNames = dialog.selectedFiles() if len(fileNames) > 0: last_len = len(self.photo_ids) if type(self.photo_ids) == type([]) else 0 for i, f in enumerate(fileNames): if os.path.isfile(f): data = self.db.add_album({'alid': self.alid, 'oldpath': f}) if data: self.changed = True if self.photo_ids: self.photo_ids.append( data[0]['imid'] ) else: self.photo_ids = [ data[0]['imid'] ] print(self.photo_ids) if self.photo_ids and type(self.photo_ids) == type([]) and len(self.photo_ids) > 0: if last_len < len(self.photo_ids): self.curindex = last_len else: self.curindex = 0 self.setPhoto() if action == addAction2: res = [] dialog = QFileDialog() dialog.setFileMode(QFileDialog.ExistingFiles) img_filter = 'Видео (*.mp4 *.avi *.3gp *.mpeg *.mpg);' dialog.setNameFilter(img_filter) fileNames = [] if (dialog.exec()): fileNames = dialog.selectedFiles() if len(fileNames) > 0: #print(fileNames) last_len = len(self.photo_ids) if type(self.photo_ids) == type([]) else 0 for i, f in enumerate(fileNames): if os.path.isfile(f): data = self.db.add_album({'alid': self.alid, 'oldpath': f, 'video': True}) if data: self.changed = True if self.photo_ids: self.photo_ids.append( data[0]['imid'] ) else: self.photo_ids = [ data[0]['imid'] ] print(self.photo_ids) if self.photo_ids and type(self.photo_ids) == type([]) and len(self.photo_ids) > 0: if last_len < len(self.photo_ids): self.curindex = last_len else: self.curindex = 0 self.setPhoto() if action == nextAction: self.setFocus() self.next_show() if action == delAction: eid = self.listWidget.currentItem() if eid is not None: eid = self.listWidget.currentItem().whatsThis() self.db.del_event({'alid':self.alid, 'eid': eid}) self.listWidget.takeItem(self.listWidget.currentRow()) self.db.events.save() self.changed = True self.event_ids = db.get_all_event_ids(self.alid) if action == delAllAction: self.setPixmap(QPixmap( os.path.join( 'images', 'no-photo.jpg') ).scaled(image_squre_length, image_squre_length, Qt.KeepAspectRatio)) self.db.edit_event({'alid':self.alid, 'eid': self.eid, 'photo_ids': 0}) self.db.events.save() self.changed = True self.photo_ids = self.get_photo_ids() if action == quitAction: self.accept()
def openMenu(position): # Создание PopupMenu menu = QMenu() if mode > 0: addAction = menu.addAction('Добавить фото') addAction2 = menu.addAction('Добавить видео') #menu.addSeparator() nextAction = menu.addAction('Следующий') #menu.addSeparator() delAction = menu.addAction('Удалить фото') delAllAction = menu.addAction('Удалить все фото') menu.addSeparator() else: addAction, addAction2, delAction, delAllAction = QAction(), QAction(), QAction(), QAction() quitAction = menu.addAction('Выход') action = menu.exec_(self.mapToGlobal(position)) # Привязка событий к Actions if action == addAction: res = [] dialog = QFileDialog() dialog.setFileMode(QFileDialog.ExistingFiles) img_filter = 'Изображения (*.png *.bmp *.jpg);' dialog.setNameFilter(img_filter) fileNames = [] if (dialog.exec()): fileNames = dialog.selectedFiles() if len(fileNames) > 0: #print(fileNames) last_len = len(self.photo_ids) if type(self.photo_ids) == type([]) else 0 for i, f in enumerate(fileNames): if os.path.isfile(f): data = self.db.add_album({'alid': self.alid, 'oldpath': f}) if data: if self.photo_ids: self.photo_ids.append( data[0]['imid'] ) else: self.photo_ids = [ data[0]['imid'] ] print(self.photo_ids) if self.photo_ids and type(self.photo_ids) == type([]) and len(self.photo_ids) > 0: if last_len < len(self.photo_ids): self.curindex = last_len else: self.curindex = 0 self.setPhoto() if action == addAction2: res = [] dialog = QFileDialog() dialog.setFileMode(QFileDialog.ExistingFiles) img_filter = 'Видео (*.mp4 *.avi *.3gp *.mpeg *.mpg);' dialog.setNameFilter(img_filter) fileNames = [] if (dialog.exec()): fileNames = dialog.selectedFiles() if len(fileNames) > 0: #print(fileNames) last_len = len(self.photo_ids) if type(self.photo_ids) == type([]) else 0 for i, f in enumerate(fileNames): if os.path.isfile(f): data = self.db.add_album({'alid': self.alid, 'oldpath': f, 'video': True}) if data: if self.photo_ids: self.photo_ids.append( data[0]['imid'] ) else: self.photo_ids = [ data[0]['imid'] ] print(self.photo_ids) if self.photo_ids and type(self.photo_ids) == type([]) and len(self.photo_ids) > 0: if last_len < len(self.photo_ids): self.curindex = last_len else: self.curindex = 0 self.setPhoto() if action == nextAction: self.setFocus() self.next_show() if action == delAction: if self.photo_ids and type(self.photo_ids) == type([]) and len(self.photo_ids) > 0: self.db.del_photo_from_album({'alid': self.alid, 'imid': self.photo_ids[self.curindex]}) self.photo_ids = db.get_all_albums_photos(self.alid) if self.photo_ids and type(self.photo_ids) == type([]) and len(self.photo_ids) > 0: if self.curindex >= len(self.photo_ids): self.curindex = len(self.photo_ids) - 1 self.setPhoto() else: self.viewWidget.setPixmap(QPixmap( os.path.join( 'images', 'no-photo.jpg') ).scaled(400, 400, Qt.KeepAspectRatio)) else: self.viewWidget.setPixmap(QPixmap( os.path.join( 'images', 'no-photo.jpg') ).scaled(400, 400, Qt.KeepAspectRatio)) if action == delAllAction: for imid in self.photo_ids: self.db.del_photo_from_album({'alid': self.alid, 'imid': imid}) self.viewWidget.setPixmap(QPixmap( os.path.join( 'images', 'no-photo.jpg') ).scaled(400, 400, Qt.KeepAspectRatio)) self.photo_ids = db.get_all_albums_photos(self.alid) if action == quitAction: self.accept()
class MyWidget(QWidget): MAX_SHOWN_LINES = 10 PROCESS_NUMBER = 2 STOP_THREADS = False # Files APP_DIR = 'app' HTML = '.html' XML = '.xml' TXT = '.txt' EXTENSIONS = [TXT, XML, HTML] def __init__(self): QWidget.__init__(self) # Configuration from CLI interface self.file_names = [] self.disable_logging = False self.result_filter = None self.filters = [] self.configuration = [] # Internal subprocess attributes # Shared queues, first for steps and second for processes self.queues = None self.worker = None self.processes = [] self.thread = None self.show_steps_thread = None self.web_views = [] # Create Menu bar self.setWindowTitle("Sec&Po testing framework") self.main_menu = QMenuBar() self.file_menu = self.main_menu.addMenu("File") self.configure_menu = self.main_menu.addMenu("Configure") # Set actions file_actions = self.create_file_actions() for action in file_actions: self.file_menu.addAction(action) manage_actions = self.create_management_actions() for action in manage_actions: self.configure_menu.addAction(action) # Create main window self.selected_files = QLabel( "Here will be printed some of the selected files") self.finish_button = QPushButton("&Run security and" " portability testing") # Connecting the signal self.finish_button.clicked.connect(self.run_testing) self.results_label = QLabel("No results") self.show_results_button = QPushButton("&Show results") self.show_results_button.clicked.connect(self.load_html_result) # Create file dialog self.file_dialog = QFileDialog(self) # fixme: debug for pycharm # self.file_dialog.setOption(QFileDialog.DontUseNativeDialog, True) self.file_dialog.setFileMode(QFileDialog.ExistingFiles) file_filters = ["All files files (*)"] for value in ProgramTypes: file_filters.append(value.name + " files (") for program_filters in next(iter(value.value.values())): file_filters[len(file_filters) - 1] += "*" + program_filters\ + " " file_filters[len(file_filters) - 1] += ")" self.file_dialog.setNameFilters(file_filters) self.file_dialog.setViewMode(QFileDialog.Detail) # Add proxy model to change default behaviour or file selector # todo: does not work with files only directories. # However selecting of both must be overridden with own QFileDialog # proxy = ProxyModel(self.file_dialog) # self.file_dialog.setProxyModel(proxy) # Set layout of elements self._set_layout() def _set_layout(self): self.layout = QFormLayout() self.layout.setFormAlignment(Qt.AlignHCenter | Qt.AlignTop) self.layout.setFieldGrowthPolicy(QFormLayout.FieldsStayAtSizeHint) self.layout.setVerticalSpacing(150) self.layout.setHorizontalSpacing(220) self.layout.setLabelAlignment(Qt.AlignRight) self.layout.addRow(self.main_menu) self.finish_button.setFixedSize(250, 65) self.layout.addRow(self.selected_files, self.finish_button) self.show_results_button.setFixedSize(250, 65) self.layout.addRow(self.results_label, self.show_results_button) self.setLayout(self.layout) def create_file_actions(self): openAct = QAction(QIcon("images/folder.png"), self.tr("&Open..."), self) openAct.setShortcuts(QKeySequence.Open) openAct.setStatusTip( self.tr("Open an existing file, " "files or directories")) openAct.triggered.connect(self.open) addFilter = QAction(QIcon("images/filter.png"), self.tr("&Add filter"), self) # addFilter.setShortcuts() addFilter.setStatusTip( self.tr("Select filter files to apply " " result filtering")) addFilter.triggered.connect(self.add_filter) return [openAct, addFilter] def create_management_actions(self): manageAct = QAction(QIcon("images/settings.png"), self.tr("&Manage filters"), self) # manageAct.setShortcuts(QKeySequence.Open) manageAct.setStatusTip(self.tr("Manage added filters")) manageAct.triggered.connect(self.manage_filters) docker_conf_action = QAction(QIcon("images/docker.png"), self.tr("&Docker"), self) # docker_conf_action.setShortcuts() docker_conf_action.setStatusTip(self.tr("Docker")) docker_conf_action.triggered.connect(self.docker_conf) apparmor_conf_action = QAction(QIcon("images/apparmor.png"), self.tr("&Apparmor"), self) # apparmor_conf_action.setShortcuts() apparmor_conf_action.setStatusTip(self.tr("Apparmor")) apparmor_conf_action.triggered.connect(self.apparmor_conf) seccomp_conf_action = QAction(QIcon("images/lock.png"), self.tr("&Seccomp"), self) # docker_conf_action.setShortcuts() seccomp_conf_action.setStatusTip(self.tr("Seccomp")) seccomp_conf_action.triggered.connect(self.seccomp_conf) return [ manageAct, docker_conf_action, apparmor_conf_action, seccomp_conf_action ] def add_filter(self): pass def manage_filters(self): output = subprocess.check_output(['secpo', '--list-filters']) dialog = QDialog(self) label = QLabel("Managed filters are: {}".format( output.decode('utf-8'))) # dialog.set widgets = QWidget() layout = QHBoxLayout() layout.addWidget(dialog) layout.addWidget(label) widgets.setLayout(layout) widgets.show() dialog.exec() pass def docker_conf(self): pass def apparmor_conf(self): pass def seccomp_conf(self): pass def check_result_dir(self, file_name): result_dir = file_name.parent / self.APP_DIR if result_dir.exists(): self.results_label.setText("Results present") def open(self): output = 'No files chosen!' self.file_names = [] cnt = 0 # fixme: running code from pycharm causes to not use # regular path system but symlinks # https://stackoverflow.com/questions/57646908/pyqt5-qfiledialog-is-not-returning-correct-paths-in-ubuntu if self.file_dialog.exec(): self.file_names = self.file_dialog.selectedFiles() if self.file_names: output = '' for file_name in self.file_names: if cnt < self.MAX_SHOWN_LINES and file_name: # Correct the path absolute_path = pathlib.Path(file_name) self.check_result_dir(absolute_path) output += str(pathlib.Path(absolute_path.parts [len(absolute_path.parts) - 2])\ / pathlib.Path(absolute_path.name)) + '\n' cnt += 1 self.selected_files.setText(output + "\n") def open_single_result_view(self, result_file): if isinstance(self.web_views[-1], QWebEngineView): self.web_views[-1].load(QUrl(result_file.as_uri())) self.web_views[-1].showMaximized() elif isinstance(self.web_views[-1], QTextBrowser): text_doc = QTextDocument() self.web_views[-1].setDocument(text_doc) self.web_views[-1].setSource( QUrl(result_file.as_uri(), QUrl.ParsingMode.TolerantMode)) self.web_views[-1].show() def load_html_result(self): for file in self.file_names: root_dir = pathlib.Path(file).parent root_dir /= self.APP_DIR if root_dir.exists(): for extension in self.EXTENSIONS: result_files = root_dir.glob('**/*' + extension) for result_file in result_files: if extension == self.HTML or extension == self.XML: self.web_views.append(QWebEngineView()) elif extension == self.TXT: self.web_views.append(QTextBrowser()) self.open_single_result_view(result_file) def show_steps(self, progress): while True: time.sleep(0.5) if not self.queues[0].empty(): steps = self.queues[0].get() progress.setValue(steps.value) if steps.value == len(self.file_names) * 2: self.thread.quit() self.check_result_dir(pathlib.Path(self.file_names[0])) break if self.STOP_THREADS: break def remove_processes(self): self.processes = [] def cancel(self): for process in self.processes: self.queues[1].put(process.pid) time.sleep(5) # Set stop threads to true to indicate end of program self.STOP_THREADS = True if self.thread: self.thread.quit() self.processes = [] def run_testing(self): if not self.file_names: self.selected_files.setText( "No files were selected. Go to menu and " "select files to test.") return # Create new queues every run self.queues = [ multiprocessing.Queue(maxsize=self.PROCESS_NUMBER), multiprocessing.Queue(maxsize=self.PROCESS_NUMBER) ] self.STOP_THREADS = False progress = QProgressDialog("Starting Docker and VMs", "Abort start", 0, len(self.file_names) * 2, self) progress.canceled.connect(self.cancel) progress.setWindowModality(Qt.WindowModal) # Create Qthread to show progress self.thread = QThread() self.worker = Worker(self, self.file_names, self.queues) self.worker.moveToThread(self.thread) # Custom signals connected to own functions for progress dialog self.show_steps_thread = threading.Thread(target=self.show_steps, args=(progress, )) self.show_steps_thread.start() # Thread start and stop signals connected with slots self.thread.started.connect(self.worker.run) self.thread.finished.connect(self.remove_processes) # Start thread and force to show progress dialog self.thread.start() progress.forceShow() def closeEvent(self, event: PySide2.QtGui.QCloseEvent): event.ignore() super(MyWidget, self).closeEvent(event) # Indicate end of program if self.thread: self.thread.quit() self.thread.wait() for process in self.processes: if process: if os.name == 'nt': process.send_signal(signal.CTRL_C_EVENT) else: process.send_signal(signal.SIGINT)