示例#1
0
    def import_from_excel(self):
        msg_box = QMessageBox()
        msg_box.setText(
            "Use one of the available templates to import your collection from an Excel spreadsheet."
        )
        msg_box.setInformativeText(
            "Note: do not change the filename of the template.")
        msg_box.setStandardButtons(QMessageBox.Open | QMessageBox.Cancel)
        expanded = msg_box.addButton('Create Expanded...',
                                     QMessageBox.ApplyRole)
        condensed = msg_box.addButton('Create Condensed...',
                                      QMessageBox.ApplyRole)
        msg_box.setDefaultButton(QMessageBox.Cancel)
        ret = msg_box.exec_()

        if msg_box.clickedButton() == expanded:
            path = QFileDialog.getExistingDirectory(
                self, "Select Directory for Template...") + '/'
            import_export.generate_sheet(path, expanded=True)
        elif msg_box.clickedButton() == condensed:
            path = QFileDialog.getExistingDirectory(
                self, "Select Directory for Template...") + '/'
            import_export.generate_sheet(path, expanded=False)
        elif ret == QMessageBox.Open:
            path = QFileDialog.getOpenFileName(
                self, "Select Filled-Out Template...")
            import_export.import_db(path[0])
示例#2
0
 def confirmSupprEle(self):
     print("confirm suppr")
     msgSuppr = QMessageBox()
     msgSuppr.setWindowTitle("Suppression")
     msgSuppr.setText("Confirmer la suppression de l'élève: {}".format(self.ui2.BDcbEleSupprSelectNom.currentText()))
     msgSuppr.setStandardButtons(QMessageBox.Yes| QMessageBox.No)
     buttonY = msgSuppr.button(QMessageBox.Yes)
     buttonN = msgSuppr.button(QMessageBox.No)
     msgSuppr.exec()
     if msgSuppr.clickedButton() == buttonY:
         self.supprEle()
     elif msgSuppr.clickedButton() == buttonN:
         pass
示例#3
0
 def confirmModifEle(self):
     print("confirm modif")
     msgModif = QMessageBox()
     msgModif.setWindowTitle("Modification")
     msgModif.setText(
         "Confirmer la modification de l'élève: {}".format(self.ui2.BDcbEleModifSelectNom.currentText()))
     msgModif.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
     buttonY= msgModif.button(QMessageBox.Yes)
     buttonN= msgModif.button(QMessageBox.No)
     msgModif.exec()
     if msgModif.clickedButton() == buttonY:
         self.modifEle()
     elif msgModif.clickedButton() == buttonN:
         pass
示例#4
0
 def confirm_negative_start_time(self,
                                 negative_starts: List[Package]) -> bool:
     formatted = '<br />'.join([
         f"{p.primary_task.name} {p.target.name}" for p in negative_starts
     ])
     mbox = QMessageBox(
         QMessageBox.Question,
         "Continue with past start times?",
         ("Some flights in the following packages have start times set "
          "earlier than mission start time:<br />"
          "<br />"
          f"{formatted}<br />"
          "<br />"
          "Flight start times are estimated based on the package TOT, so it "
          "is possible that not all flights will be able to reach the "
          "target area at their assigned times.<br />"
          "<br />"
          "You can either continue with the mission as planned, with the "
          "misplanned flights potentially flying too fast and/or missing "
          "their rendezvous; automatically fix negative TOTs; or cancel "
          "mission start and fix the packages manually."),
         parent=self)
     auto = mbox.addButton("Fix TOTs automatically", QMessageBox.ActionRole)
     ignore = mbox.addButton("Continue without fixing",
                             QMessageBox.DestructiveRole)
     cancel = mbox.addButton(QMessageBox.Cancel)
     mbox.setEscapeButton(cancel)
     mbox.exec_()
     clicked = mbox.clickedButton()
     if clicked == auto:
         self.fix_tots(negative_starts)
         return True
     elif clicked == ignore:
         return True
     return False
