示例#1
0
    def findFiles(self, files, text):
        progressDialog = QProgressDialog(self)

        progressDialog.setCancelButtonText("&Cancel")
        progressDialog.setRange(0, files.count())
        progressDialog.setWindowTitle("Find Files")

        foundFiles = []

        for i in range(files.count()):
            progressDialog.setValue(i)
            progressDialog.setLabelText("Searching file number %d of %d..." %
                                        (i, files.count()))
            QApplication.processEvents()

            if progressDialog.wasCanceled():
                break

            inFile = QFile(self.currentDir.absoluteFilePath(files[i]))

            if inFile.open(QIODevice.ReadOnly):
                stream = QTextStream(inFile)
                while not stream.atEnd():
                    if progressDialog.wasCanceled():
                        break
                    line = stream.readLine()
                    if text in line:
                        foundFiles.append(files[i])
                        break

        progressDialog.close()

        return foundFiles
示例#2
0
    def buttonclicked_run_allocation(self):
        attempts = self.ctx.app_data.settings['nattempts']
        progress_bar = QProgressDialog("Generating table allocations...", "",
                                       0, attempts, self.ctx.window)
        progress_bar.setWindowTitle("Generating...")
        progress_bar.setWindowModality(Qt.WindowModal)
        progress_bar.setAutoClose(False)
        progress_bar.setMinimumDuration(0)
        progress_bar.setCancelButton(None)

        progress_bar.show()
        progress_bar.setValue(0)

        try:
            self.ctx.ta_manager.run(progress_bar)
        except Exception as e:
            progress_bar.close()
            QMessageBox.critical(
                self, "Error",
                "An error occured during allocation: {}".format(str(e)))
            return

        progress_bar.close()
        QMessageBox.information(
            self, "Success!",
            "The allocations were successfully computed. Average number of links is {:.2f} ({:.2f} % of max)."
            .format(self.ctx.ta_manager.links,
                    100 * self.ctx.ta_manager.links_rel))

        self.ctx.set_unsaved()
        self.ctx.window.tabs.results_updated()
        self.ctx.window.results_menu.setEnabled(True)
示例#3
0
文件: main.py 项目: PetrovKP/courses
class ProgressDialog(QThread):
    MAXPROGRESS = 100
    sendSep = pyqtSignal(int)

    def __init__(self):
        super().__init__()
        self.progress = QProgressDialog("Идёт выполнение фильтра...", "Отмена",
                                        0, self.MAXPROGRESS, None)
        self.progress.setWindowTitle("Обновление")
        self.progress.setWindowModality(Qt.WindowModal)
        self.progress.setValue(0)
        self.progress.setFixedSize(QSize(300, 150))
        self.progress.show()

        self.running = True

    def cancel(self):
        self.running = False
        self.progress.close()
        self.quit()

    def updateProgress(self, val):
        self.progress.setValue(val)
        if self.progress.wasCanceled() or val == self.MAXPROGRESS:
            self.cancel()

    def run(self):
        self.exec_()
示例#4
0
 def download_all_shapefiles(self):
     progress_bar = QProgressDialog()
     for layer in self.data_layers:
         self.download_shapefile(layer,
                                 force=False,
                                 progress_bar=progress_bar)
     progress_bar.close()
示例#5
0
    def load_hdf5_files(self, filenames):
        n_files = len(filenames)

        for f in filenames:
            if not h5py.is_hdf5(f):
                raise TypeError(f'{f} is not a valid HDF5 file.')

        loop = QEventLoop()

        progress = QProgressDialog("Loading location tables", None, 0, n_files,
                                   self._parent)
        plural = 'files' if n_files > 1 else 'file'
        progress.setWindowTitle(f"Loading {n_files} location table {plural}")
        progress.setModal(True)
        progress.setMinimumDuration(0)
        progress.setValue(0)
        progress.show()

        loop.processEvents()

        for i, filename in enumerate(filenames):
            status_message = f'loading {filename}'
            progress.setLabelText(status_message)
            progress.setValue(i)
            loop.processEvents()

            self.load_hdf5(filename)

            progress.setValue(i + 1)
            loop.processEvents()

        progress.close()
示例#6
0
    def show_progress_bar(self):
        percent = 0
        is_exits = False
        self.result = None
        progressDialog = QProgressDialog(self.files_list_dialog)
        progressDialog.setAutoReset(True)
        progressDialog.setWindowModality(Qt.WindowModal)
        progressDialog.setMinimumDuration(5)
        progressDialog.setWindowTitle('Downloading')
        progressDialog.setWindowIcon(QIcon(':/res/favicon.ico'))
        progressDialog.setLabelText('Current speed: ')
        progressDialog.setCancelButtonText('Cancel')
        progressDialog.setRange(0, 100)

        while percent < 100 and not is_exits:
            percent = status.get_percent()
            is_exits = status.get_exist()
            if is_exits:
                self.result = 'Files already exists (..•˘_˘•..)'
                progressDialog.close()
                break
            progressDialog.setValue(percent)
            progressDialog.setLabelText('Current speed: ' + str(status.get_speed()))
            QThread.msleep(100)
            if progressDialog.wasCanceled():
                status.set_stop_thread(True)
                self.download_thread.wait()
                mlog.debug('stop the download thread')
                mlog.debug('download_thread.isRunning ' + str(self.download_thread.isRunning()))
                progressDialog.close()
                self.result = 'Paused Σ(っ °Д °;)っ'
                break
示例#7
0
    def printDocument(self, printer):
        loop = QEventLoop()
        result = False

        def printPreview(success):
            nonlocal result
            result = success
            loop.quit()

        progressbar = QProgressDialog(self.m_page.view())
        progressbar.findChild(QProgressBar).setTextVisible(False)
        progressbar.setLabelText("Wait please...")
        progressbar.setRange(0, 0)
        progressbar.show()
        progressbar.canceled.connect(loop.quit)
        self.m_page.print(printer, printPreview)
        loop.exec_()
        progressbar.close()
        if not result:
            painter = QPainter()
            if painter.begin(printer):
                font = painter.font()
                font.setPixelSize(20)
                painter.setFont(font)
                painter.drawText(QPointF(10, 25),
                                 "Could not generate print preview.")
                painter.end()
示例#8
0
def blocking_loading_bar(
	task: Callable[[pyqtSignal, pyqtSignal, pyqtSignal], R],
	window_title: str,
) -> R:
	progress_dialog = QProgressDialog()
	progress_dialog.setWindowTitle(window_title)
	progress_dialog.show()

	return_value = None
	def finished_callback(value: R) -> None:
		nonlocal return_value
		return_value = value
	
	def label_text_callback(new_label_text: str) -> None:
		progress_dialog.setLabelText(new_label_text)

	(thread, obj) = run_in_background(task, progress_dialog, label_text_callback, finished_callback)

	qapp = QApplication.instance()
	while not return_value:
		qapp.processEvents()

	del thread, obj

	progress_dialog.close()
	return return_value
示例#9
0
    def addMediaFile(self):
        path = '.'
        filename = self.labeltool.getCurrentFilename()
        if (filename is not None) and (len(filename) > 0):
            path = QFileInfo(filename).path()

        image_types = [ '*.jpg', '*.bmp', '*.png', '*.pgm', '*.ppm', '*.tiff', '*.tif', '*.gif' ]
        video_types = [ '*.mp4', '*.mpg', '*.mpeg', '*.avi', '*.mov', '*.vob' ]
        format_str = ' '.join(image_types + video_types)
        fnames = QFileDialog.getOpenFileNames(self, "%s - Add Media File" % APP_NAME, path, "Media files (%s)" % (format_str, ))[0]

        item = None
        numFiles = len(fnames)
        progress_bar = QProgressDialog('Importing files...', 'Cancel import', 0, numFiles, self)
        for fname,c in zip(fnames, range(numFiles)):
            if len(str(fname)) == 0:
                continue

            fname = str(fname)

            if os.path.isabs(fname):
                fname = os.path.relpath(fname, str(path))

            for pattern in image_types:
                if fnmatch.fnmatch(fname.lower(), pattern):
                    item = self.labeltool.addImageFile(fname)
            
            progress_bar.setValue(c)

        if item is None:
            return self.labeltool.addVideoFile(fname)

        progress_bar.close()
        
        return item
示例#10
0
 def ConvertToHSV(self):
     progress_dialog = QProgressDialog()
     self.processing_wdg.SetConvertBtnDisactive()
     image = self.processed_image.ConvertToHSV()
     self.processed_image = Segmented_image.FromSITKImage(image)
     self.ShowSelectedImage()
     progress_dialog.close()
示例#11
0
    def show_progress_bar(self):
        percent = 0
        is_exits = False
        self.result = None
        progressDialog = QProgressDialog(self.files_list_dialog)
        progressDialog.setAutoReset(True)
        progressDialog.setWindowModality(Qt.WindowModal)
        progressDialog.setMinimumDuration(5)
        progressDialog.setWindowTitle('Downloading')
        progressDialog.setWindowIcon(QIcon(':/res/favicon.ico'))
        progressDialog.setLabelText('Current speed: ')
        progressDialog.setCancelButtonText('Cancel')
        progressDialog.setRange(0, 100)

        while percent < 100 and not is_exits:
            percent = status.get_percent()
            is_exits = status.get_exist()
            if is_exits:
                self.result = 'Files already exists (..•˘_˘•..)'
                progressDialog.close()
                break
            progressDialog.setValue(percent)
            progressDialog.setLabelText('Current speed: ' +
                                        str(status.get_speed()))
            QThread.msleep(100)
            if progressDialog.wasCanceled():
                status.set_stop_thread(True)
                self.download_thread.wait()
                mlog.debug('stop the download thread')
                mlog.debug('download_thread.isRunning ' +
                           str(self.download_thread.isRunning()))
                progressDialog.close()
                self.result = 'Paused Σ(っ °Д °;)っ'
                break
示例#12
0
    def findFiles(self, files, text):
        progressDialog = QProgressDialog(self)

        progressDialog.setCancelButtonText("&Cancel")
        progressDialog.setRange(0, files.count())
        progressDialog.setWindowTitle("Find Files")

        foundFiles = []

        for i in range(files.count()):
            progressDialog.setValue(i)
            progressDialog.setLabelText("Searching file number %d of %d..." % (i, files.count()))
            QApplication.processEvents()

            if progressDialog.wasCanceled():
                break

            inFile = QFile(self.currentDir.absoluteFilePath(files[i]))

            if inFile.open(QIODevice.ReadOnly):
                stream = QTextStream(inFile)
                while not stream.atEnd():
                    if progressDialog.wasCanceled():
                        break
                    line = stream.readLine()
                    if text in line:
                        foundFiles.append(files[i])
                        break

        progressDialog.close()

        return foundFiles
示例#13
0
 def repop (self) :
     h=QMessageBox.question(self, "WARNING", "WARNING ! Repopulate will erase all the database by an Excel file generated by this database. Do not do this action randomly !!! Are you sur you want to continue ?")
     if h==QMessageBox.No :
         return None
     fname=QFileDialog.getOpenFileName(self, 'Choose an Excel File', '/','Excem File (*.xls)')[0]
     prog=QProgressDialog("Gathering Data...","Cancel",0,100,self)
     prog.open()
     if prog.wasCanceled() :
         return None
     rep=excel.repopulate(fname)
     try :
         rep.begin()
         if prog.wasCanceled() :
             return None
     except :
         return None
     state=int(rep.returnstate())
     prog.setLabelText("Repopulating...")
     while state==0 :
         prog.setValue(rep.returnpercent())
         state=rep.returnstate()
         prog.setCancelButton(None)
     if state==1 :
         prog.close()
         QMessageBox.information(self, "Sucess", "Repopulation Sucess")
     if state==-1 :
         QMessageBox.information(self, "Error", "Repopulation Failled")