示例#5
0
 def _try_installing_ijulia(self):
     """Prompts user to install IJulia."""
     # First find out active project to ask user's permission to change it
     program = "{0}".format(self.julia_exe)
     args = list()
     args.append(f"--project={self.julia_project_path}")
     args.append("-e")
     args.append("println(Base.active_project())")
     exec_mngr = QProcessExecutionManager(self._toolbox,
                                          program,
                                          args,
                                          silent=True)
     exec_mngr.start_execution()
     if not exec_mngr.wait_for_process_finished(msecs=5000):
         self._toolbox.msg_error.emit(
             "\tCouldn't find out Julia active project. "
             "Make sure that Julia is correctly installed and try again.")
         self.execution_failed.emit(-1)
         return
     julia_active_project = exec_mngr.process_output
     msg = QMessageBox(parent=self._toolbox)
     msg.setIcon(QMessageBox.Question)
     msg.setWindowTitle("IJulia installation needed")
     msg.setText(
         "Spine Toolbox needs to do the following modifications to the Julia project at <b>{0}</b>:"
         "<p>Install the IJulia package.".format(julia_active_project))
     allow_button = msg.addButton("Allow", QMessageBox.YesRole)
     msg.addButton("Cancel", QMessageBox.RejectRole)
     msg.exec_()  # Show message box
     if msg.clickedButton() != allow_button:
         self.starting = False
         self._control.viewport().setCursor(self.normal_cursor)
         self.execution_failed.emit(-1)
         return
     self._do_try_installing_ijulia()
 def export_alleles():
     msgBox = QMessageBox(QApplication.activeWindow())
     msgBox.setText("Data export")
     msgBox.setInformativeText("What would you like to export?")
     exp_orig = msgBox.addButton("Original Data", QMessageBox.ActionRole)
     exp_renamed = msgBox.addButton("Renamed Alleles Data",
                                    QMessageBox.ActionRole)
     if len(Data.mod_alleles_dict) == 0:
         msgBox.removeButton(msgBox.buttons()[1])
     msgBox.addButton(QMessageBox.Cancel)
     export = True
     msgBox.exec_()
     if msgBox.clickedButton() == exp_orig:
         data = Data.orig_alleles_dict
         print("Exporting renames alleles data...")
     elif msgBox.clickedButton() == exp_renamed:
         data = Data.mod_alleles_dict
         print("Exporting renamed alleles data...")
     else:
         export = False
         print("Cancel")
     if export:
         try:
             path, _ = QFileDialog().getSaveFileName(
                 QApplication.activeWindow(), filter='*.csv')
             df = DataFrame.from_dict(
                 data,
                 orient='index',
                 columns=['marker_id', 'allele', 'marker_name'])
             df = df.drop(labels="marker_id", axis=1)
             df = df.reindex(columns=["marker_name", "allele"])
             df.to_csv(path_or_buf=path,
                       sep="\t",
                       header=False,
                       index=False)
             #with ExcelWriter(path) as writer:
             #  df.to_excel(writer)
             QMessageBox.information(
                 GraphicalGenotypeController.ui, "Info",
                 "Export Success\nAlleles data was "
                 "exported successfully to path")
         except ():
             QMessageBox.information(
                 GraphicalGenotypeController.ui, "Warning",
                 "Export Failed\nAn error has occurred!")
示例#7
0
    def action_apply(self):
        """
        Apply parameters to relevant .nif files
        """
        if self.nif_files_list_widget.count() == 0:
            QMessageBox.warning(self, "No .nif files loaded",
                                "Don't forget to load .nif files !")
            return

        if self.nif_files_list_widget.count() >= get_config().getint(
                "DEFAULT", "softLimit"):
            box = QMessageBox()
            box.setIcon(QMessageBox.Question)
            box.setWindowTitle('Are you sure ?')
            box.setText(
                "The tool may struggle with more than 100 .nif files at once. We advise you to process small batches.\n\nAre you sure you wish to continue ?"
            )
            box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
            buttonY = box.button(QMessageBox.Yes)
            buttonY.setText('Yes')
            buttonN = box.button(QMessageBox.No)
            buttonN.setText('No')
            box.exec_()

            if box.clickedButton() == buttonN:
                return

        log.info("Applying parameters to " +
                 str(self.nif_files_list_widget.count()) + " files ...")
        self.toggle(False)
        self.progress_bar.setValue(0)
        self.processed_files = itertools.count()

        CONFIG.set("NIF", "Glossiness", str(self.spin_box_glossiness.value())),
        CONFIG.set("NIF", "SpecularStrength",
                   str(self.spin_box_specular_strength.value())),
        save_config()

        QMessageBox.warning(
            self, "Attention !",
            "The process is quite slow.\n\nThe gui will be mostly unresponsive to your input. Don't close the application, unless the completion pourcentage has not been updated in a long time (several minutes).\nIt took me 13 minutes to process 100 files for example."
        )

        #for indices in chunkify(range(self.nif_files_list_widget.count()), QThreadPool.globalInstance().maxThreadCount()-1):
        QThreadPool.globalInstance().setExpiryTimeout(-1)
        for index in range(self.nif_files_list_widget.count()):
            item = self.nif_files_list_widget.item(index)
            worker = NifProcessWorker(
                index=index,
                path=item.text(),
                keywords=self.keywords,
                glossiness=self.spin_box_glossiness.value(),
                specular_strength=self.spin_box_specular_strength.value())
            worker.signals.start.connect(self.start_apply_action)
            worker.signals.result.connect(self.result_apply_action)
            worker.signals.finished.connect(self.finish_apply_action)
            QThreadPool.globalInstance().start(worker)
示例#8
0
    def draw_pajek():
        msgBox = QMessageBox(QApplication.activeWindow())
        msgBox.setText("Plot network with Pajek")
        msgBox.setInformativeText("Which network would you like to plot?")
        net_plot = msgBox.addButton("Network", QMessageBox.ActionRole)
        mst_plot = msgBox.addButton("MST of Network", QMessageBox.ActionRole)
        plot = True
        if Data.network.mst == None:
            msgBox.removeButton(msgBox.buttons()[1])
        msgBox.addButton(QMessageBox.Cancel)
        msgBox.exec_()
        if msgBox.clickedButton() == net_plot:
            to_plot = Data.network
            print("Plotting network with Pajek...")
        elif msgBox.clickedButton() == mst_plot:
            to_plot = Data.network.mst
            print("Plotting MST with Pajek...")
        else:
            plot = False
            print("Cancel")

        if plot:
            pajek_path = os.getcwd() + '\Pajek64\Pajek.exe'
            try:
                path, _ = QFileDialog().getSaveFileName(
                    QApplication.activeWindow(), filter='*.net')
                Network.print_pajek_network(plot_net=to_plot, sFileName=path)
                QMessageBox.information(
                    NetworkTabController.ui, "Info", "Save Success\nMap "
                    "was successfully saved to path")
            except ():
                QMessageBox.information(NetworkTabController.ui, "Warning",
                                        "Save Failed\nAn error has occurred!")

            NetworkTabController.ui.log_plainTextEdit.appendPlainText(
                f"Network was exported to Pajek format successfully"
                f"\n\t#Nodes: {len(to_plot.nodes)}"
                f"\n\t#Edges: {len(to_plot.edges)}"
                f"\n\tNetwork save path: {path}\n")

            subprocess.Popen([pajek_path, path])
示例#9
0
 def closeEvent(self, event):
     print("confirm exit")
     msgExit = QMessageBox()
     msgExit.setWindowTitle("exit")
     msgExit.setText("Voulez-vous sauvegarder les changements effectués avant de quitter ?")
     msgExit.setStandardButtons(QMessageBox.Save | QMessageBox.Cancel | QMessageBox.Discard)
     buttonS = msgExit.button(QMessageBox.Save)
     buttonD = msgExit.button(QMessageBox.Discard)
     buttonC = msgExit.button(QMessageBox.Cancel)
     msgExit.exec()
     if msgExit.clickedButton() == buttonS:
         print("save")
         # self.sauveJSON(filename)
         self.upd.emit()
         event.accept()
     elif msgExit.clickedButton() == buttonD:
         print("discard")
         event.accept()
     elif msgExit.clickedButton() == buttonC:
         print("cancel")
         event.ignore()