示例#14
0
    def download_shapefile(self, layer, force=False, progress_bar=None):
        """
        This downloads shapefile&friends from the github repository if it doesn't exist already.
        """
        path = os.path.dirname(os.path.abspath(__file__)) + "/data/" + layer

        if not os.path.exists(path) or force:
            QgsMessageLog.logMessage("{} does not exist or redownload forced.".format(layer),"PopGIS")

            if progress_bar is None:
                close_progress_bar = True
                progress_bar = QProgressDialog()
            else:
                close_progress_bar = False
            progress_bar.setAutoClose(False)
            progress_bar.show()

            def show_progress_callback(block_num, block_size, total_size):
                progress_bar.setMaximum(total_size)
                progress_bar.setValue(block_num*block_size)
                QApplication.processEvents()

            try:
                for ext in self.shp_required_friends + self.shp_friends:

                    file_name = os.path.splitext(layer)[0] + ext
                    download_url = self.shp_download_root + urllib.parse.quote(file_name)
                    save_url = os.path.splitext(path)[0] + ext

                    progress_bar.setLabelText("Downloading {}".format(file_name))

                    QgsMessageLog.logMessage("Downloading {}...".format(download_url),"PopGIS")

                    os.makedirs( os.path.dirname(save_url), exist_ok=True )
                    try:
                        urllib.request.urlretrieve(download_url, save_url, show_progress_callback)
                        QgsMessageLog.logMessage("Saved to {}".format(save_url),"PopGIS")
                    except urllib.error.HTTPError as e:
                        # We throw the exception only if the file is required.
                        if ext in self.shp_required_friends:
                            raise e

            except Exception as e:
                QgsMessageLog.logMessage("Download of {} failed. Removing data.".format(layer),"PopGIS")

                # We delete all files to avoid leaving corrupted data
                for ext in self.shp_friends:
                    save_url = os.path.splitext(path)[0] + ext

                # We still raise the exception
                raise e

            if close_progress_bar:
                progress_bar.close()

        else:
            QgsMessageLog.logMessage("{} already exists. Using cached version.".format(layer),"PopGIS")

        return path
    def on_pb_downloadPerson_clicked(self):
        '''方法作用从住建平台上下载已生成了住建平台号的人员信息'''
        runStatus = True
        progress = QProgressDialog(self)
        progress.setWindowTitle('请稍等')
        progress.setLabelText('数据下载中...')
        progress.setCancelButtonText('中止操作')
        progress.setWindowModality(Qt.WindowModal)
        progress.resize(800, 50)
        while runStatus:
            countD = self.faceDevices.rowCount()

            progress.setRange(0, countD)

            if countD > 0:
                i = 0

                while i < countD:

                    faces = self.faceDevices.record(i)

                    sn = str.strip(faces.field('sn').value())
                    key = str.strip(faces.field('key').value())

                    self.cdzj.downloadPerson(sn, key)
                    if self.cdzj.msg_downloadPerson == 'success':
                        qs = "update wis_person set user_id = '%s', work_sn = '%s' where idNo = '%s'" % (
                            self.cdzj.person['user_id'],
                            self.cdzj.person['work_sn'],
                            self.cdzj.person['idNo'])
                        self.db.excuteSQl(qs)
                        selectQs = "select * from wis_person where idNo = '%s'" % self.cdzj.person[
                            'idNo']
                        data = self.db.querySQL(selectQs)
                        countP = data.rowCount()
                        self.cdzj.feedback(sn, 2, '下发成功')
                        progress.setValue(i)
                        if progress.wasCanceled():
                            QMessageBox.warning(self, "提示", "操作失败")
                            break
                        # QMessageBox.information(self, '提示', '本次同步人员数:%d  ' % countP, QMessageBox.Yes)
                    else:
                        runStatus = False
                        progress.close()
                        QMessageBox.information(self, '提示',
                                                '同步失败,原因:%s  ' % self.cdzj.msg,
                                                QMessageBox.Yes)
                        # self.cdzj.feedback('smz-a03', 3, '下发失败')
                        break
                    i += 1
                else:
                    progress.setValue(countD)
                    QMessageBox.information(self, "提示", "操作成功")

            else:
                progress.deleteLater()
                QMessageBox.information(self, '提示', '未找到考勤设备!',
                                        QMessageBox.Yes)
                break
示例#16
0
    def addImages(self):
        imageFileNames = QFileDialog.getOpenFileNames(
            caption="Select image files to label")

        if not imageFileNames[0] or len(imageFileNames[0]) == 0:
            return

        imageFileNames = imageFileNames[0]
        labelsDir = QFileInfo(self.labelsFileName).absoluteDir()
        originDir = QFileInfo(imageFileNames[0]).absoluteDir()

        #Copy image files to the labels folder
        if originDir.absolutePath() != labelsDir.absolutePath():
            progDialog = QProgressDialog(
                "Copying image files to the labels folder", "Cancel", 0,
                len(imageFileNames), self)

        i = 0
        for imageFileName in imageFileNames:
            progDialog.setValue(i)

            oldName = QFileInfo(imageFileName).fileName()
            newPath = labelsDir.absoluteFilePath(oldName)

            print("Copying {} to {}".format(imageFileName, newPath))

            ok = QFile.copy(imageFileName, newPath)

            QApplication.processEvents()

            if not ok:
                print("Error copying {} to {}".format(imageFileName, newPath))

            i += 1

        progDialog.setValue(len(imageFileNames))
        progDialog.close()

        currentImageFileNames = [s.fileName for s in self.labeledImages]

        newImgIdx = len(self.labeledImages)

        for imageFileName in imageFileNames:
            normalizedFileName = QFileInfo(imageFileName).fileName()

            if normalizedFileName in currentImageFileNames:
                print("File {} already in dataset, skipping".format(
                    normalizedFileName))
                continue

            self.labeledImages.append(LabeledImage(normalizedFileName, []))

        self.fileListModel.setStringList(
            [s.fileName for s in self.labeledImages])
        self.loadImageAtIndex(newImgIdx)

        print("Added {} images to dataset".format(len(imageFileNames)))
        print("New length of labeledImages array {}".format(
            len(self.labeledImages)))
示例#17
0
    def _load_json(self, filename):
        """
        Loads all of the HDF5 files listed in the input JSON file.

        Args:

            filename: the fully-qualified name of a JSON file containing the names of HDF5 files produced by a
            DecontaminatedSpectraCollection.
        """
        if not os.path.isabs(filename):
            raise ValueError(
                "The filename must include the full (absolute) path.")

        dir_name = os.path.dirname(filename)

        with open(filename) as f:
            decontaminated_spectra_collection_filenames = json.load(f)

        for f in decontaminated_spectra_collection_filenames:
            full_name = os.path.join(dir_name, 'data', f)
            if not h5py.is_hdf5(full_name):
                raise TypeError(f'{f} is not a valid HDF5 file.')

        n_files = len(decontaminated_spectra_collection_filenames)

        loop = QEventLoop()

        progress = QProgressDialog(
            "Loading decontaminated spectra collections", None, 0, n_files,
            self._parent)
        plural = 'files' if n_files > 1 else 'file'
        progress.setWindowTitle(
            f"Loading {n_files} decontaminated spectra {plural}")
        progress.setModal(True)
        progress.setMinimumDuration(0)
        progress.setValue(0)
        progress.show()

        loop.processEvents()

        for i, decontaminated_spectra_filename in enumerate(
                decontaminated_spectra_collection_filenames):
            status_message = f'loading {decontaminated_spectra_filename}'
            progress.setLabelText(status_message)
            progress.setValue(i)
            loop.processEvents()
            full_name = os.path.join(dir_name, 'data',
                                     decontaminated_spectra_filename)

            self._load_hdf5(full_name)

            progress.setValue(i + 1)
            loop.processEvents()

        progress.close()
示例#18
0
def create_database_de_novo(parent, database_path):
    """ Setup a new database from the MetaNetX files
    
    Parameters
    ----------
    parent: GEMEditor.main.MainWindow
    database_path: str

    Returns
    -------

    """

    # Generate an empty database
    if not setup_empty_database(database_path):
        return

    # Download files
    files = download_metanetx_files(parent)
    if not files:
        return

    connection = get_database_connection()
    if connection is None:
        # Delete temp files
        cleanup_files(files)
        return

    # Setup progress dialog
    progress = QProgressDialog()
    progress.setAutoClose(0)
    progress.setWindowTitle("Setting up tables..")

    load_metabolites(connection, files, progress)
    load_metabolites_xref(connection, files, progress)
    load_compartments(connection, files, progress)
    load_reactions(connection, files, progress)
    load_reaction_xrefs(connection, files, progress)
    create_indices(connection, progress)

    # Cleanup files
    connection.close()
    cleanup_files(files)

    if progress.wasCanceled():
        try:
            os.remove(database_path)
        except OSError:
            pass
        progress.close()
        return None

    progress.close()
    return True
    def on_addFileButton_clicked(self):
        fileDialog = QFileDialog(self.mainwindow)
        fileDialog.setFileMode(QFileDialog.ExistingFiles)
        fileDialog.setViewMode(QFileDialog.List)
        if fileDialog.exec_():
            file_paths = fileDialog.selectedFiles()
            whole_task_num = len(file_paths) * 4
            progress = 0
            progressDialog = QProgressDialog("Accessing data....", "cancel", 0,
                                             whole_task_num, self.filelistView)
            progressDialog.setWindowModality(Qt.ApplicationModal)
            progressDialog.setValue(0)
            progressDialog.show()
            QCoreApplication.processEvents()

            for each_path in file_paths:
                reader = IOFactory.CreateHandler(each_path)
                if not reader:
                    continue
                new_data = reader.ReadSingleFile()

                #                 if len(new_data) > 1:
                #                     if new_data[0][0] > new_data[1][0]:
                #                         new_data = sorted(new_data, key=itemgetter(0))
                #                 elif len(new_data) == 0:
                #                     progress += 4
                #                     continue
                progress += 1
                progressDialog.setValue(progress)
                for each_data in new_data.items():
                    filemodeldata = [
                        each_data[0], each_data[1][0][0], each_data[1][-1][0]
                    ]
                    self.filemodel.appendRow(filemodeldata)
                    progress += 1
                    progressDialog.setValue(progress)
                    new_contract_name = each_data[0]
                    if new_contract_name not in self.contractEditor_dict.keys(
                    ):
                        new_contract_editor = ContractMain(
                            new_contract_name, each_data[1])
                        self.contractEditor_dict[
                            new_contract_name] = new_contract_editor
                    progress += 1
                    progressDialog.setValue(progress)
                    contract_range = [each_data[1][0][0], each_data[1][-1][0]]
                    self.adjustmodel.addNewContract(each_data[0],
                                                    contract_range)
                    progress += 1
                    progressDialog.setValue(progress)

            progressDialog.close()
示例#20
0
    def update_evidences(self):
        progress = QProgressDialog(self)
        conflicts, failing, error = sort_evidences(self.model.all_evidences.values())

        # Populate tables
        self.tab_error.datatable.populate_table(error)
        self.populate_tree(self.tab_failing.datatable, failing, EvidenceTable.row_from_item)
        self.tab_failing.dataView.expandAll()
        self.populate_tree(self.tab_conflict.datatable, conflicts, EvidenceTable.row_from_item)
        self.tab_conflict.dataView.expandAll()

        self.update_labels()
        progress.close()
示例#21
0
class ProgressWindow:
    def __init__(self, parent, model):
        self._window = None
        self.parent = parent
        self.model = model
        model.view = self
        # We don't have access to QProgressDialog's labels directly, so we se the model label's view
        # to self and we'll refresh them together.
        self.model.jobdesc_textfield.view = self
        self.model.progressdesc_textfield.view = self

    # --- Callbacks
    def refresh(self):  # Labels
        if self._window is not None:
            self._window.setWindowTitle(self.model.jobdesc_textfield.text)
            self._window.setLabelText(self.model.progressdesc_textfield.text)

    def set_progress(self, last_progress):
        if self._window is not None:
            if last_progress < 0:
                self._window.setRange(0, 0)
            else:
                self._window.setRange(0, 100)
            self._window.setValue(last_progress)

    def show(self):
        flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint
        self._window = QProgressDialog("", tr("Cancel"), 0, 100, self.parent,
                                       flags)
        self._window.setModal(True)
        self._window.setAutoReset(False)
        self._window.setAutoClose(False)
        self._timer = QTimer(self._window)
        self._timer.timeout.connect(self.model.pulse)
        self._window.show()
        self._window.canceled.connect(self.model.cancel)
        self._timer.start(500)

    def close(self):
        # it seems it is possible for close to be called without a corresponding
        # show, only perform a close if there is a window to close
        if self._window is not None:
            self._timer.stop()
            del self._timer
            # For some weird reason, canceled() signal is sent upon close, whether the user canceled
            # or not. If we don't want a false cancellation, we have to disconnect it.
            self._window.canceled.disconnect()
            self._window.close()
            self._window.setParent(None)
            self._window = None
示例#22
0
 def MakeSegmentation(self):
     progress_dialog = QProgressDialog()
     segmentation = Segmentation(self.processed_image)
     progress_dialog.setValue(10)
     seg_img = segmentation.makeSegment(self.processing_wdg.GetMinObjSize(),
                                        self.processing_wdg.GetThrDown(),
                                        self.processing_wdg.GetThrUp())
     progress_dialog.setValue(30)
     self.processed_image = Segmented_image.FromSITKImage(seg_img)
     progress_dialog.setValue(50)
     self.processing_wdg.SetCellsNumResult(segmentation.GetCellsNum())
     progress_dialog.setValue(80)
     self.ShowSelectedImage()
     progress_dialog.setValue(100)
     progress_dialog.close()
示例#23
0
def progressbar_iterator(iteratable, n_elements, label, win_title):
    # iterator function with prgress bar
    dialog = QProgressDialog()
    dialog.setMaximum(100)
    dialog.setLabelText(label)
    dialog.setWindowTitle(win_title)
    dialog.open()
    for cnt, item in enumerate(iteratable):
        p = (cnt * 100) // n_elements
        QCoreApplication.instance().processEvents()
        if dialog.wasCanceled():
            raise StopIteration
        dialog.setValue(p)
        yield (item)

    dialog.close()
示例#24
0
 def analysis_riss(self):
     self.resultView.deleteAllLabels()
     progress = QProgressDialog(self)
     progress.setWindowTitle("Analyzing")
     progress.setLabelText("Analyzing...")
     progress.setCancelButtonText("cancel")
     progress.setMinimumDuration(5)
     progress.setWindowModality(Qt.WindowModal)
     polygons = []
     for i, polygon in enumerate(self.originView.polygonList):
         polygons.append(polygon['geo'])
         progress.setValue(i + 1)
     self.resultView.addRissPolygons(polygons)
     progress.close()
     QMessageBox.information(self, 'Finished', 'Analysis is Finished.')
     self.__updateActionState()
示例#25
0
 def analysis(self):
     # progressDialog.show()
     # msgBox=QMessageBox.information(self, 'Analysising', 'The result is being calculated, please wait. ')
     self.resultView.deleteAllLabels()
     progress = QProgressDialog(self)
     progress.setWindowTitle("Analyzing")
     progress.setLabelText("Analyzing...")
     progress.setCancelButtonText("cancel")
     progress.setMinimumDuration(5)
     progress.setWindowModality(Qt.WindowModal)
     progress.setRange(0, len(self.originView.polygonList))
     for i, polygon in enumerate(self.originView.polygonList):
         self.resultView.addPolygonArea(polygon['geo'])
         progress.setValue(i + 1)
     progress.close()
     QMessageBox.information(self, 'Finished', 'Analysis is Finished.')
     self.__updateActionState()
示例#26
0
class ProgressWindow:
    def __init__(self, parent, model):
        self._window = None
        self.parent = parent
        self.model = model
        model.view = self
        # We don't have access to QProgressDialog's labels directly, so we se the model label's view
        # to self and we'll refresh them together.
        self.model.jobdesc_textfield.view = self
        self.model.progressdesc_textfield.view = self

    # --- Callbacks
    def refresh(self): # Labels
        if self._window is not None:
            self._window.setWindowTitle(self.model.jobdesc_textfield.text)
            self._window.setLabelText(self.model.progressdesc_textfield.text)

    def set_progress(self, last_progress):
        if self._window is not None:
            self._window.setValue(last_progress)

    def show(self):
        flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint
        self._window = QProgressDialog('', "Cancel", 0, 100, self.parent, flags)
        self._window.setModal(True)
        self._window.setAutoReset(False)
        self._window.setAutoClose(False)
        self._timer = QTimer(self._window)
        self._timer.timeout.connect(self.model.pulse)
        self._window.show()
        self._window.canceled.connect(self.model.cancel)
        self._timer.start(500)

    def close(self):
        # it seems it is possible for close to be called without a corresponding
        # show, only perform a close if there is a window to close
        if self._window is not None:
            self._timer.stop()
            del self._timer
            # For some weird reason, canceled() signal is sent upon close, whether the user canceled
            # or not. If we don't want a false cancellation, we have to disconnect it.
            self._window.canceled.disconnect()
            self._window.close()
            self._window.setParent(None)
            self._window = None
示例#27
0
class ProgressBarDialog(QWidget):
    def __init__(self,
                 title='',
                 label='',
                 minValue=0,
                 maxValue=100,
                 parent=None):
        super(ProgressBarDialog, self).__init__(parent)
        self.process_bar = QProgressDialog(self)
        self.set_bar_window_title(title)
        self.set_label_text(label)
        self.set_min_value(minValue)
        self.set_max_value(maxValue)
        self.process_bar.setWindowModality(Qt.WindowModal)
        self.setGeometry(800, 300, 580, 570)
        self.process_bar.canceled.connect(self.close_bar)

    def set_bar_window_title(self, text):
        self.process_bar.setWindowTitle(text)
        self.setWindowTitle(text)

    def set_label_text(self, text):
        self.process_bar.setLabelText(text)

    def set_min_value(self, minValue):
        self.process_bar.setMinimum(minValue)

    def set_max_value(self, maxvalue):
        self.process_bar.setMaximum(maxvalue)

    def set_value(self, value):
        self.process_bar.setValue(value)

    def close_bar(self):
        self.process_bar.close()

    def reset_bar(self):
        self.process_bar = None

    def show(self):
        self.process_bar.show()

    def is_valid(self):
        return bool(self.process_bar)
示例#28
0
    class ProgressBar():
        def __init__(self, text):
            if QApplication.instance() is None:
                self.dialog = None
                print(text)
            else:
                self.dialog = QProgressDialog(text, 'Cancel', 0, 100)
                self.dialog.setWindowFlags(Qt.WindowStaysOnTopHint)
                self.dialog.show()

        def update(self, value):
            if self.dialog:
                self.dialog.setValue(value)
                QApplication.processEvents()
            else:
                print('Progress: %.2f%% done' % value)

        def close(self):
            if self.dialog:
                self.dialog.close()
示例#29
0
    class ProgressBar():
        def __init__(self, text):
            if QApplication.instance() is None:
                self.dialog = None
                print(text)
            else:
                self.dialog = QProgressDialog(text, 'Cancel', 0, 100)
                self.dialog.setWindowFlags(Qt.WindowStaysOnTopHint)
                self.dialog.show()

        def update(self, value):
            if self.dialog:
                self.dialog.setValue(value)
                QApplication.processEvents()
            else:
                print('Progress: %.2f%% done' % value)

        def close(self):
            if self.dialog:
                self.dialog.close()
示例#30
0
def progress_dialog(main_window: QMainWindow, title: str, label: str,
                    maximum: int) -> ContextManager[QProgressDialog]:
    """:class:`~contextlib.contextmanager` that displays a progress dialog

    :param main_window: Application main window
    :param title: Progress dialog title
    :param label: Progress dialog label
    :param maximum: Maximum value for progress

    """

    progress_dialog = QProgressDialog(main_window)
    progress_dialog.setWindowTitle(title)
    progress_dialog.setWindowModality(Qt.WindowModal)
    progress_dialog.setLabelText(label)
    progress_dialog.setMaximum(maximum)

    yield progress_dialog

    progress_dialog.setValue(maximum)
    progress_dialog.close()
    progress_dialog.deleteLater()
def download_file(url, path, session):
    count = 0
    chunksize = 8192
    lastvalue = 0

    r = session.get(url, stream=True)
    if r.status_code == 401:  # not logged in anymore
        os.remove(COOKIE_FILE)
        show_popup("ERROR", "Please restart the application and try again!")
        sys.exit(1)
    if r.status_code == 404:  # release not found, skip
        show_popup("ERROR", "There was an error downloading the release with the url: " + url)
        return True
    filename = str.replace(re.findall("filename=(.+)", r.headers['content-disposition'])[0], "\"", "")
    fullpath = path + "/" + filename
    print(fullpath)
    diff = (100 / int(r.headers['Content-Length']))

    # PROGRESS BAR
    bar = QProgressDialog("Downloading <i>" + filename + "</i>", "Cancel", 0, 100)
    bar.setWindowTitle("Downloading")
    bar.setValue(0)

    with open(fullpath, 'wb') as f:
        for chunk in r.iter_content(chunk_size=chunksize):
            if chunk:  # filter out keep-alive new chunks
                f.write(chunk)
                percentvalue = round(count * chunksize * diff, 0)
                # print(percentvalue)
                if percentvalue != lastvalue:
                    bar.setValue(percentvalue)
                    lastvalue = percentvalue
                count += 1
                if bar.wasCanceled():
                    os.remove(fullpath)
                    return False
                QApplication.processEvents()
    bar.close()
    return True
示例#32
0
 def train_payee_to_account(self):
     if not os.path.isfile(app_config.recent_beancount_file):
         QMessageBox.critical(self, self.tr('Error'), self.tr('No beancount file is open for traning.'))
         return
     dialog = QProgressDialog(self.tr('Training...'), self.tr('Abort training'), 0, 100, self)
     trainer = PayeeToAccountTrainer(self)
     trainer.trainProgress.connect(dialog.setValue)
     dialog.canceled.connect(trainer.cancel)
     dialog.open()
     try:
         result = trainer.train(app_config.recent_beancount_file)
         for (payee, account) in result.items():
             if payee in app_config.payee_account_map and app_config.payee_account_map[payee] != account:
                 overwrite = QMessageBox.question(self,
                                                  self.tr('Overwrite?'),
                                                  self.tr('{0} already exists on payee to account map with value {1}. Do you want to overwite it with {2}?').format(payee, app_config.payee_account_map[payee], account))
                 if overwrite == QMessageBox.Yes:
                     app_config.payee_account_map[payee] = account
             else:
                 app_config.payee_account_map[payee] = account
     except Exception as e:
         QMessageBox.critical(self, self.tr('Error'), self.tr('An error occurred while training: {0}.').format(e))
         dialog.close()
 def getAllFrames(self):
     """ Return the entire image stack as a NumPy ndarray.
     !!! This currently ONLY works for grayscale image stacks that can be represented as 3D arrays.
     !!! For large image stacks this can be time and memory hungry.
     """
     if self._tiffCaptureHandle is None:
         return None
     imageWidth = self._tiffCaptureHandle.shape[0]
     imageHeight = self._tiffCaptureHandle.shape[1]
     numFrames = self.numFrames()
     entireStackArray = np.empty((imageWidth, imageHeight, numFrames))
     progress = QProgressDialog(self)
     progress.setLabelText("Loading TIFF image stack...")
     progress.setRange(0, numFrames)
     progress.setValue(0)
     progress.setWindowModality(Qt.WindowModal)
     progress.show()
     for i, frame in enumerate(self._tiffCaptureHandle):
         entireStackArray[:,:,i] = frame
         progress.setValue(i)
         if progress.wasCanceled():
             return None
     progress.close()
     return entireStackArray
 def getAllFrames(self):
     """ Return the entire image stack as a NumPy ndarray.
     !!! This currently ONLY works for grayscale image stacks that can be represented as 3D arrays.
     !!! For large image stacks this can be time and memory hungry.
     """
     if self._tiffCaptureHandle is None:
         return None
     imageWidth = self._tiffCaptureHandle.shape[0]
     imageHeight = self._tiffCaptureHandle.shape[1]
     numFrames = self.numFrames()
     entireStackArray = np.empty((imageWidth, imageHeight, numFrames))
     progress = QProgressDialog(self)
     progress.setLabelText("Loading TIFF image stack...")
     progress.setRange(0, numFrames)
     progress.setValue(0)
     progress.setWindowModality(Qt.WindowModal)
     progress.show()
     for i, frame in enumerate(self._tiffCaptureHandle):
         entireStackArray[:, :, i] = frame
         progress.setValue(i)
         if progress.wasCanceled():
             return None
     progress.close()
     return entireStackArray
示例#35
0
class ProgressCallbackWidget(ClientCallback):
    def __init__(self, parent):
        ClientCallback.__init__(self)

        self._parent = parent
        self._block = False

        self._label_text = ''
        self._title_text = ''
        self._updated_text = ''
        self._finished_text = ''
        self._cancellable = True

        self.status_progress = QProgressDialog(self._parent, Qt.Dialog)

        self.set_range(0, 1)

    def __del__(self):
        self.status_progress.close()
        del self.status_progress

    def set_block(self, block):
        self._block = block

    def set_title_text(self, title_text):
        self._title_text = title_text

    def set_label_text(self, label_text):
        self._label_text = label_text

    def set_updated_text(self, updated_text):
        self._updated_text = updated_text

    def set_finished_text(self, finished_label):
        self._finished_text = finished_label

    def set_cancellable(self, cancellable):
        if not self._cancellable and cancellable:
            log.warning(
                'ProgressCallbackWidget.set_cancellable({cancellable}): invalid operation'
                .format(cancellable=cancellable))
        if cancellable:
            if not self._cancellable:
                self.status_progress.setCancelButton(QPushButton(_('Cancel')))
        else:
            self.status_progress.setCancelButton(None)
        self._cancellable = cancellable

    def on_show(self):
        # FIXME: status_progress may be None if on_update is called BEFORE show..
        # FIXME: rename to start..
        self.status_progress.reset()

        self.set_block(self._block)
        self.set_cancellable(self._cancellable)

        self.status_progress.setWindowTitle(self._title_text)
        self.status_progress.setLabelText(self._label_text)

        minimum, maximum = self.get_range()

        self.status_progress.setMinimum(minimum)
        self.status_progress.setMaximum(maximum)

        self.status_progress.show()
        if self._block:
            self._parent.setCursor(Qt.WaitCursor)

    def on_update(self, value, *args, **kwargs):
        self.status_progress.setValue(value)
        if self._updated_text:
            # FIXME: let the caller format the strings
            updatedMsg = self._updated_text.format(*args)
            self.status_progress.setLabelText(updatedMsg)
        QCoreApplication.processEvents()

    def on_finish(self, *args, **kwargs):
        # FIXME: let the caller format the strings
        finishedMsg = self._finished_text.format(*args)
        self.status_progress.setLabelText(finishedMsg)
        self.status_progress.done(0)
        if self._block:
            self._parent.setCursor(
                Qt.ArrowCursor
            )  # FIXME: restoreCursor? setCursor only in this class!!
        QCoreApplication.processEvents()

    def on_rangeChange(self, minimum, maximum):
        self.status_progress.setMinimum(minimum)
        self.status_progress.setMaximum(maximum)
        QCoreApplication.processEvents()

    def on_cancel(self):
        self.status_progress.cancel()
        if self._block:
            self._parent.setCursor(Qt.ArrowCursor)
        QCoreApplication.processEvents()

    def canceled(self):
        return self.status_progress.wasCanceled()