示例#10
0
def msgbox(message_text,
           title=None,
           icon=None,
           buttons=None,
           parent=None,
           default_index=-1,
           enable_close_button=False):
    '''
    Show message_text to user and wait until window will be closed

    @param icon: message box can also have one of standart icon
        QMessageBox.NoIcon
        QMessageBox.Question
        QMessageBox.Information
        QMessageBox.Warning
        QMessageBox.Critical

    @param buttoons: You can pass list of tuples (caption, result) to specify
        which buttons will be shown on the messagebox window.
        appropriate 'result' value of pushed button is returned as result.
        By default only one OK button is shown with empty string as result

    @return 'result' value of pushed button or empty string
    '''
    mymessage = QMessageBox(parent)
    if title:
        mymessage.setWindowTitle(title)
    else:
        mymessage.setWindowTitle(tr("Pvtbox"))
    mymessage.setText(str(message_text))

    results = {}
    if buttons:
        for i, (caption, result) in enumerate(buttons):
            btn = mymessage.addButton(caption, QMessageBox.ActionRole)
            if i == default_index:
                mymessage.setDefaultButton(btn)
            results[btn] = result

    if enable_close_button:
        close_btn = mymessage.addButton('', QMessageBox.RejectRole)
        close_btn.hide()

    pvtboxIcon = QIcon(':/images/icon.png')
    mymessage.setWindowIcon(pvtboxIcon)

    if icon:
        mymessage.setIcon(icon)

    mymessage.raise_()
    mymessage.exec_()
    return results.get(mymessage.clickedButton(), "")
 def get_permission(self, title, action):
     """Ask user's permission to perform an action and return True if granted."""
     msg = QMessageBox(parent=self)
     msg.setIcon(QMessageBox.Question)
     msg.setWindowTitle(title)
     msg.setText(
         "Spine Toolbox needs to do the following modifications to the Julia project at <b>{0}</b>:"
         "<p>{1}".format(
             self.spine_model_config_asst.julia_active_project(), action))
     allow_button = msg.addButton("Allow", QMessageBox.YesRole)
     msg.addButton("Cancel", QMessageBox.RejectRole)
     msg.exec_()  # Show message box
     return msg.clickedButton() == allow_button
示例#12
0
    def request_to_user(
            self, dialog_id, text, buttons=("Yes", "No"), title="",
            close_button_index=-1, close_button_off=False, parent=None,
            on_clicked_cb=None,
            details=''):

        msg_box = QMessageBox(parent)
        # msg_box = QMessageBox()
        if not title:
            title = tr('Pvtbox')
        msg_box.setWindowTitle(title)
        msg_box.setText(str(text))

        pvtboxIcon = QIcon(':/images/icon.png')
        msg_box.setWindowIcon(pvtboxIcon)

        if details:
            msg_box.setDetailedText(details)

        if close_button_off:
            if get_platform() == 'Darwin':
                msg_box.setWindowFlags(Qt.Tool)
            else:
                msg_box.setWindowFlags(Qt.Dialog |
                                       Qt.CustomizeWindowHint |
                                       Qt.WindowTitleHint)
        msg_box.setAttribute(Qt.WA_MacFrameworkScaled)
        msg_box.setModal(True)

        buttons = list(buttons)
        for button in buttons:
            msg_box.addButton(button, QMessageBox.ActionRole)
        msg_box.show()
        msg_box.raise_()
        msg_box.exec_()
        try:
            button_index = buttons.index(msg_box.clickedButton().text())
        except (ValueError, AttributeError):
            button_index = -1
           # message box was closed with close button
            if len(buttons) == 1 and close_button_index == -1:
                # if only one button then call callback
                close_button_index = 0

            if len(buttons) > close_button_index >= 0:
                button_index = close_button_index

        if button_index >= 0 and callable(on_clicked_cb):
            on_clicked_cb(dialog_id, button_index)
示例#13
0
 def showContinueSearchDialog(self, searchlimit: int) -> bool:
     messagebox = QMessageBox(self)
     messagebox.setWindowTitle('Unusual search depth')
     messagebox.setText(f'''
         <p>No mod detected after searching through {searchlimit} directories.</p>
         <p>Are you sure this is a valid mod?</p>
         ''')
     messagebox.setTextFormat(Qt.RichText)
     messagebox.setStandardButtons(QMessageBox.Cancel)
     yes: QPushButton = QPushButton(' Yes, continue searching ', messagebox)
     yes.setAutoDefault(True)
     yes.setDefault(True)
     messagebox.addButton(yes, QMessageBox.YesRole)
     messagebox.exec_()
     return messagebox.clickedButton() == yes