示例#36
0
class MainWindow(QMainWindow):

    connect_to_yadisk_signal = pyqtSignal()
    get_yadisk_listdir = pyqtSignal(str)
    get_local_listdir = pyqtSignal(str)
    get_bublic_listdir = pyqtSignal(str)

    move_file_signal = pyqtSignal(str, str)
    download_from_auth_yadisk = pyqtSignal(str, str, dict)
    download_from_bublic_yadisk = pyqtSignal(str, str, dict)
    upload_to_auth_yadisk = pyqtSignal(str, str, dict)

    open_link_signal = pyqtSignal()

    local_browse_clicked = pyqtSignal(KeyType, SecurityAlgorithm)
    yadisk_browse_clicked = pyqtSignal(KeyType, SecurityAlgorithm)

    local_algorithm_changed = pyqtSignal(SecurityAlgorithm, KeyType)
    yadisk_algorithm_changed = pyqtSignal(SecurityAlgorithm, KeyType)

    set_media_folder = pyqtSignal(str)

    def __init__(self):
        super(MainWindow, self).__init__()
        uic.loadUi("forms/mainwindow.ui", self)
        self.local_files = QTabWidget()  #FileSystem()
        self.add_local_file_system()

        self.yadisk_files = QTabWidget()

        self.h_layout.layout().addWidget(self.local_files)
        self.h_layout.layout().addWidget(self.yadisk_files)

        self.connect_to_actions()
        self.show_status("Not connected")
        self.local_files.show()

        self.icon = QIcon(":/img/images/icon.png")
        self.setWindowIcon(self.icon)

    def connect_to_actions(self):
        self.connect_to_yadisk_action.triggered.connect(self.connect_to_yadisk)
        self.open_link_action.triggered.connect(self.open_link)
        self.yadisk_files.currentChanged.connect(self.yadisk_tab_changed)

    def get_local_system(self):
        return self.local_files.currentWidget()

    def get_yadisk(self):
        return self.yadisk_files.currentWidget()

    def add_local_file_system(self):
        file_system = FileSystem(magic_const.LOCAL_FILE_SYSTEM_LABELS, "local")

        file_system.double_clicked.connect(self.get_local_listdir)
        file_system.move_clicked.connect(self.move_file_from_local)
        file_system.browse_clicked.connect(self.local_browse_clicked)
        file_system.algorithm_changed.connect(self.local_algorithm_changed)

        self.local_files.addTab(file_system, "Local file system")
        file_system.set_load_button_enable(False)

    def add_authorized_yadisk_tab(self):
        file_system = FileSystem(magic_const.YADISK_FILE_SYSTEM_LABELS,
                                 "yadisk_auth")
        file_system.double_clicked.connect(self.get_yadisk_listdir)
        file_system.move_clicked.connect(self.move_file_from_yadisk)
        file_system.browse_clicked.connect(self.yadisk_browse_clicked)
        file_system.algorithm_changed.connect(self.yadisk_algorithm_changed)
        file_system.set_media_folder.connect(self.set_media_folder)

        self.yadisk_files.addTab(file_system, "YaDisk")
        self.yadisk_files.setCurrentWidget(file_system)

    def add_bublic_yadisk_tab(self, name="name"):
        file_system = BublicFileSystem(magic_const.YADISK_FILE_SYSTEM_LABELS,
                                       "bublic")
        file_system.double_clicked.connect(self.get_bublic_listdir)
        file_system.move_clicked.connect(self.move_file_from_bublic_yadisk)
        file_system.algorithm_changed.connect(self.yadisk_algorithm_changed)
        self.yadisk_files.addTab(file_system, name)
        self.yadisk_files.setCurrentWidget(file_system)

    def connect_to_yadisk(self):
        self.connect_to_yadisk_signal.emit()
        #self.yadisk_files.addTab(FileSystem(), "name")
        #self.connect_to_yadisk_signal.emit()

    def open_link(self):
        #self.add_yadisk_tab()
        self.open_link_signal.emit()

    def show_status(self, message):
        self.statusBar().showMessage(message)

    def show_local_listdir(self, listdir, path):
        #print("show local listdir", path)
        self.get_local_system().show_listdir(listdir, path)

    def show_yadisk_listdir(self, listdir, path):
        self.get_yadisk().show_listdir(listdir, path)

    def get_crypto_data(self, file_system):
        result = {
            "algorithm": file_system.get_algorithm(),
            "key_type": file_system.get_key_type(),
            "key": file_system.get_key().encode("utf-8"),
            "media_path": file_system.get_file_path(),
            "take_file_from_yadisk": file_system.take_file_from_yadisk(),
            "media_type": file_system.get_media_type()
        }

        return result

    def move_file_from_yadisk(self):
        local_system = self.get_local_system()
        yadisk_files = self.get_yadisk()
        from_folder = Path(yadisk_files.get_folder_path())
        to_folder = Path(local_system.get_folder_path())

        file_name = yadisk_files.get_file_name()
        from_path = from_folder / file_name
        to_path = to_folder / file_name

        encryption_data = self.get_crypto_data(yadisk_files)
        self.download_from_auth_yadisk.emit(from_path.as_posix(),
                                            to_path.as_posix(),
                                            encryption_data)
        #self.move_file_signal.emit(from_path.as_posix(), to_path.as_posix())

    def move_file_from_local(self):
        # TODO : add algorithm and key type

        local_system = self.get_local_system()
        yadisk_files = self.get_yadisk()

        from_folder = Path(local_system.get_folder_path())
        to_folder = Path(yadisk_files.get_folder_path())

        file_name = local_system.get_file_name()
        from_path = from_folder / file_name
        to_path = to_folder / file_name

        encryption_data = self.get_crypto_data(local_system)
        self.upload_to_auth_yadisk.emit(from_path.as_posix(),
                                        to_path.as_posix(), encryption_data)

    def move_file_from_bublic_yadisk(self):
        local_system = self.get_local_system()
        yadisk_files = self.get_yadisk()

        from_url = yadisk_files.get_folder_path()

        to_folder = Path(local_system.get_folder_path())
        file_name = yadisk_files.get_file_name()

        to_path = to_folder / file_name

        encryption_data = self.get_crypto_data(yadisk_files)
        self.download_from_bublic_yadisk.emit(from_url, to_path.as_posix(),
                                              encryption_data)

    def get_yadisk_folder_name(self):
        return self.yadisk_files.currentWidget().get_folder_path()

    def get_local_folder_name(self):
        return self.local_files.currentWidget().get_folder_path()

    def browse(self, filesystem, result):
        #filesystem.put_key("")
        filesystem.put_file_path("")

        if result["action"] == "get_save_filename":
            path = QFileDialog.getSaveFileName(self, "Create file", "new",
                                               result["limits"])
            filesystem.put_file_path(path[0])

        elif result["action"] == "get_open_filename":
            path = QFileDialog.getOpenFileName(self, "Open file", "",
                                               result["limits"])
            filesystem.put_file_path(path[0])
        else:
            pass

    def local_browse(self, result):
        filesystem = self.get_local_system()
        self.browse(filesystem, result)

    def yadisk_browse(self, result):
        filesystem = self.get_yadisk()
        self.browse(filesystem, result)

    def put_local_key(self, key):
        filesystem = self.get_local_system()
        filesystem.put_key(key)

    def put_yadisk_key(self, key):
        filesystem = self.get_yadisk()
        filesystem.put_key(key)

    def yadisk_tab_changed(self):
        yadisk_filesystem = self.yadisk_files.currentWidget()
        local_filesystem = self.local_files.currentWidget()
        if yadisk_filesystem.system_type == "yadisk_auth":
            local_filesystem.set_load_button_enable(True)
        elif yadisk_filesystem.system_type == "bublic":
            local_filesystem.set_load_button_enable(False)
        else:
            logger.error("In yadisk tab wrong system type")

    def show_progress_dialog(self, message, value=0, minmax=None):

        if minmax == None:
            minmax = (0, 0)
        self.progress = QProgressDialog(self)
        self.progress.setWindowTitle("Please, wait")
        self.progress.setLabelText(message)
        self.progress.setRange(*minmax)
        self.progress.setValue(value)
        self.progress.setCancelButton(None)
        self.progress.show()

        logger.info("Progress bar is opened")

    def close_progress_dialog(self):
        self.progress.close()
        logger.info("Progress bar is closed")