示例#14
0
    def winBox(self):
        MessageBox = QMessageBox()
        MessageBox.setStyleSheet(
            "QLabel{min-width: 150px; min-height: 50px; color: #FF8C00;} QPushButton{min-width: 120px; min-height: 40px;} QMessageBox { background-color: #323232; font-size: 24px;}"
        )
        MessageBox.setText('YOU WIN!')

        MessageBox.setStandardButtons(QMessageBox.Ok)

        buttonOK = MessageBox.button(QMessageBox.Ok)
        buttonOK.setText('OK!')
        buttonOK.setStyleSheet(
            'background-color: #ff1e56; border-radius: 10px; font-size:20px')
        MessageBox.exec()

        if MessageBox.clickedButton() == buttonOK:
            MessageBox.close()
示例#15
0
    def closeEvent(self, event):
        """It requests the user's confirmation to close the system."""
        box = QMessageBox(self)
        box.setIcon(QMessageBox.Question)
        box.setWindowTitle(App._text['close_window'])
        box.setText(App._text['msg_close_window'])
        box.setStandardButtons(QMessageBox.Yes|QMessageBox.No)
        btn_y = box.button(QMessageBox.Yes)
        btn_y.setText(App._text['yes'])
        btn_n = box.button(QMessageBox.No)
        btn_n.setText(App._text['no'])
        box.exec_()

        if box.clickedButton() == btn_y:
            event.accept()
        else:
            event.ignore()
示例#16
0
    def generate_barcode(self):
        barcode_img = self.bottle.generate_label()
        msg_box = QMessageBox()
        msg_box.setText(
            "Lable has been created. Select one of the options below to continue:"
        )
        msg_box.setStandardButtons(QMessageBox.Save | QMessageBox.Cancel)
        pr_button = msg_box.addButton('Print', QMessageBox.ApplyRole)
        msg_box.setDefaultButton(pr_button)
        ret = msg_box.exec_()

        if ret != QMessageBox.Cancel:
            if msg_box.clickedButton() == pr_button:
                self.bottle.print_label()
            elif ret == QMessageBox.Save:
                path = QFileDialog.getSaveFileName(self, "Save As...", '',
                                                   'Picture Files (*.png)')[0]
                shutil.copyfile(barcode_img + '.png', path)
示例#17
0
    def clicked(self):
        if self.input.dataLoaded and self.output.islocationSelected:
            # TODO: Launches loading widget and disables gui until process has finished
            self.convert = Execute(self)

            msgBox = QMessageBox()
            msgBox.setWindowTitle('Converter')

            try:
                for x in self.convert(): # Conversion starts here
                    continue

                msgBox.setText('Converted')
                msgBox.exec_()
            except Errors.IncorrectFile:
                msgBox.setText('''File not Recognised''')
                msgBox.exec_()
            except PermissionError:
                msgBox.setText(''' Please Close down the Spreadsheet before attempting to convert it''')
                msgBox.exec_()
            except UnicodeDecodeError:
                msgBox.setText(''' File Encoding isn't compatible
                Encoding must be in unicode
                Click on 'Help' for a guide on how to change encoding using Excel
                ''')
                help = msgBox.addButton('Help', QMessageBox.HelpRole)
                msgBox.exec_()
                if msgBox.clickedButton() == help:
                    webbrowser.open('https://support.office.com/en-us/article/choose-text-encoding-when-you-open-and-save-files-60d59c21-88b5-4006-831c-d536d42fd861', 2)
            except Exception as e:
                s = ''
                msgBox.setText('''Unknown Error has Occured:

                ''' + repr(e) + " : \n")
                traceback.print_exc()
                msgBox.exec_()
            finally:
                self.reset()
        else:
            msg = QMessageBox()
            msg.setWindowTitle('Converter')
            msg.setText('Select Files for Conversion')
            msg.exec_()
示例#18
0
def askYesNo(message, title=bdstr.question):
    """Uses `QMessageBox` to ask "Yes" or "No" for a given question.

    Parameters:
        message: the question to be displayed
        title: the window title

    Output:
        return True if the "Yes" button has been clicked,
            False otherwise
    """
    mbox = QMessageBox(QMessageBox.Question, title, message)
    yesButton = mbox.addButton(QMessageBox.Yes)
    noButton = mbox.addButton(QMessageBox.No)
    mbox.setDefaultButton(noButton)
    mbox.exec_()
    if mbox.clickedButton() == yesButton:
        return True
    else:
        return False
示例#19
0
def popUpChooseCurrentAxis(plotted_data_axis):
    '''
    A window pops up and allows you to choose one of the given DataAxis in plotted_data_axis

    plotted_data_axis [list of DataAxis] is the data_axis to choose between

    Return the selected data_axis
    '''
    if len(plotted_data_axis) > 1:
        button_pressed_map = {}
        button_list = []

        for ax in plotted_data_axis:
            name = str(ax.getItem())
            button = QPushButton(name)

            button_list.append(button)
            button_pressed_map[button] = ax

        dialog_box = QMessageBox()
        dialog_box.setText(
            'Choose which variable that you want to have control over currently:'
        )

        for button in button_list:
            dialog_box.addButton(button, QMessageBox.AcceptRole)

        dialog_box.exec_()

        pressed_button = dialog_box.clickedButton()

        return button_pressed_map.get(pressed_button)

    elif len(plotted_data_axis) == 1:
        dialog_box = QMessageBox()
        dialog_box.setText('Only one variable being plotted.')
        dialog_box.addButton(QMessageBox.Ok)
    else:
        dialog_box = QMessageBox()
        dialog_box.setText('Nothing is plotted currently.')
        dialog_box.addButton(QMessageBox.Ok)
示例#20
0
def popUpBoxTable(path):
    '''
    A pop-up window to confirm if one should save a table in ASCII

    path [string] is the displayed path to the new history file

    Will return buttonRole of pressed button
    '''

    msgBox = QMessageBox()

    msgBox.setText('Confirm the following action:')
    text = 'Save table in ASCII-format as:' + path
    msgBox.setInformativeText(text)

    msgBox.addButton(QMessageBox.Save)
    msgBox.addButton(QMessageBox.Cancel)

    msgBox.exec_()

    pressed_button = msgBox.clickedButton()
    return msgBox.buttonRole(pressed_button)
示例#21
0
def yesNoDialog(parent, msg, title):
    """
    Convenience function to display a Yes/No dialog

    Returns:
        bool: return True if yes button press. No otherwise
    """

    m = QMessageBox(parent)
    m.setText(msg)
    m.setIcon(QMessageBox.Question)
    yesButton = m.addButton(_(Text.txt0082), QMessageBox.ButtonRole.YesRole)
    noButton = m.addButton(" No ", QMessageBox.ButtonRole.NoRole)
    m.setDefaultButton(noButton)
    m.setFont(parent.font())
    m.setWindowTitle(title)
    m.exec_()

    if m.clickedButton() == yesButton:
        return True

    return False
示例#22
0
def popUpBoxEdit(msg):
    '''
    A pop-up window to confirm if one should save tracked changes

    msg [string] is the displayed information in the window

    Will return buttonRole of pressed button

    '''

    msgBox = QMessageBox()

    msgBox.setText('Confirm saving your changes:')
    msgBox.setDetailedText(msg)

    save_button = msgBox.addButton(QMessageBox.Save)
    msgBox.addButton(QMessageBox.Cancel)
    msgBox.addButton(QMessageBox.Reset)

    msgBox.exec_()

    pressed_button = msgBox.clickedButton()
    return msgBox.buttonRole(pressed_button)