示例#37
0
    def CreateWord(self, savePathName):
        """
        将解析的Excel内容转换为Word内容并输出为Word文件
        """

        ComboBoxSelected = self.GetComboBoxSelected()
        tablename = ComboBoxSelected.get("tablename")
        casename = ComboBoxSelected.get("casename")
        caseID = ComboBoxSelected.get("caseID")
        requirement = ComboBoxSelected.get("requirement")
        condition = ComboBoxSelected.get("condition")
        casetext = ComboBoxSelected.get("casetext")
        testdata = ComboBoxSelected.get("testdata")
        passcondition = ComboBoxSelected.get("passcondition")
        input = ComboBoxSelected.get("input")
        expect = ComboBoxSelected.get("expect")
        result = ComboBoxSelected.get("result")
        # ispass = ComboBoxSelected.get("ispass")
        totalresult = ComboBoxSelected.get("totalresult")
        bugID = ComboBoxSelected.get("bugID")
        testman = ComboBoxSelected.get("testman")
        testtime = ComboBoxSelected.get("testtime")

        document = Document()

        # 设置进度显示
        prs = 1
        len_cases = len(self.Cases)
        process = QProgressDialog(self.model2_testreport_ui.groupBox)
        #如果进度条运行的时间小于2秒,进度条就不会显示,不设置默认是4S
        process.setMinimumDuration(2)
        process.setWindowTitle("清稍后")
        process.setLabelText("正在保存...")
        process.setCancelButtonText("取消")
        process.setRange(prs, len_cases + 1)
        process.setModal(True)

        for case in self.Cases:
            prs += 1
            process.setValue(prs)

            if process.wasCanceled():
                break

            # 添加表,并设置样式,可以使用的样式参见"site-packages\docx\templates\default-styles.xml"
            # 或"http://python-docx.readthedocs.io/en/latest/user/styles-understanding.html"
            document.add_paragraph(
                case[tablename],
                style='List Number').alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
            table = document.add_table(rows=7, cols=6, style='Table Grid')
            #第1行
            hdr_cells = table.rows[0].cells
            hdr_cells[0].text = u'测试用例名称'
            hdr_cells[1].merge(hdr_cells[2])
            hdr_cells[1].text = case[casename]
            hdr_cells[3].text = '用例标识'
            hdr_cells[4].merge(hdr_cells[5])
            hdr_cells[4].text = case[caseID]
            #宋体小四加粗
            cell_runs00 = hdr_cells[0].paragraphs[0].runs
            cell_runs00[0].font.name = u'宋体'
            r = cell_runs00[0]._element
            r.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
            cell_runs00[0].font.size = Pt(12)
            # cell_runs00[0].font.bold = True

            cell_runs02 = hdr_cells[3].paragraphs[0].runs
            cell_runs02[0].font.name = u'宋体'
            r = cell_runs02[0]._element
            r.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
            cell_runs02[0].font.size = Pt(12)
            # cell_runs04[0].font.bold = True
            # 第2行
            hdr_cells1 = table.rows[1].cells
            hdr_cells1[0].text = '需求追踪'
            hdr_cells1[1].merge(hdr_cells1[2]).merge(hdr_cells1[3]).merge(
                hdr_cells1[4]).merge(hdr_cells1[5])
            hdr_cells1[1].text = case[requirement]
            #宋体小四加粗
            cell_runs10 = hdr_cells1[0].paragraphs[0].runs
            cell_runs10[0].font.name = u'宋体'
            r = cell_runs10[0]._element
            r.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
            cell_runs10[0].font.size = Pt(12)
            # cell_runs10[0].font.bold = True

            # cell_runs14 = hdr_cells1[4].paragraphs[0].runs
            # cell_runs14[0].font.name = u'宋体'
            # r = cell_runs14[0]._element
            # r.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
            # cell_runs14[0].font.size = Pt(12)
            # cell_runs14[0].font.bold = True
            # 第3行
            hdr_cells2 = table.rows[2].cells
            hdr_cells2[0].text = '先决条件'
            hdr_cells2[1].merge(hdr_cells2[2]).merge(hdr_cells2[3]).merge(
                hdr_cells2[4]).merge(hdr_cells2[5])
            hdr_cells2[1].text = case[condition]
            #宋体小四加粗
            cell_runs20 = hdr_cells2[0].paragraphs[0].runs
            cell_runs20[0].font.name = u'宋体'
            r = cell_runs20[0]._element
            r.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
            cell_runs20[0].font.size = Pt(12)
            # cell_runs20[0].font.bold = True

            # cell_runs22 = hdr_cells2[2].paragraphs[0].runs
            # cell_runs22[0].font.name = u'宋体'
            # r = cell_runs22[0]._element
            # r.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
            # cell_runs22[0].font.size = Pt(12)
            # cell_runs22[0].font.bold = True
            #
            # cell_runs24 = hdr_cells2[4].paragraphs[0].runs
            # cell_runs24[0].font.name = u'宋体'
            # r = cell_runs24[0]._element
            # r.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
            # cell_runs24[0].font.size = Pt(12)
            # cell_runs24[0].font.bold = True
            # 第4行
            hdr_cells3 = table.rows[3].cells
            hdr_cells3[0].text = '测试用例综述'
            hdr_cells3[1].merge(hdr_cells3[2]).merge(hdr_cells3[3]).merge(
                hdr_cells3[4]).merge(hdr_cells3[5])
            hdr_cells3[1].text = case[casetext]
            #宋体小四加粗
            cell_runs30 = hdr_cells3[0].paragraphs[0].runs
            cell_runs30[0].font.name = u'宋体'
            r = cell_runs30[0]._element
            r.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
            cell_runs30[0].font.size = Pt(12)
            # cell_runs30[0].font.bold = True
            # 第5行
            hdr_cells4 = table.rows[4].cells
            hdr_cells4[0].text = '测试数据'
            hdr_cells4[1].merge(hdr_cells4[2]).merge(hdr_cells4[3]).merge(
                hdr_cells4[4]).merge(hdr_cells4[5])
            hdr_cells4[1].text = case[testdata]
            #宋体小四加粗
            cell_runs40 = hdr_cells4[0].paragraphs[0].runs
            cell_runs40[0].font.name = u'宋体'
            r = cell_runs40[0]._element
            r.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
            cell_runs40[0].font.size = Pt(12)
            # cell_runs40[0].font.bold = True
            # 第6行
            hdr_cells5 = table.rows[5].cells
            hdr_cells5[0].text = '通过准则'
            hdr_cells5[1].merge(hdr_cells5[2]).merge(hdr_cells5[3]).merge(
                hdr_cells5[4]).merge(hdr_cells5[5])
            hdr_cells5[1].text = case[passcondition]
            #宋体小四加粗
            cell_runs50 = hdr_cells5[0].paragraphs[0].runs
            cell_runs50[0].font.name = u'宋体'
            r = cell_runs50[0]._element
            r.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
            cell_runs50[0].font.size = Pt(12)
            # cell_runs50[0].font.bold = True
            # 第7行
            hdr_cells6 = table.rows[6].cells
            hdr_cells6[0].merge(hdr_cells6[1]).merge(hdr_cells6[2]).merge(hdr_cells6[3]).\
                merge(hdr_cells6[4]).merge(hdr_cells6[5])
            hdr_cells6[0].text = '测试步骤'
            #宋体小四加粗
            cell_runs60 = hdr_cells6[0].paragraphs[0].runs
            cell_runs60[0].font.name = u'宋体'
            r = cell_runs60[0]._element
            r.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
            cell_runs60[0].font.size = Pt(12)
            # cell_runs60[0].font.bold = True
            # 第8行
            table2 = document.add_table(rows=2, cols=10, style='Table Grid')

            hdr2_cells = table2.rows[0].cells
            hdr2_cells[0].text = '序号'
            hdr2_cells[1].merge(hdr2_cells[2]).merge(hdr2_cells[3])
            hdr2_cells[1].text = '输入及操作'
            hdr2_cells[4].merge(hdr2_cells[5]).merge(hdr2_cells[6])
            hdr2_cells[4].text = '期望结果'
            hdr2_cells[7].merge(hdr2_cells[8]).merge(hdr2_cells[9])
            hdr2_cells[7].text = '实测结果'
            # hdr2_cells[8].text = '通过与否'
            #宋体小四加粗
            # cell_runs70 = hdr2_cells[0].paragraphs[0].runs
            # cell_runs70[0].font.name = u'宋体'
            # r = cell_runs70[0]._element
            # r.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
            # cell_runs70[0].font.size = Pt(12)
            # # cell_runs70[0].font.bold = True
            #
            # cell_runs71 = hdr2_cells[1].paragraphs[0].runs
            # cell_runs71[0].font.name = u'宋体'
            # r = cell_runs71[0]._element
            # r.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
            # cell_runs71[0].font.size = Pt(12)
            #
            # cell_runs73 = hdr2_cells[5].paragraphs[0].runs
            # cell_runs73[0].font.name = u'宋体'
            # r = cell_runs73[0]._element
            # r.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
            # cell_runs73[0].font.size = Pt(12)

            #第9行
            hdr2_cells1 = table2.rows[1].cells
            hdr2_cells1[0].text = '1'
            hdr2_cells1[1].merge(hdr2_cells1[2]).merge(hdr2_cells1[3])
            hdr2_cells1[1].text = case[input]
            hdr2_cells1[4].merge(hdr2_cells1[5]).merge(hdr2_cells1[6])
            hdr2_cells1[4].text = case[expect]
            hdr2_cells1[7].merge(hdr2_cells1[8]).merge(hdr2_cells1[9])
            hdr2_cells1[7].text = case[result]
            # hdr2_cells1[8].text = case[ispass]

            #宋体小四加粗
            cell_runs80 = hdr2_cells1[0].paragraphs[0].runs
            cell_runs80[0].font.name = u'宋体'
            r = cell_runs80[0]._element
            r.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
            cell_runs80[0].font.size = Pt(12)
            #第10行
            table3 = document.add_table(rows=4, cols=6, style='Table Grid')

            hdr3_cells = table3.rows[0].cells
            hdr3_cells[0].text = '执行结果'
            hdr3_cells[1].merge(hdr3_cells[2]).merge(hdr3_cells[3]).merge(
                hdr3_cells[4]).merge(hdr3_cells[5])
            hdr3_cells[1].text = case[totalresult]
            #宋体小四加粗
            cell_runs90 = hdr3_cells[0].paragraphs[0].runs
            cell_runs90[0].font.name = u'宋体'
            r = cell_runs90[0]._element
            r.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
            cell_runs90[0].font.size = Pt(12)
            #第11行
            hdr3_cells = table3.rows[1].cells
            hdr3_cells[0].text = '问题标识单'
            hdr3_cells[1].merge(hdr3_cells[2]).merge(hdr3_cells[3]).merge(
                hdr3_cells[4]).merge(hdr3_cells[5])
            hdr3_cells[1].text = case[bugID]
            #宋体小四加粗
            cell_runs100 = hdr3_cells[0].paragraphs[0].runs
            cell_runs100[0].font.name = u'宋体'
            r = cell_runs100[0]._element
            r.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
            cell_runs100[0].font.size = Pt(12)
            #第12行
            hdr3_cells = table3.rows[2].cells
            hdr3_cells[0].text = '执行人员'
            hdr3_cells[1].merge(hdr3_cells[2]).merge(hdr3_cells[3]).merge(
                hdr3_cells[4]).merge(hdr3_cells[5])
            hdr3_cells[1].text = case[testman]
            #宋体小四加粗
            cell_runs110 = hdr3_cells[0].paragraphs[0].runs
            cell_runs110[0].font.name = u'宋体'
            r = cell_runs110[0]._element
            r.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
            cell_runs110[0].font.size = Pt(12)

            #第13行
            hdr3_cells = table3.rows[3].cells
            hdr3_cells[0].text = '测试时间'
            hdr3_cells[1].merge(hdr3_cells[2]).merge(hdr3_cells[3]).merge(
                hdr3_cells[4]).merge(hdr3_cells[5])
            hdr3_cells[1].text = case[testtime]
            #宋体小四加粗
            cell_runs120 = hdr3_cells[0].paragraphs[0].runs
            cell_runs120[0].font.name = u'宋体'
            r = cell_runs120[0]._element
            r.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
            cell_runs120[0].font.size = Pt(12)

            # 添加换行段落
            document.add_paragraph()

            #表格文本全部居中
            # for r in range(0, 8):
            #     handr_cells = table.rows[r].cells
            #     for i in range(len(handr_cells)):
            #         for p in range(len(handr_cells[i].paragraphs)):
            #             handr_cells[i].paragraphs[p].alignment = WD_ALIGN_PARAGRAPH.CENTER

            #测试步骤居中显示
            handr_cells = table.rows[6].cells
            handr_cells[0].paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER

        try:
            document.save(savePathName)
        except (IOError, NameError, FileNotFoundError) as e:
            m_box = QMessageBox()
            m_box.setWindowTitle("提示")
            m_box.setText("保存文件失败!!!" + str(e))
            m_box.exec_()
            return

        process.close()
        self.CreateWordSucess()