示例#23
0
def saveDlg(img, mainWidget):
    """
    Image saving dialogs. The actual saving is
    done by a call to mImage.save(). Metadata is copied from sidecar
    to image file. The function returns the image file name.
    Exception ValueError or IOError are raised if the saving fails.
    @param img:
    @type img: vImage
    @param mainWidget:
    @type mainWidget: QWidget
    @return: filename
    @rtype: str
    """
    # get last accessed dir
    lastDir = str(mainWidget.settings.value("paths/dlgdir",
                                            QDir.currentPath()))
    # file dialogs
    dlg = savingDialog(mainWidget, "Save", lastDir)
    # default saving format JPG
    dlg.selectFile(img.filename[:-3] + 'JPG')
    dlg.dlg.currentChanged.connect(lambda f: print(f))
    if dlg.exec_():
        newDir = dlg.directory().absolutePath()
        mainWidget.settings.setValue('paths/dlgdir', newDir)
        filenames = dlg.selectedFiles()
        if filenames:
            filename = filenames[0]
        else:
            raise ValueError("You must select a file")
        if isfile(filename):
            reply = QMessageBox()
            reply.setWindowTitle('Warning')
            reply.setIcon(QMessageBox.Warning)
            reply.setText("File %s already exists\n" % filename)
            reply.setStandardButtons(QMessageBox.Cancel)
            accButton = QPushButton("Save as New Copy")
            rejButton = QPushButton("OverWrite")
            reply.addButton(accButton, QMessageBox.AcceptRole)
            reply.addButton(rejButton, QMessageBox.RejectRole)
            reply.setDefaultButton(accButton)
            reply.exec_()
            retButton = reply.clickedButton()
            # build a unique name
            if retButton is accButton:
                i = 0
                base = filename
                if '_copy' in base:
                    flag = '_'
                else:
                    flag = '_copy'
                while isfile(filename):
                    filename = base[:-4] + flag + str(i) + base[-4:]
                    i = i + 1
            # overwrite
            elif retButton is rejButton:
                pass
            else:
                raise ValueError("Saving Operation Failure")
        # get parameters
        quality = dlg.sliderQual.value()
        compression = dlg.sliderComp.value()
        # call mImage.save to write image to file : throw ValueError or IOError
        thumb = img.save(filename, quality=quality, compression=compression)
        tempFilename = mktemp('.jpg')
        # save jpg to temp file
        thumb.save(tempFilename)
        # copy temp file to image file
        img.restoreMeta(img.filename, filename, thumbfile=tempFilename)
        os.remove(tempFilename)
        return filename
    else:
        raise ValueError("Saving Operation Failure")
示例#24
0
    def check_dialect(self, dialect):
        """Check if selected dialect is supported. Offer to install DBAPI if not.

        Returns:
            True if dialect is supported, False if not.
        """
        if dialect == "":  # TODO: Set text when index is -1 to 'Select dialect...'
            return
        dbapi = SQL_DIALECT_API[dialect]
        try:
            if dialect == 'sqlite':
                create_engine('sqlite://')
                self.enable_sqlite()
            elif dialect == 'mssql':
                import pyodbc
                dsns = pyodbc.dataSources()
                # Collect dsns which use the msodbcsql driver
                mssql_dsns = list()
                for key, value in dsns.items():
                    if 'msodbcsql' in value.lower():
                        mssql_dsns.append(key)
                if mssql_dsns:
                    self._toolbox.ui.comboBox_dsn.clear()
                    self._toolbox.ui.comboBox_dsn.addItems(mssql_dsns)
                    self._toolbox.ui.comboBox_dsn.setCurrentIndex(-1)
                    self.enable_mssql()
                else:
                    msg = "Please create a SQL Server ODBC Data Source first."
                    self._toolbox.msg_warning.emit(msg)
            else:
                create_engine('{}://username:password@host/database'.format(
                    "+".join([dialect, dbapi])))
                self.enable_common()
            return True
        except ModuleNotFoundError:
            dbapi = SQL_DIALECT_API[dialect]
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Question)
            msg.setWindowTitle("Dialect not supported")
            msg.setText("There is no DBAPI installed for dialect '{0}'. "
                        "The default one is '{1}'.".format(dialect, dbapi))
            msg.setInformativeText(
                "Do you want to install it using pip or conda?")
            pip_button = msg.addButton("pip", QMessageBox.YesRole)
            conda_button = msg.addButton("conda", QMessageBox.NoRole)
            cancel_button = msg.addButton("Cancel", QMessageBox.RejectRole)
            msg.exec_()  # Show message box
            if msg.clickedButton() == pip_button:
                if not self.install_dbapi_pip(dbapi):
                    self._toolbox.ui.comboBox_dialect.setCurrentIndex(-1)
                    return False
            elif msg.clickedButton() == conda_button:
                if not self.install_dbapi_conda(dbapi):
                    self._toolbox.ui.comboBox_dialect.setCurrentIndex(-1)
                    return False
            else:
                self._toolbox.ui.comboBox_dialect.setCurrentIndex(-1)
                msg = "Unable to use dialect '{}'.".format(dialect)
                self._toolbox.msg_error.emit(msg)
                return False
            # Check that dialect is not found
            if not self.check_dialect(dialect):
                self._toolbox.ui.comboBox_dialect.setCurrentIndex(-1)
                return False
            return True