示例#38
0
class Pesel2PBNWindow(QMainWindow):
    def __init__(self, networkAccessManager):
        super(Pesel2PBNWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.wykonajButton.clicked.connect(self.startWork)
        self.ui.pastePESEL.clicked.connect(self.pastePESEL)
        self.ui.copyPBN.clicked.connect(self.copyPBN)

        self.ui.oProgramie.clicked.connect(self.aboutBox)

        self.networkAccessManager = networkAccessManager
        self.networkAccessManager.finished.connect(self.finished)

        self.networkResults = {}
        self.progressDialog = None

    def aboutBox(self):
        QMessageBox.about(
            self,
            "O programie",
            "<b>PESEL2PBN</b>"
            "<br>"
            "wersja {wersja}"
            "<p>"
            "(C) 2015 Michał Pasternak &lt;<a href=mailto:[email protected]>[email protected]</a>>"
            "<br>"
            "(C) 2015 <a href=http://iplweb.pl>iplweb.pl</a>"
            "<p>"
            "Program rozpowszechniany jest na zasadach licencji MIT."
            "<br>"
            "Kod źródłowy i issue tracker dostępny na <a href=\"http://github.com/mpasternak/pesel2pbn/\">http://github.com/mpasternak/pesel2pbn</a>".format(
                wersja=VERSION
            )

        )

    def pastePESEL(self):
        cb = QApplication.clipboard()
        value = cb.text(mode=QClipboard.Clipboard)
        self.ui.numeryPESEL.setPlainText(value)

    def copyPBN(self):
        cb = QApplication.clipboard()
        cb.clear(mode=cb.Clipboard)
        cb.setText(self.ui.numeryPBN.toPlainText(), mode=cb.Clipboard)

    def saveSettings(self):
        settings = get_QSettings()
        settings.setValue('token', self.ui.token.text().strip())
        settings.setValue('empty_line', self.ui.emptyLineIfNoPBN.checkState())

    def loadSettings(self):
        settings = get_QSettings()
        self.ui.token.setText(settings.value('token', ''))
        self.ui.emptyLineIfNoPBN.setCheckState(settings.value('empty_line', False))

    def cancelAllRequests(self):
        for reply in self.networkResults.keys():
            if not reply.isFinished():
                reply.abort()
                reply.deleteLater()
        self.networkResults = {}

    def getPESELfromUI(self):
        dane = self.ui.numeryPESEL.toPlainText().split("\n")

        # Pozwól na ostatnią pustą linię
        while dane and dane[-1] == '':
            dane = dane[:-1]

        return dane


    def startWork(self, *args, **kw):
        self.saveSettings()
        self.cancelAllRequests()
        self.ui.numeryPBN.clear()

        for elem in self.networkResults.keys():
            elem.abort()

        if self.progressDialog is not None:
            self.progressDialog.close()

        token = self.ui.token.text()

        if not token.strip():
            QMessageBox.critical(
                self,
                'Problem z tokenem',
                "Wartość token jest pusta. Wpisz token autoryzacyjny.",
                QMessageBox.Ok)
            return

        self.ui.numeryPBN.clear()

        dane = self.getPESELfromUI()
        if not dane:
            QMessageBox.critical(
                self,
                "Brak wpisanych danych",
                "Pole z numerami PESEL jest puste.",
                QMessageBox.Ok)
            return

        for linia in dane:
            if not linia.strip():
                QMessageBox.critical(
                    self,
                    "Problem z danymi wejściowymi",
                    "Proszę, usuń puste linie z listy numerów PESEL.",
                    QMessageBox.Ok)
                return

            if len(linia) != 11:
                QMessageBox.critical(
                    self,
                    "Problem z danymi wejściowymi",
                    "Na liście numerów PESEL znajduje się niepoprawny numer: %s. Skoryguj, proszę, "
                    "dane wejściowe." % linia,
                    QMessageBox.Ok)
                return

        URL = "https://pbn.nauka.gov.pl/data/persons/auth/{token}/pesel.{pesel}/id.pbn"

        for line in dane:
            reply = self.networkAccessManager.get(QNetworkRequest(
                QUrl(URL.format(token=token, pesel=line))))

            self.networkResults[reply] = [line, None]

        self.progressDialog = QProgressDialog("Kontaktuję się z serwerem PBN...", "Anuluj", 0, len(self.networkResults.keys()), self)
        self.progressDialog.setWindowModality(Qt.WindowModal)
        self.progressDialog.setValue(0)
        self.progressDialog.show()
        self.progressDialog.canceled.connect(self.canceled)

    def canceled(self, *args, **kw):
        self.cancelAllRequests()

    def finished(self, reply):

        err = reply.error()

        if err == QNetworkReply.OperationCanceledError:
            return

        BRAK_W_PBN = "Brak w PBN"
        if self.ui.emptyLineIfNoPBN.checkState():
            BRAK_W_PBN = ''


        if err != QNetworkReply.NoError:

            if err == QNetworkReply.ContentOperationNotPermittedError:
                self.cancelAllRequests()
                QMessageBox.critical(
                    self,
                    "Nieprawidłowy token.",
                    "Serwer nie pozwala na połączenia z tym tokenem. Sprawdź, czy token jest wpisany poprawnie. "
                    "Sprawdź również, czy okres jego ważności nie zakończył się. ",
                    QMessageBox.Ok
                )
                self.progressDialog.close()
                return

            elif err == QNetworkReply.ContentNotFoundError:
                buf = BRAK_W_PBN

            else:
                buf = reply.errorString()

        else:

            buf = reply.readAll()

            dane = bytes(buf).decode('utf-8')

            try:
                buf = json.loads(dane)['value']
            except (ValueError, KeyError):
                buf = "Odpowiedź z serwera nie do analizy (%r)" % dane
                pass


        self.networkResults[reply][1] = buf

        self.progressDialog.setValue(self.progressDialog.value() + 1)

        if self.progressDialog.value() == -1:
            self.everythingFinished()

    def everythingFinished(self):
        out = dict((x[0], x[1]) for x in self.networkResults.values())

        for linia in self.getPESELfromUI():
            self.ui.numeryPBN.appendPlainText(out[linia]) # ret)
示例#39
0
class BAONQtApplication(QApplication):
    BACKUP_DIALOG_CAPTION = 'Rename Plan Backup Detected'
    BACKUP_DIALOG_ERROR_CAPTION = 'Error'
    BACKUP_INTRO_TEXT = 'BAON has detected a backed up rename plan from a previous run of the '\
        'application. This suggests that the application crashed partway through executing a rename operation. The '\
        'files may have been left in an inconsistent state.'
    BACKUP_PROMPT_TEXT = 'What do you want to do?'

    REVERT_BACKUP_PROGRESS_TEXT = 'Reverting the rename operation'

    SUCCESS_DIALOG_CAPTION = 'Success'
    WARNING_DIALOG_CAPTION = 'Warning'

    BACKUP_DELETED_DIALOG_TEXT =\
        'The backed up plan has been deleted. Further runs of the application will proceed normally.'
    BACKUP_REVERTED_SUCCESS_DIALOG_TEXT = 'The rename operation has been reverted successfully. The directory state '\
        'should now have been completely restored.'
    BACKUP_REVERTED_WARNING_DIALOG_TEXT = 'There were inconsistencies while trying to revert the previous rename '\
        'operation. The directory state may not have been fully restored.'

    REVERT_BACKUP_BUTTON_TEXT = 'Revert the rename (recommended)'
    DELETE_BACKUP_BUTTON_TEXT = 'Delete the backup file'
    EXAMINE_BACKUP_BUTTON_TEXT = 'Examine the plan in a text editor'
    QUIT_BUTTON_TEXT = 'Quit BAON'

    request_revert_backup = pyqtSignal()
    request_delete_backup = pyqtSignal()

    _main_window = None
    _core = None
    _progress_dialog = None

    _core_thread = None

    def __init__(self, args):
        super().__init__(sys.argv)

        # Actually we do quit when the last window is closed, but we need to do this in a more controlled way
        self.setQuitOnLastWindowClosed(False)

        self._init_threads()
        self._init_main_objects(args)
        self._connect_main_objects()
        self._start_core()

    def event(self, evt):
        if isinstance(evt, QFileOpenEvent):
            path = evt.file()
            if not os.path.isdir(path):
                path, _ = os.path.split(path)

            self._main_window.set_base_path(path)
            return True

        return super().event(evt)

    def _init_threads(self):
        self._core_thread = QThread()
        self._core_thread.start()

    def _init_main_objects(self, args):
        self._main_window = MainWindow(args)

        self._core = BAONQtCore(args)
        self._core.moveToThread(self._core_thread)

    def _connect_main_objects(self):
        self.aboutToQuit.connect(self._on_quit)

        # Core vs. application

        self._core.request_backup_decision.connect(self.backup_decision_requested)
        self._core.reverted_backup.connect(self.notify_backup_reverted)
        self._core.revert_backup_error.connect(self.handle_backup_op_error)
        self._core.deleted_backup.connect(self.notify_backup_deleted)
        self._core.delete_backup_error.connect(self.handle_backup_op_error)

        self.request_revert_backup.connect(self._core.revert_backup)
        self.request_delete_backup.connect(self._core.delete_backup)

        # Core vs. main window

        self._core.prologue_finished.connect(self._main_window.show_first_time)

        self._core.status_changed.connect(self._main_window.report_status)
        self._core.scanned_files_updated.connect(self._main_window.update_scanned_files)
        self._core.renamed_files_updated.connect(self._main_window.update_renamed_files)

        self._core.has_shutdown.connect(self.quit)

        self._main_window.base_path_edited.connect(self._core.update_base_path)
        self._main_window.scan_recursive_changed.connect(self._core.update_scan_recursive)

        self._main_window.rules_text_changed.connect(self._core.update_rules_text)
        self._main_window.use_path_changed.connect(self._core.update_use_path)
        self._main_window.use_extension_changed.connect(self._core.update_use_extension)

        self._main_window.request_add_override.connect(self._core.add_override)
        self._main_window.request_remove_override.connect(self._core.remove_override)

        self._main_window.request_do_rename.connect(self._core.do_rename)
        self._main_window.request_rescan.connect(self._core.rescan)

        self._main_window.rejected.connect(self._core.shutdown)

    def _start_core(self):
        QMetaObject.invokeMethod(self._core, 'start', Qt.QueuedConnection)

    def _on_quit(self):
        self._core_thread.quit()
        self._core_thread.wait()

    @pyqtSlot()
    def backup_decision_requested(self):
        self._show_backup_decision()

    @pyqtSlot(Exception)
    def handle_backup_op_error(self, error):
        self._close_progress_dialog()
        self._show_backup_decision(error=error)

    @pyqtSlot()
    def notify_backup_deleted(self):
        QMessageBox.information(
            None,
            self.SUCCESS_DIALOG_CAPTION,
            self.BACKUP_DELETED_DIALOG_TEXT,
        )

    @pyqtSlot(bool)
    def notify_backup_reverted(self, complete_success):
        self._close_progress_dialog()
        if complete_success:
            QMessageBox.information(
                None,
                self.SUCCESS_DIALOG_CAPTION,
                self.BACKUP_REVERTED_SUCCESS_DIALOG_TEXT,
            )
        else:
            QMessageBox.warning(
                None,
                self.WARNING_DIALOG_CAPTION,
                self.BACKUP_REVERTED_WARNING_DIALOG_TEXT,
            )

    def _show_backup_decision(self, error=None):
        text = '<p>{0}</p><p>{1}</p>'.format(
            self.BACKUP_INTRO_TEXT if error is None else error,
            self.BACKUP_PROMPT_TEXT,
        )

        dialog = QMessageBox(
            QMessageBox.Question if error is None else QMessageBox.Critical,
            self.BACKUP_DIALOG_CAPTION if error is None else self.BACKUP_DIALOG_ERROR_CAPTION,
            text,
        )

        revert_button = dialog.addButton(self.REVERT_BACKUP_BUTTON_TEXT, QMessageBox.AcceptRole)
        delete_button = dialog.addButton(self.DELETE_BACKUP_BUTTON_TEXT, QMessageBox.DestructiveRole)
        examine_button = dialog.addButton(self.EXAMINE_BACKUP_BUTTON_TEXT, QMessageBox.ActionRole)
        dialog.addButton(self.QUIT_BUTTON_TEXT, QMessageBox.RejectRole)

        dialog.exec()
        clicked_button = dialog.clickedButton()

        if clicked_button == examine_button:
            QMetaObject.invokeMethod(self, '_examine_backup', Qt.QueuedConnection)
        elif clicked_button == revert_button:
            self._progress_dialog = QProgressDialog(None)
            self._progress_dialog.setLabelText(self.REVERT_BACKUP_PROGRESS_TEXT)
            self._progress_dialog.setCancelButton(None)
            self._progress_dialog.setRange(0, 0)
            self._progress_dialog.forceShow()

            self.request_revert_backup.emit()
        elif clicked_button == delete_button:
            self.request_delete_backup.emit()
        else:
            self.quit()

    @pyqtSlot()
    def _examine_backup(self):
        error = None
        try:
            filename = get_rename_plan_backup_filename()
            QDesktopServices.openUrl(QUrl.fromLocalFile(filename))
        except Exception as err:
            error = err
        finally:
            self._show_backup_decision(error)

    def _close_progress_dialog(self):
        if self._progress_dialog is not None:
            self._progress_dialog.close()

        self._progress_dialog = None
示例#40
0
class MasterForm(QMainWindow):
    def __init__(self, parent=None):
        super(MasterForm, self).__init__(parent)

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Encrypt/Decrypt button
        self.ui.pushEncrypt.clicked.connect(self.tamponencrypt)
        self.ui.pushDecrypt.clicked.connect(self.tampondecrypt)
        self.ui.pushSign.clicked.connect(self.tamponsign)
        self.ui.pushVerify.clicked.connect(self.tamponverify)

        # Menu connexions
        self.ui.actionCopier.triggered.connect(self.ui.plainTextEdit.copy)
        self.ui.actionColler.triggered.connect(self.ui.plainTextEdit.paste)
        self.ui.actionCut.triggered.connect(self.ui.plainTextEdit.cut)
        self.ui.actionCacher.triggered.connect(self.toolbarvisibility)
        self.ui.actionShow_text_icons.triggered.connect(self.texticonsvisibility)
        self.ui.actionKeymanager.triggered.connect(keymanager)
        self.ui.actionInfos_QPyCrypto.triggered.connect(openabout)
        self.ui.actionInfos_Qt.triggered.connect(self.aboutqt)
        self.ui.actionChiffrerfichier.triggered.connect(self.encryptfile)
        self.ui.actionDechiffrerfichier.triggered.connect(self.decryptfile)

        self.ui.actionChiffrer_un_fichier_Enigma.triggered.connect(self.encryptfileenigma)
        self.ui.actionD_chiffrer_un_fichier_Enigma.triggered.connect(self.decryptfileenigma)

        self.ui.actionSigner_un_fichier.triggered.connect(self.signfile)
        self.ui.actionVerifier_signature.triggered.connect(self.verifysignfile)

        self.ui.actionVider_Tampon.triggered.connect(self.vidertampon)
        self.ui.actionOuvrir.triggered.connect(self.ouvrirtexte)
        self.ui.actionSauver.triggered.connect(self.sauvertexte)
        self.ui.actionQuitter.triggered.connect(sys.exit)

        # Menu HASH File:
        self.ui.actionSHA512.triggered.connect(self.hashfilesha512)
        self.ui.actionSHA384.triggered.connect(self.hashfilesha384)
        self.ui.actionSHA256.triggered.connect(self.hashfilesha256)
        self.ui.actionSHA224.triggered.connect(self.hashfilesha224)
        self.ui.actionSHA_1.triggered.connect(self.hashfilesha)
        self.ui.actionMD5_2.triggered.connect(self.hashfilemd5)
        self.ui.actionMD2.triggered.connect(self.hashfilemd2)
        self.ui.actionMD4.triggered.connect(self.hashfilemd4)
        self.ui.actionRIPEMD_160.triggered.connect(self.hashfileripemd_160)
        self.ui.actionRIPEMD_128.triggered.connect(self.hashfileripemd_128)
        self.ui.actionWhirlpool.triggered.connect(self.hashfileWhirlpool)
        self.ui.actionTiger.triggered.connect(self.hashfileTiger)
        self.ui.actionAdler32.triggered.connect(self.hashfileAdler32)
        self.ui.actionCRC24.triggered.connect(self.hashfileCrc24)
        self.ui.actionCRC32.triggered.connect(self.hashfileCrc32)
        self.ui.actionSHA_3_winner_Keccak_1600.triggered.connect(self.hashfileKeccak_1600)
        self.ui.actionSHA_3_candidate_Skein_512.triggered.connect(self.hashfileSkein_512)
        self.ui.actionGOST_34_11.triggered.connect(self.hashfileGOST_34_11)

    def encryptfileenigma(self):
        filename, _ = QFileDialog.getOpenFileName(self,
                                                  "Select the file to encrypt", "",
                                                  "All Files (*)")
        if filename:
            dialog = Fenselectkey(self)
            if dialog.exec_() == QDialog.Accepted:
                m_key = dialog.ui.EditPass.text()
                algorithm = dialog.ui.comboAlgo.currentText()
                if algorithm == "Serpent-256":
                    algo = "srp"
                if algorithm == "AES-256":
                    algo = "aes"
                if algorithm == "Twofish-256":
                    algo = "twf"

                result = encryptfile(filename, m_key, algo)
                if result["success"] == "successfully encrypted":
                    QMessageBox.information(self, "Successfully encrypted",
                                            "File: " + filename + " is encrypted with " + algorithm,
                                            QMessageBox.Ok)
                else:
                    QMessageBox.information(self, "Encryption Error",
                                            "Encryption error: " + result["success"],
                                            QMessageBox.Ok)

                self.ui.statusbar.showMessage("File " + filename + " is encrypted.", 50000)
                return

    def decryptfileenigma(self):
        filename, _ = QFileDialog.getOpenFileName(self,
                                                  "Select the file to decrypt", "",
                                                  "Cryptoshop Files (*.cryptoshop);;All Files (*)")

        if filename:
            m_key, ok = QInputDialog.getText(self, "Enter your passphrase",
                                             "Key:", QLineEdit.Normal)
            if ok and m_key != '':
                try:
                    result = decryptfile(filename, m_key)
                    if result["success"] == "successfully decrypted":
                        QMessageBox.information(self, "Successfully Decrypted",
                                                "File: " + filename + " encrypted with " + result[
                                                    "algorithm"] + " was successfully decrypted",
                                                QMessageBox.Ok)
                    else:
                        QMessageBox.warning(self, "Decryption Error",
                                            "Decryption Error " + result["success"],
                                            QMessageBox.Ok)

                except Exception as e:
                    QMessageBox.warning(self, appname + version + "What that bug ??", (str(e)), QMessageBox.Ok)

    def signfile(self):
        filename, _ = QFileDialog.getOpenFileName(self,
                                                  "Select a file to sign", "",
                                                  "All files (*)")
        if filename:
            gpg = gnupg.GPG(use_agent=False)
            gpg.encoding = 'utf-8'
            dialog = Fenselectsignkey(self)
            if dialog.exec_() == QDialog.Accepted:
                keyid = dialog.ui.comboBox.currentText()
                key = dialog.ui.editKey.text()
                with open(filename, 'rb') as data:
                    signed_data = gpg.sign_file(file=data, keyid=keyid, output=filename + ".sig", detach=True)
                    print(signed_data)
                    data.close()

    def verifysignfile(self):
        filename, _ = QFileDialog.getOpenFileName(self,
                                                  "Select the sig file", "",
                                                  "sig Files (*.sig);;asc Files (*.asc);;All Files (*)")
        if filename:
            with open(filename, 'rb') as stream:
                gpg = gnupg.GPG(use_agent=False)
                gpg.encoding = 'utf-8'
                data = os.path.splitext(filename)[0].split("_")[-1]
                verified = gpg.verify_file(stream, data)
                stream.close()

            if verified.valid is True:
                QMessageBox.information(self, appname + version + "Good Signature",
                                        "Good signature from:  " + verified.username +
                                        "\n\nFingerprint:  " + verified.fingerprint +
                                        "\nKey Id:  " + verified.key_id +
                                        "\nThe signature was created at " + verified.creation_date + "\n\nTrust  :" + verified.trust_text,
                                        QMessageBox.Ok)
                return
            if verified.valid is False and verified.username is None:
                QMessageBox.warning(self, appname + version + "No signature found",
                                    "No signature found:  " + verified.stderr, QMessageBox.Ok)
                return
            else:
                QMessageBox.warning(self, appname + version + "Bad Signature",
                                    "Bad signature from:  " + verified.username +
                                    "\nKey Id:  " + verified.key_id + "\n\nTHE FILE IS CORRUPTED." + "\n\nDetails  :\n" + verified.stderr,
                                    QMessageBox.Ok)

    def tamponverify(self):
        texttoverify = self.ui.plainTextEdit.toPlainText()
        gpg = gnupg.GPG(use_agent=False)
        gpg.encoding = 'utf-8'
        verified_data = gpg.verify(texttoverify)
        if verified_data.valid is False and verified_data.status is None:
            QMessageBox.warning(self, "No valid signature",
                                "No valid signature.",
                                QMessageBox.Ok)
            return
        if verified_data.valid is False:
            QMessageBox.warning(self, appname + version + "Bad Signature",
                                "BAD SIGNATURE " + "\nDATA ARE CORRUPTED:\n\n" + "GnuPG Message: \n" + verified_data.stderr,
                                QMessageBox.Ok)
            return
        if verified_data.valid is True:
            QMessageBox.information(self, appname + version + "Good Signature",
                                    "Good signature from:  " + verified_data.username +
                                    "\nID " + verified_data.key_id + "\n\nFingerprint: \n"
                                    + verified_data.fingerprint + "\n\nGnuPG Message:\n" + verified_data.stderr,
                                    QMessageBox.Ok)
        else:
            QMessageBox.warning(self, appname + version + "Error",
                                " Error ",
                                QMessageBox.Ok)

    def updatePixmap(self, boll):
        if boll == "False":
            QMessageBox.warning(self, appname + version + "Error",
                                " Wrong passphrase " + self.originalfile,
                                QMessageBox.Ok)
            return
        else:
            self.ui.plainTextEdit.clear()
            self.ui.plainTextEdit.appendPlainText("----------------------------------------------")
            self.ui.plainTextEdit.appendPlainText("Cryptoshop-->The file " + self.originalfile + " is decrypted")
            self.ui.plainTextEdit.appendPlainText(str("----->>>") + self.afterfile)

    def tamponsign(self):
        texttosign = self.ui.plainTextEdit.toPlainText()
        gpg = gnupg.GPG(use_agent=False)
        dialog = Fenselectsignkey(self)
        if dialog.exec_() == QDialog.Accepted:
            key = dialog.ui.comboBox.currentText()
            signed_data = gpg.sign(texttosign, keyid=key)
            if str(signed_data) == "":
                QMessageBox.critical(self, appname + version + "Can't Sign...",
                                     '''The passphrase is invalid for unlock this key.''',
                                     QMessageBox.Ok)
                return
            self.ui.plainTextEdit.clear()
            self.ui.plainTextEdit.appendPlainText(str(signed_data))

    def toolbarvisibility(self):
        if self.ui.actionCacher.isChecked():
            self.ui.toolBar.hide()
        else:
            self.ui.toolBar.show()

    def texticonsvisibility(self):
        if self.ui.actionShow_text_icons.isChecked():
            self.ui.toolBar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        else:
            self.ui.toolBar.setToolButtonStyle(Qt.ToolButtonIconOnly)

    def hidetexticons(self):
        self.ui.toolBar.setToolButtonStyle(Qt.ToolButtonIconOnly)

    def encryptfile(self):
        filename, _ = QFileDialog.getOpenFileName(self,
                                                  "Select file to encrypt", "",
                                                  "All (*)")

        if filename:

            dialog = Fenselectkeygpg(self)

            if dialog.exec_() == QDialog.Accepted:
                m_key = dialog.ui.editKey.text().strip()

                if dialog.ui.checkSymetric.isChecked():
                    if dialog.ui.editKey.text() == "":
                        QMessageBox.warning(self, appname + version + "Error...",
                                            '''You must type a passphrase.''',
                                            QMessageBox.Ok)
                        return
                    encryordecry = True
                    lname = "not used for encrypt"
                    sym = True
                    self.originalfile = filename

                    self.myLongTask = Crypto_gpg.Worker(filename, m_key, encryordecry, lname, sym)
                    self.myLongTask.renderedImage.connect(self.updatePixmap)
                    self.myLongTask.isstarted.connect(self.isstarted)

                    self.myLongTask.start()

                    QMessageBox.warning(self, appname + version + "The file is encrypted",
                                        filename + ".gpg",
                                        QMessageBox.Ok)

                else:
                    sym = False
                    item = dialog.ui.comboBox.currentText()
                    print(item)
                    gpg = gnupg.GPG(use_agent=False)
                    keylist = gpg.list_keys()

                    uid_strings = []
                    uid_string2key = {}
                    for key in keylist:
                        for uid_string in key['uids']:
                            uid_strings.append(uid_string)
                            uid_string2key[uid_string] = key
                    uid = item
                    m_key = uid_string2key[uid]
                    encryordecry = True
                    lname = "not used for encrypt"
                    sym = False
                    self.myLongTask = Crypto_gpg.Worker(filename, m_key, encryordecry, lname, sym)
                    self.myLongTask.renderedImage.connect(self.updatePixmap)
                    self.myLongTask.isstarted.connect(self.isstarted)

                    self.myLongTask.start()

                    self.ui.plainTextEdit.clear()
                    self.ui.plainTextEdit.appendPlainText("----------------------------------------------")
                    self.ui.plainTextEdit.appendPlainText("Cryptoshop-->The file is encrypted.")
                    self.ui.plainTextEdit.appendPlainText(str(filename + ".gpg"))

    def aboutqt(self):
        QMessageBox.aboutQt(self, appname + version + "Qt is the best !")

    def tamponencrypt(self):
        dialog = Fenselectkeygpg(self)

        if dialog.exec_() == QDialog.Accepted:
            self.m_key = dialog.ui.editKey.text().strip()
            if dialog.ui.checkSymetric.isChecked():
                if dialog.ui.editKey.text() == "":
                    QMessageBox.warning(self, appname + version + "Error",
                                        '''You must type a passphrase.''',
                                        QMessageBox.Ok)
                    return

                gpg = gnupg.GPG(use_agent=False)
                plaintext = self.ui.plainTextEdit.toPlainText()
                crypted = gpg.encrypt(plaintext, False, passphrase=self.m_key, symmetric='AES256',
                                      armor=True)
                self.ui.plainTextEdit.clear()
                self.ui.plainTextEdit.appendPlainText(str(crypted))

            else:
                item = dialog.ui.comboBox.currentText()
                print(item)
                gpg = gnupg.GPG()
                keylist = gpg.list_keys()

                uid_strings = []
                uid_string2key = {}

                for key in keylist:
                    for uid_string in key['uids']:
                        uid_strings.append(uid_string)
                        uid_string2key[uid_string] = key

                uid = item
                key = uid_string2key[uid]
                unencrypted_string = self.ui.plainTextEdit.toPlainText()
                encrypted_data = gpg.encrypt(unencrypted_string, key['fingerprint'], always_trust=True)
                encrypted_string = str(encrypted_data)
                self.ui.plainTextEdit.clear()
                self.ui.plainTextEdit.appendPlainText(encrypted_string)

    def sauvertexte(self):
        filename, _ = QFileDialog.getSaveFileName(self)
        if filename:
            file = QFile(filename)
            if not file.open(QFile.WriteOnly | QFile.Text):
                QMessageBox.critical(self, appname + version + "Save",
                                     "Writing Error %s:\n%s." % (filename, file.errorString()))
                return
            outstr = QTextStream(file)
            outstr << self.ui.plainTextEdit.toPlainText()
            QMessageBox.information(self, appname + version + "Save file",
                                    "The file is saved. \n%s" % (file.fileName()))

    def ouvrirtexte(self):
        filename, _ = QFileDialog.getOpenFileName(self)
        if filename:
            file = QFile(filename)
            if not file.open(QFile.ReadOnly | QFile.Text):
                QMessageBox.critical(self, appname + version + "Open File",
                                     "Reading Error %s:\n%s." % (filename, file.errorString()))
                return
            instr = QTextStream(file)
            self.ui.plainTextEdit.setPlainText(instr.readAll())

    def vidertampon(self):
        self.ui.plainTextEdit.clear()

    def tampondecrypt(self):
        encrypted_string = str(self.ui.plainTextEdit.toPlainText())
        gpg = gnupg.GPG(use_agent=False)

        decrypted_data = gpg.decrypt(encrypted_string)

        if decrypted_data.ok is True:
            self.ui.plainTextEdit.clear()
            self.ui.plainTextEdit.appendPlainText(str(decrypted_data))
        else:
            QMessageBox.warning(self, appname + version + "Invalid passphrase",
                                ''' Invalid passphrase.''',
                                QMessageBox.Ok)
            return

    def hashfileripemd_160(self):
        filename, _ = QFileDialog.getOpenFileName(self,
                                                  "RIPEMD-160: Select File", "",
                                                  "All Files (*);;Text Files (*.txt)")
        if filename:
            output = simplehash.get_file_checksum(filename, 'RIPEMD-160')
            self.ui.plainTextEdit.clear()
            self.ui.plainTextEdit.appendPlainText("----------------------------------------------")
            self.ui.plainTextEdit.appendPlainText("Hash RIPEMD-160 -->" + filename)
            self.ui.plainTextEdit.appendPlainText(output)

    def hashfileripemd_128(self):
        filename, _ = QFileDialog.getOpenFileName(self,
                                                  "RIPEMD-128: Select File", "",
                                                  "All Files (*);;Text Files (*.txt)")
        if filename:
            output = simplehash.get_file_checksum(filename, 'RIPEMD-128')
            self.ui.plainTextEdit.clear()
            self.ui.plainTextEdit.appendPlainText("----------------------------------------------")
            self.ui.plainTextEdit.appendPlainText("Hash RIPEMD-128 -->" + filename)
            self.ui.plainTextEdit.appendPlainText(output)

    def hashfilemd2(self):
        filename, _ = QFileDialog.getOpenFileName(self,
                                                  "MD2: Select File", "",
                                                  "All Files (*);;Text Files (*.txt)")
        if filename:
            output = simplehash.get_file_checksum(filename, 'MD2')
            self.ui.plainTextEdit.clear()
            self.ui.plainTextEdit.appendPlainText("----------------------------------------------")
            self.ui.plainTextEdit.appendPlainText("Hash MD2 -->" + filename)
            self.ui.plainTextEdit.appendPlainText(output)

    def hashfilemd4(self):
        filename, _ = QFileDialog.getOpenFileName(self,
                                                  "MD4: Select File", "",
                                                  "All Files (*);;Text Files (*.txt)")
        if filename:
            output = simplehash.get_file_checksum(filename, 'MD4')
            self.ui.plainTextEdit.clear()
            self.ui.plainTextEdit.appendPlainText("----------------------------------------------")
            self.ui.plainTextEdit.appendPlainText("Hash MD4 -->" + filename)
            self.ui.plainTextEdit.appendPlainText(output)

    def hashfilemd5(self):
        filename, _ = QFileDialog.getOpenFileName(self,
                                                  "MD5: Select File", "",
                                                  "All Files (*);;Text Files (*.txt)")
        if filename:
            output = simplehash.get_file_checksum(filename, 'MD5')
            self.ui.plainTextEdit.clear()
            self.ui.plainTextEdit.appendPlainText("----------------------------------------------")
            self.ui.plainTextEdit.appendPlainText("Hash MD5 -->" + filename)
            self.ui.plainTextEdit.appendPlainText(output)

    def hashfilesha512(self):
        filename, _ = QFileDialog.getOpenFileName(self,
                                                  "SHA-512: Select File", "",
                                                  "All Files (*);;Text Files (*.txt)")
        if filename:
            output = simplehash.get_file_checksum(filename, 'SHA-512')
            self.ui.plainTextEdit.clear()
            self.ui.plainTextEdit.appendPlainText("----------------------------------------------")
            self.ui.plainTextEdit.appendPlainText("Hash SHA-512 -->" + filename)
            self.ui.plainTextEdit.appendPlainText(output)

    def hashfilesha384(self):
        filename, _ = QFileDialog.getOpenFileName(self,
                                                  "SHA-384: Select File", "",
                                                  "All Files (*);;Text Files (*.txt)")
        if filename:
            output = simplehash.get_file_checksum(filename, 'SHA-384')
            self.ui.plainTextEdit.clear()
            self.ui.plainTextEdit.appendPlainText("----------------------------------------------")
            self.ui.plainTextEdit.appendPlainText("Hash SHA-384 -->" + filename)
            self.ui.plainTextEdit.appendPlainText(output)

    def hashfilesha256(self):
        filename, _ = QFileDialog.getOpenFileName(self,
                                                  "SHA-256: Select File", "",
                                                  "All Files (*);;Text Files (*.txt)")
        if filename:
            output = simplehash.get_file_checksum(filename, 'SHA-256')
            self.ui.plainTextEdit.clear()
            self.ui.plainTextEdit.appendPlainText("----------------------------------------------")
            self.ui.plainTextEdit.appendPlainText("Hash SHA-256 -->" + filename)
            self.ui.plainTextEdit.appendPlainText(output)

    def hashfilesha224(self):
        filename, _ = QFileDialog.getOpenFileName(self,
                                                  "SHA-224: Select File", "",
                                                  "All Files (*);;Text Files (*.txt)")
        if filename:
            output = simplehash.get_file_checksum(filename, 'SHA-224')
            self.ui.plainTextEdit.clear()
            self.ui.plainTextEdit.appendPlainText("----------------------------------------------")
            self.ui.plainTextEdit.appendPlainText("Hash SHA-224 -->" + filename)
            self.ui.plainTextEdit.appendPlainText(output)

    def hashfilesha(self):
        filename, _ = QFileDialog.getOpenFileName(self,
                                                  "SHA-1: Select File", "",
                                                  "All Files (*);;Text Files (*.txt)", )
        if filename:
            output = simplehash.get_file_checksum(filename, 'SHA-1')
            self.ui.plainTextEdit.clear()
            self.ui.plainTextEdit.appendPlainText("----------------------------------------------")
            self.ui.plainTextEdit.appendPlainText("Hash SHA-1 -->" + filename)
            self.ui.plainTextEdit.appendPlainText(output)

    def hashfileWhirlpool(self):
        filename, _ = QFileDialog.getOpenFileName(self,
                                                  "Whirlpool: Select File", "",
                                                  "All Files (*);;Text Files (*.txt)", )
        if filename:
            output = simplehash.get_file_checksum(filename, 'Whirlpool')
            self.ui.plainTextEdit.clear()
            self.ui.plainTextEdit.appendPlainText("----------------------------------------------")
            self.ui.plainTextEdit.appendPlainText("Hash Whirlpool -->" + filename)
            self.ui.plainTextEdit.appendPlainText(output)

    def hashfileTiger(self):
        filename, _ = QFileDialog.getOpenFileName(self,
                                                  "Tiger: Select File", "",
                                                  "All Files (*);;Text Files (*.txt)", )
        if filename:
            output = simplehash.get_file_checksum(filename, 'Tiger')
            self.ui.plainTextEdit.clear()
            self.ui.plainTextEdit.appendPlainText("----------------------------------------------")
            self.ui.plainTextEdit.appendPlainText("Hash Tiger -->" + filename)
            self.ui.plainTextEdit.appendPlainText(output)

    def hashfileAdler32(self):
        filename, _ = QFileDialog.getOpenFileName(self,
                                                  "Adler32: Select File", "",
                                                  "All Files (*);;Text Files (*.txt)", )
        if filename:
            output = simplehash.get_file_checksum(filename, 'Adler32')
            self.ui.plainTextEdit.clear()
            self.ui.plainTextEdit.appendPlainText("----------------------------------------------")
            self.ui.plainTextEdit.appendPlainText("Hash Adler32 -->" + filename)
            self.ui.plainTextEdit.appendPlainText(output)

    def hashfileCrc24(self):
        filename, _ = QFileDialog.getOpenFileName(self,
                                                  "Crc24: Select File", "",
                                                  "All Files (*);;Text Files (*.txt)", )
        if filename:
            output = simplehash.get_file_checksum(filename, 'CRC24')
            self.ui.plainTextEdit.clear()
            self.ui.plainTextEdit.appendPlainText("----------------------------------------------")
            self.ui.plainTextEdit.appendPlainText("Hash CRC24 -->" + filename)
            self.ui.plainTextEdit.appendPlainText(output)

    def hashfileCrc32(self):
        filename, _ = QFileDialog.getOpenFileName(self,
                                                  "Crc32: Select File", "",
                                                  "All Files (*);;Text Files (*.txt)", )
        if filename:
            output = simplehash.get_file_checksum(filename, 'CRC32')
            self.ui.plainTextEdit.clear()
            self.ui.plainTextEdit.appendPlainText("----------------------------------------------")
            self.ui.plainTextEdit.appendPlainText("Hash CRC32 -->" + filename)
            self.ui.plainTextEdit.appendPlainText(output)

    def hashfileKeccak_1600(self):
        filename, _ = QFileDialog.getOpenFileName(self,
                                                  "SHA-3 Keccak-1600: Select File", "",
                                                  "All Files (*);;Text Files (*.txt)", )
        if filename:
            output = simplehash.get_file_checksum(filename, 'Keccak-1600')
            self.ui.plainTextEdit.clear()
            self.ui.plainTextEdit.appendPlainText("----------------------------------------------")
            self.ui.plainTextEdit.appendPlainText("Hash SHA-3 Keccak-1600 -->" + filename)
            self.ui.plainTextEdit.appendPlainText(output)

    def hashfileSkein_512(self):
        filename, _ = QFileDialog.getOpenFileName(self,
                                                  "Skein_512: Select File", "",
                                                  "All Files (*);;Text Files (*.txt)", )
        if filename:
            output = simplehash.get_file_checksum(filename, 'Skein-512')
            self.ui.plainTextEdit.clear()
            self.ui.plainTextEdit.appendPlainText("----------------------------------------------")
            self.ui.plainTextEdit.appendPlainText("Hash Skein-512 -->" + filename)
            self.ui.plainTextEdit.appendPlainText(output)

    def hashfileGOST_34_11(self):
        filename, _ = QFileDialog.getOpenFileName(self,
                                                  "GOST 34.11: Select File", "",
                                                  "All Files (*);;Text Files (*.txt)", )
        if filename:
            output = simplehash.get_file_checksum(filename, 'GOST-34.11')
            self.ui.plainTextEdit.clear()
            self.ui.plainTextEdit.appendPlainText("----------------------------------------------")
            self.ui.plainTextEdit.appendPlainText("Hash GOST 34.11 -->" + filename)
            self.ui.plainTextEdit.appendPlainText(output)

    def decryptfile(self):
        filename, _ = QFileDialog.getOpenFileName(self,
                                                  "Select encrypted file", "",
                                                  "GPG files (*.gpg);;Tous (*)")
        if filename:
            m_key, ok = QInputDialog.getText(self, "Enter your passphrase",
                                             "Key:", QLineEdit.Normal)
            if ok and m_key != '':
                lname = os.path.splitext(filename)[0].split("_")[-1]

                self.originalfile = filename
                self.afterfile = lname
                encryordecry = False
                sym = False

                self.myLongTask = Crypto_gpg.Worker(filename, m_key, encryordecry, lname, sym)
                self.myLongTask.renderedImage.connect(self.updatePixmap)
                self.myLongTask.isstarted.connect(self.isstarted)
                self.myLongTask.start()

            else:
                QMessageBox.warning(self, appname + version + "Error",
                                    ''' You must enter a passphrase ''',
                                    QMessageBox.Ok)

    def isstarted(self, status):
        if status == "True":
            self.progress = QProgressDialog("Work in progress...", "Cancel", 0, 0)
            self.progress.setWindowTitle(appname + version)
            self.progress.setWindowModality(Qt.ApplicationModal)
            self.progress.exec()
        else:
            self.progress.close()
示例#41
0
def load_airport_data():
    if os.path.isfile('data/global/apt.p'):
        f_vdata       = open('data/global/apt.p', 'rb')
        vbuf_asphalt  = pickle.load(f_vdata)
        vbuf_concrete = pickle.load(f_vdata)
        vbuf_runways  = pickle.load(f_vdata)
        apt_ctr_lat   = pickle.load(f_vdata)
        apt_ctr_lon   = pickle.load(f_vdata)
        apt_indices   = pickle.load(f_vdata)
        f_vdata.close()
    else:
        pb = QProgressDialog('Binary buffer file not found, or file out of date: Constructing vertex buffers from geo data.', 'Cancel', 0, 100)
        pb.setWindowFlags(Qt.WindowStaysOnTopHint)
        pb.show()

        REARTH_INV    = 1.56961231e-7
        runways       = []
        asphalt       = PolygonSet()
        concrete      = PolygonSet()
        cur_poly      = asphalt
        apt_indices   = []
        apt_ctr_lat   = []
        apt_ctr_lon   = []
        apt_bb        = None
        count         = 0
        bytecount     = 0
        #fsize         = os.stat('data/global/apt.dat').st_size
        zfile = ZipFile('data/global/apt.zip')
        fsize = float(zfile.getinfo('apt.dat').file_size)
        with zfile.open('apt.dat', 'r') as f:
            for line in f:
                bytecount += len(line)
                # Check how far we are
                count += 1
                if count % 1000 == 0:
                    pb.setValue((bytecount / fsize * 100.0))
                    QApplication.processEvents()

                elems = line.strip().split()
                if len(elems) == 0:
                    continue

                # 1: AIRPORT
                if elems[0] == '1':
                    cur_poly.end()
                    if len(apt_indices) > 0:
                        # Store the number of vertices per airport
                        apt_indices[-1][1] = asphalt.bufsize()  / 2 - apt_indices[-1][0]
                        apt_indices[-1][3] = concrete.bufsize() / 2 - apt_indices[-1][2]

                    # Store the starting vertex index for the next airport
                    apt_indices.append([asphalt.bufsize() / 2, 0, concrete.bufsize() / 2, 0])
                    apt_ctr_lat.append(0.0)
                    apt_ctr_lon.append(0.0)
                    continue

                # 100: LAND RUNWAY
                if elems[0] == '100':
                    width = float(elems[1])
                    # Only asphalt and concrete runways
                    if int(elems[2]) > 2:
                        continue
                    # rwy_lbl = (elems[8], elems[17])
                    lat0 = float(elems[9])
                    lon0 = float(elems[10])
                    lat1 = float(elems[18])
                    lon1 = float(elems[19])
                    flat_earth = cos(0.5 * radians(lat0 + lat1))
                    lx = lat1 - lat0
                    ly = (lon1 - lon0) * flat_earth
                    l  = sqrt(lx * lx + ly * ly)
                    wx =  ly / l * 0.5 * width
                    wy = -lx / l * 0.5 * width
                    dlat = degrees(wx * REARTH_INV)
                    dlon = degrees(wy * REARTH_INV / flat_earth)
                    runways.extend([ lat0 + dlat, lon0 + dlon,
                                    lat0 - dlat, lon0 - dlon,
                                    lat1 + dlat, lon1 + dlon,
                                    lat0 - dlat, lon0 - dlon,
                                    lat1 + dlat, lon1 + dlon,
                                    lat1 - dlat, lon1 - dlon])
                    continue

                # 110: TAXIWAY/PAVEMENT: Start of polygon contour
                if elems[0] == '110':
                    cur_poly.end()
                    if elems[1] == '1':
                        cur_poly = asphalt
                        cur_poly.begin()
                    elif elems[1] == '2':
                        cur_poly = concrete
                        cur_poly.begin()
                    continue

                # 130: AIRPORT BOUNDARY
                if elems[0] == '130':
                    cur_poly.end()
                    apt_bb      = BoundingBox()
                    continue

                if cur_poly.in_poly is False and apt_bb is None:
                    continue

                controlpoint = None
                # Straight line (111) or bezier line (112) in contour
                if elems[0] == '111' or elems[0] == '112':
                    vertex           = np.array((float(elems[1]), float(elems[2]), 0.0))
                    if apt_bb is not None:
                        apt_bb.update(vertex)
                        continue
                    if elems[0] == '112':
                        controlpoint = np.array((float(elems[3]), float(elems[4]), 0.0))

                    cur_poly.addVertex(vertex, controlpoint)

                # Straight (113) or bezier (114) contour endpoint
                elif elems[0] == '113' or elems[0] == '114':
                    vertex           = np.array((float(elems[1]), float(elems[2]), 0.0))
                    if apt_bb is not None:
                        apt_bb.update(vertex)
                        apt_ctr_lat[-1], apt_ctr_lon[-1] = apt_bb.center()
                        apt_bb = None
                        continue
                    if elems[0] == '114':
                        controlpoint = np.array((float(elems[3]), float(elems[4]), 0.0))

                    cur_poly.addVertex(vertex, controlpoint)

                    cur_poly.endContour()

                else:
                    cur_poly.end()

        # Clean up:
        cur_poly.end()
        apt_indices[-1][1] = asphalt.bufsize()  / 2 - apt_indices[-1][0]
        apt_indices[-1][3] = concrete.bufsize() / 2 - apt_indices[-1][2]

        # Store in binary pickle file
        vbuf_asphalt  = np.array(asphalt.vbuf, dtype=np.float32)
        vbuf_concrete = np.array(concrete.vbuf, dtype=np.float32)
        vbuf_runways  = np.array(runways, dtype=np.float32)
        apt_ctr_lat   = np.array(apt_ctr_lat)
        apt_ctr_lon   = np.array(apt_ctr_lon)
        apt_indices   = np.array(apt_indices)

        f = open('data/global/apt.p', 'wb')
        pickle.dump(vbuf_asphalt, f, 2)
        pickle.dump(vbuf_concrete, f, 2)
        pickle.dump(vbuf_runways , f, 2)
        pickle.dump(apt_ctr_lat  , f, 2)
        pickle.dump(apt_ctr_lon  , f, 2)
        pickle.dump(apt_indices  , f, 2)
        f.close()

        # Close the progress dialog
        pb.close()

    # return the data
    return vbuf_asphalt, vbuf_concrete, vbuf_runways, apt_ctr_lat, apt_ctr_lon, apt_indices