def ask_user(self, title, question):
        """Shows a messagebox with yes/no question

        Args:
            title (str): MessageBox title
            question (str): MessageBox qustion label
        Returns:
            bool: True if user clicked yes, False otherwise
        """
        answer = QMessageBox.question(
            self,
            title,
            question,
            QMessageBox.StandardButtons(QMessageBox.Yes | QMessageBox.No),
        )
        return bool(answer == QMessageBox.Yes)
Exemple #2
0
    def upload_file(self):

        file_path = self.select_file()  # 获取要上传的文件名

        if file_path:
            self.label_upload_status.setText("上传中...")
            try:
                target_path = self.om.upload_file(file_path)
                self.text_url.setText(target_path)
                self.label_upload_status.setText("上传成功!")
            except Exception as e:
                QMessageBox.warning(self,
                                    "ERROR",
                                    "\n\t\tUpload Failed!\t\n\n\tPlease Check Your Config and Run again.\t\t\n\n",
                                    QMessageBox.StandardButtons(QMessageBox.Close))
                self.label_upload_status.setText("")
                print_error(e, other_string="[!] Upload Failed - {}".format(file_path))
Exemple #3
0
 def msurf(self):
     t1 = cv2.getTickCount()
     im1 = cv2.imread(self.f1[0], 0)
     im2 = cv2.imread(self.f1[1], 0)
     surf = cv2.xfeatures2d.SURF_create()
     kp1, des1 = surf.detectAndCompute(im1, None)
     kp2, des2 = surf.detectAndCompute(im2, None)
     im3 = self.matchIMG(im1, im2, kp1, kp2, des1, des2)
     t2 = cv2.getTickCount()
     time = (t2 - t1) / cv2.getTickFrequency()
     self.statusbar.showMessage("时间是%s" % str(time))
     cv2.imshow('img', im3)
     cv2.waitKey(0)
     result = QMessageBox.information(
         self, "Notice", "Do you want to save the final image",
         QMessageBox.StandardButtons(QMessageBox.Yes | QMessageBox.No))
     if result == QMessageBox.Yes:
         cv2.imwrite("Image.jpg", im3)
    def importInpProject(self):
        # Common validations
        isValid = self.validationsCreateProject()
        if isValid:
            # Validations INP
            self.InpFile = self.tbInpFile.text()
            if len(self.InpFile) == 0:
                self.iface.messageBar().pushMessage("Validations",
                                                    "INP file is not valid",
                                                    level=1)
                return
            else:
                if not os.path.exists(self.InpFile):
                    self.iface.messageBar().pushMessage(
                        "Validations", "INP file does not exist", level=1)
                    return

            # Process
            if self.NewProject:
                if not self.createProject():
                    return
            else:
                question = 'Import INP file will be delete all previous data in the current project. Do you want to continue?'
                request = QMessageBox.question(
                    self.iface.mainWindow(), self.tr('QGISRed'),
                    self.tr(question),
                    QMessageBox.StandardButtons(QMessageBox.Yes
                                                | QMessageBox.No))
                if request == QMessageBox.No:
                    return

            self.parent.zoomToFullExtent = True
            self.close()
            self.ProcessDone = True
            epsg = self.crs.authid().replace("EPSG:", "")
            # Process
            QApplication.setOverrideCursor(Qt.WaitCursor)
            resMessage = GISRed.ImportFromInp(self.ProjectDirectory,
                                              self.NetworkName,
                                              self.parent.tempFolder,
                                              self.InpFile, epsg)
            QApplication.restoreOverrideCursor()

            self.parent.processCsharpResult(resMessage, "")
Exemple #5
0
def retryAbort(parent, title, text, icon=Question, textFormat=Qt.AutoText):
    """
    Function to show a model abort/retry message box.
    
    @param parent parent widget of the message box (QWidget)
    @param title caption of the message box (string)
    @param text text to be shown by the message box (string)
    @keyparam icon icon for the dialog (Critical, Information, Question or
        Warning)
    @param textFormat format of the text (Qt.TextFormat)
    @return flag indicating the selection of the Retry button (boolean)
    """
    assert icon in [Critical, Information, Question, Warning]

    res = __messageBox(
        parent, title, text, icon,
        QMessageBox.StandardButtons(QMessageBox.Retry | QMessageBox.Abort),
        QMessageBox.Retry, textFormat)
    return res == QMessageBox.Retry
Exemple #6
0
    def dlg_workspace_load(self, _flag) -> None:
        if self.isWindowModified():
            answer = QMessageBox.warning(
                self,
                "Load workspace",
                "Do you want to save the current workspace before loading a new one?",
                QMessageBox.StandardButtons(QMessageBox.Yes | QMessageBox.No
                                            | QMessageBox.Cancel),
                QMessageBox.Cancel,
            )
            if answer == QMessageBox.Cancel:
                return
            elif answer == QMessageBox.Yes:
                saved = self.dlg_workspace_save()
                if not saved:
                    QMessageBox.information(
                        self,
                        "Load workspace",
                        "The save dialog was cancelled, not switching the workspace.",
                    )
                    return

        fname, _ftype = QFileDialog.getOpenFileName(
            self,
            "Load workspace",
            ".",
            "Prest Workspace File (*.pwf);;All files (*.*)",
        )
        if fname:

            class MyWorker(Worker):
                def work(self, workspace):
                    workspace.load_from_file(self, fname)

            try:
                MyWorker(self.workspace).run_with_progress(
                    self, "Loading %s..." % fname)
                self.refresh_datasets()
                self.setWindowFilePath(fname)
                self.setWindowModified(False)
            except Cancelled:
                log.info('PWF load cancelled')
Exemple #7
0
    def change_locals_click(self):
        # check souce local exists
        sql = '''select count(pu_cota) from livros where pu_cota = %s'''

        a = dbmain.query_one(sql, (self.fromEdt.text().upper(), ))
        flag = True
        if not a[0] > 0:
            b = QMessageBox.question(
                self, self.tr("Cota inistente"),
                self.tr("""A Cota de origem não existe!
            Continuar?"""),
                QMessageBox.StandardButtons(QMessageBox.No | QMessageBox.Yes),
                QMessageBox.No)
            if b == QMessageBox.No:
                flag == False
        if flag:
            sql = '''UPDATE livros set pu_cota=%s where pu_cota=%s'''
            dbmain.execute_query(
                sql, (self.toEdt.text().upper(), self.fromEdt.text().upper()))
            self.grid_refresh()
    def __init__(self, app_name='', validation_type='', parent_dialog=None):
        """Constructor
        
        :param app_name: the name of the plug-in to show on the 
        message box header
        :type app_name: str
        
        :param validation_type: the type of credentials (consumer keys or oauth keys)
        which do not seem to be valid
        :type validation_type: str

        :param parent_dialog: the parent dialog of this message box
        :type parent_dialog: QDialog


        """
        self.app_name = app_name
        self.validation_type = validation_type
        super().__init__(QMessageBox.Question, self.app_name, '{0} don\'t seem to be valid. Proceed anyway ?'.format(validation_type),
                         QMessageBox.StandardButtons(QMessageBox.Yes | QMessageBox.No), parent_dialog)
    def pushButton_remove_clicked(self):
        """ Slot : Remove the selected character

            -#  If there is a selected character ask the user if he wants
                to remove the file also. 
            -#  Call the removeItem of the main item
        """

        if self.mainItem.selectedItemIndex == -1:
            QMessageBox.critical(None, "Char identifier window",
                                 "No item was selected")
            return

        deleteFile = QMessageBox.question(
            None, "Char Identifier Input",
            "Do You want to delete the character file ?",
            QMessageBox.StandardButtons(QMessageBox.Yes
                                        | QMessageBox.No)) == QMessageBox.Yes

        self.mainItem.removeItem(deleteFile)
        self.graphicsScene.update()
Exemple #10
0
    def launch_close_dialog(self):
        if cfg.core.project.is_open() == False:
            return

        result = QMessageBox.question(
            self,
            _("Close the current project"),
            _("The last changes are not yet saved. Do you really want to close the current project ?"),
            QMessageBox.StandardButtons(
                QMessageBox.Cancel |
                QMessageBox.Discard |
                QMessageBox.Save),
            QMessageBox.Cancel)

        if result == QMessageBox.Cancel:
            return QMessageBox.Cancel
        elif result == QMessageBox.Discard:
            cfg.core.project.close_project()
        elif result == QMessageBox.Save:
            cfg.core.project.save()
            cfg.core.project.close_project()
 def saveProfileClick(self):
     logging.debug("Saving profile")
     self.saveQuestion = QMessageBox()
     self.saveQuestion.setIcon(QMessageBox.Question)
     self.saveQuestion.setStandardButtons(
         QMessageBox.StandardButtons(81920))  #yes, no
     self.saveQuestion.setText(
         "Do you want to apply selected tweaks and overwrite userChrome?")
     self.saveQuestion.exec()
     self.saveCSS = ""
     if self.saveQuestion.result() == 16384:  #yes
         logging.debug("Saving userChrome")
         selTweaksNumber = self.filesBox.selectedTweaks.topLevelItemCount()
         savingTweaks = []
         for i in range(selTweaksNumber):
             currentSavingTweak = self.filesBox.selectedTweaks.topLevelItem(
                 i)
             currentSavingData = {}
             currentSavingData["Enabled"] = currentSavingTweak.checkState(0)
             currentSavingData["Category"] = currentSavingTweak.text(1)
             currentSavingData["Name"] = currentSavingTweak.text(2)
             logging.debug("Tweak cat %s, name %s, selected %s",
                           currentSavingData["Category"],
                           currentSavingData["Name"],
                           currentSavingData["Enabled"])
             savingTweaks.append(currentSavingData)
             if currentSavingData["Enabled"] == 2:
                 with open(self.appDir.path() + "/" +
                           currentSavingData["Category"] + "/" +
                           currentSavingData["Name"]) as twkFile:
                     self.saveCSS += twkFile.read() + "\n"
         logging.debug("Selected tweaks: %s", savingTweaks)
         with open(self.profilePath + "/chrome/userFirefox.json",
                   "w") as fp:
             json.dump(savingTweaks, fp)
         logging.debug("userChrome.css: %s", self.saveCSS)
         with open(self.profilePath + "/chrome/userChrome.css", "w") as fp:
             fp.write(self.saveCSS)
     elif self.saveQuestion.result() == 65536:  #no
         logging.debug("Not saving userChrome.")
Exemple #12
0
def okToClearData(parent, title, text, saveFunc, textFormat=Qt.AutoText):
    """
    Function to show a model message box to ask for clearing the data.
    
    @param parent parent widget of the message box (QWidget)
    @param title caption of the message box (string)
    @param text text to be shown by the message box (string)
    @param saveFunc reference to a function performing the save action. It
        must be a parameterless function returning a flag indicating success.
    @param textFormat format of the text (Qt.TextFormat)
    @return flag indicating that it is ok to clear the data (boolean)
    """
    res = __messageBox(
        parent, title, text, QMessageBox.Warning,
        QMessageBox.StandardButtons(QMessageBox.Abort | QMessageBox.Discard
                                    | QMessageBox.Save), QMessageBox.Save,
        textFormat)
    if res == QMessageBox.Abort:
        return False
    if res == QMessageBox.Save:
        return saveFunc()
    return True
Exemple #13
0
 def check_data(self):
     self.sentence_count += 1
     if self.sentence_count == len(self.data):
         self.save_rank()
         self.thread.wait()
         r = QMessageBox.information(
             self, ('Congradulations!'),
             ('\n\n\t恭喜你通关了一次句子练习!\t\t\t\n\n\t\t再接再励吧!\t\n\n\t(Ok:再来一次 | Cancel:选择其他模式)\t\n'
              ),
             QMessageBox.StandardButtons(QMessageBox.Ok
                                         | QMessageBox.Cancel))
         self.thread.terminate()  #表示已通关练习,停止计时线程
         if r == QMessageBox.Cancel:
             self.hide()
             self.mainwindow.radio_blank_menu.setChecked(True)
         else:
             self.sentence1_input.setText('')
             self.sentence2_input.setText('')
             self.sentence3_input.setText('')
             self.prepare_work()
     else:
         self.prepare_sentence_set(self.data[self.sentence_count])
Exemple #14
0
 def display(self):
     # Give the user the opportunity to abort
     confirmationButton = QMessageBox.question(
         self.__parentWidget, self.__tr("Before starting deletion..."),
         self.__tr(
             "Please double check that you want your orphaned script extender saves deleted. If you proceed, you won't be able to get them back, even if you find you've copied the corresponding base game save somewhere else so still have a copy."
         ),
         QMessageBox.StandardButtons(QMessageBox.Ok | QMessageBox.Cancel))
     if confirmationButton != QMessageBox.Ok:
         return
     managedGame = self.__organizer.managedGame()
     gameSaveExtension = managedGame.savegameExtension()
     skseSaveExtension = managedGame.savegameSEExtension()
     gameSavesDirectory = managedGame.savesDirectory().absolutePath()
     if self.__organizer.profile().localSavesEnabled():
         gameSavesDirectory = os.path.join(
             self.__organizer.profile().absolutePath(), "saves")
     count = 0
     for cosave in glob(
             os.path.join(gameSavesDirectory, "*." + skseSaveExtension)):
         saveName = os.path.splitext(cosave)[0]
         if not os.path.isfile(saveName + "." + gameSaveExtension):
             os.remove(cosave)
             count += 1
     if count == 0:
         QMessageBox.information(
             self.__parentWidget,
             self.__tr("No orphaned script extender saves found"),
             self.__tr(
                 "No orphaned script extender co-saves were found, so none were removed."
             ))
     else:
         QMessageBox.information(
             self.__parentWidget,
             self.__tr("Orphaned script extender saves removed"),
             self.__tr(
                 "{0} orphaned script extender co-save(s) removed successfully."
             ).format(count))
Exemple #15
0
def yesNo(parent, title, text, icon=Question, yesDefault=False,
          textFormat=Qt.AutoText):
    """
    Function to show a model yes/no message box.
    
    @param parent parent widget of the message box (QWidget)
    @param title caption of the message box (string)
    @param text text to be shown by the message box (string)
    @keyparam icon icon for the dialog (Critical, Information, Question or
        Warning)
    @keyparam yesDefault flag indicating that the Yes button should be the
        default button (boolean)
    @param textFormat format of the text (Qt.TextFormat)
    @return flag indicating the selection of the Yes button (boolean)
    """
    assert icon in [Critical, Information, Question, Warning]
    
    res = __messageBox(
        parent, title, text, icon,
        QMessageBox.StandardButtons(QMessageBox.Yes | QMessageBox.No),
        yesDefault and QMessageBox.Yes or QMessageBox.No,
        textFormat)
    return res == QMessageBox.Yes
Exemple #16
0
    def record_save(self):
        # só grava não haver nenhuma alteração ás tabelas externas'
        """ insere """
        gl.ON_LOCAL = self.pu_cota.text().upper().strip()
        gl.TYPE = self.pu_type.currentIndex()
        gl.STATUS = self.pu_status.currentIndex()
        if self.pub_id == -1:
            # if self.draft_data:
            if self.check_new_record():
                self.insert_record()
                self.toto = True
                self.close()
            else:
                form = missing_data.DadosWizard('\n'.join(self.error_list),
                                                ['Corrigir'])
                form.exec_()
                # if form.toto == 0:
                #     print('Corrige')
                # elif form.toto == 1:
                #     print('continua')
                #     self.fill_defaults()
                #     self.check_new_record()
                #     self.insert_record()
                #     self.toto = True
                #     self.close()

        else:
            if self.check_update_record():
                self.update_record()
                self.toto = True  # refresh
                self.close()
            else:
                result = QMessageBox.information(None, \
                                                 "Faltam os seguintes dados.",
                                                 '\n'.join(self.error_list),
                                                 QMessageBox.StandardButtons( \
                                                     QMessageBox.Close), QMessageBox.Close)
Exemple #17
0
    def __getRedirectOutput(self):
        redirectOutput = bool(
            self.__organizer.pluginSetting(self.name(), "output-to-mod"))
        initialised = bool(
            self.__organizer.pluginSetting(self.name(), "initialised"))
        if not initialised:
            result = QMessageBox.question(
                self.__parentWidget, self.__tr("Output to a mod?"),
                self.__tr(
                    "Fore's New Idles in Skyrim can output either to Mod Organizer's VFS (potentially overwriting files from multiple mods) or to a separate mod. Would you like FNIS to output to a separate mod? This setting can be updated in the Plugins tab of the Mod Organizer Settings menu."
                ),
                QMessageBox.StandardButtons(QMessageBox.Yes | QMessageBox.No
                                            | QMessageBox.Cancel))
            if result == QMessageBox.Yes:
                redirectOutput = True
            elif result == QMessageBox.No:
                redirectOutput = False
            else:
                # the user pressed cancel
                raise UnknownOutputPreferenceException

            self.__organizer.setPluginSetting(self.name(), "output-to-mod",
                                              redirectOutput)
        return redirectOutput
    def openProfileClick(self):
        #Button Open... click
        self.profilePath = self.profilePathDialog.getExistingDirectory(
            self.profileSelect, "Select Firefox profile")
        # self.profilePath = "~/Library/Application Support/Firefox/Profiles/rpk2uobe.default"
        logging.debug("Selected directory: \"%s\"", self.profilePath)
        if self.profilePath != "":
            self.selectedProfile = QDir(self.profilePath)
            self.firefoxDir = QDir(self.profilePath)
            logging.debug("Selected profile qdir: %s",
                          self.selectedProfile.path())
            self.firefoxDir.cdUp()
            self.profilesFile = QFile(self.firefoxDir.path() + "/profiles.ini")
            logging.debug("Profiles file: %s", self.profilesFile.fileName())
            logging.debug("Profiles file exists: %s",
                          self.profilesFile.exists())
            logging.debug("Firefox folder: %s", self.firefoxDir.dirName())
            # Basic check if parent directory is named 'firefox' and contains a file named 'profiles.ini'
            #if self.firefoxDir.dirName() == "firefox" and self.profilesFile.exists():
            if True:
                self.profilePath = self.profilePath
                self.profileLabel.setText(self.profilePath)

                self.filesBox.buttonBox.setEnable(True)
                self.filesBox.availableTweaks.setEnabled(True)
                self.filesBox.selectedTweaks.setEnabled(True)
                self.profileSave.setEnabled(True)

                self.profileDir.setPath(self.profilePath)
                logging.debug("Profile dirs: %s", self.profileDir.entryList())
                self.userChrome = QFile(
                    self.profilePath + "/chrome/userChrome.css")
                self.userFFSettings = QFile(
                    self.profilePath + "/chrome/userFirefox.json")
                logging.debug("userChrome exists: %s",
                              self.userChrome.exists())
                if self.userChrome.exists(
                ) and not self.userFFSettings.exists():
                    self.backupChrome = QMessageBox()
                    self.backupChrome.setIcon(QMessageBox.Question)
                    self.backupChrome.setText(
                        "userChrome.css file already exists in this profile. This may be overwritten. Do you want to make a backup?"
                    )
                    self.backupChrome.setStandardButtons(
                        QMessageBox.StandardButtons(81920))  #yes, no
                    self.backupChrome.exec()
                    logging.debug("Dialog result: %s",
                                  self.backupChrome.result())
                    if self.backupChrome.result() == 16384:  #yes
                        logging.debug("Backing up userChrome")
                        self.backupDone = QMessageBox()
                        self.backupFile = QFile(
                            self.profilePath + "/chrome/userChrome.css~")
                        logging.debug("Backup file: %s",
                                      self.backupFile.fileName())
                        logging.debug("Backup exists: %s",
                                      self.backupFile.exists())
                        if self.backupFile.exists():
                            logging.debug("Backup already exists")
                            self.backupDone.setIcon(QMessageBox.Warning)
                            self.backupDone.setText(
                                "Backup already exists. The file was NOT overwritten and new backup not made."
                            )
                        else:
                            if self.userChrome.copy(self.profilePath +
                                                    "/chrome/userChrome.css~"):
                                self.backupDone.setIcon(
                                    QMessageBox.Information)
                                self.backupDone.setText(
                                    "Backed up to 'userChrome.css~'")
                            else:
                                self.backupDone.setIcon(QMessageBox.Critical)
                                self.backupDone.setText("Backing up failed.")
                        self.backupDone.exec()
                    elif self.backupChrome.result() == 65536:  #no
                        logging.debug("Not backing up userChome")
                # Load existing settings
                try:
                    with open(self.profilePath + "/chrome/userFirefox.json"
                              ) as uFP:
                        savedTweaks = json.load(uFP)
                    logging.debug("Loaded json settings: %s", savedTweaks)
                    for loadedTweak in savedTweaks:
                        logging.debug(
                            "Loaded tweak. check: %i, category: %s, name: %s",
                            loadedTweak["Enabled"], loadedTweak["Category"],
                            loadedTweak["Name"])
                        tweakCat = loadedTweak["Category"]
                        tweakName = loadedTweak["Name"]
                        self.filesBox.tweaksAdded[
                            tweakCat + tweakName] = QTreeWidgetItem(
                                self.filesBox.selectedTweaks)
                        self.filesBox.tweaksAdded[tweakCat
                                                  + tweakName].setCheckState(
                                                      0,
                                                      loadedTweak["Enabled"])
                        self.filesBox.tweaksAdded[tweakCat
                                                  + tweakName].setText(
                                                      1, tweakCat)
                        self.filesBox.tweaksAdded[tweakCat
                                                  + tweakName].setText(
                                                      2, tweakName)
                except FileNotFoundError:
                    pass
                self.filesBox.resizeColumns()
            else:
                self.noProfile = QMessageBox()
                self.noProfile.setIcon(QMessageBox.Warning)
                self.noProfile.setText(
                    "The selected directory does not appear to be a valid Firefox profile. Profiles are usually located at '~/.mozilla/firefox/xxxx' and is most likely a hidden directory."
                )
                self.noProfile.exec()
Exemple #19
0
 def netError(self, netError):
     self.ui.BtnCon.setEnabled(True)
     print(netError)
     QMessageBox.warning(self, ("error"), ("Net Error!"),
                         QMessageBox.StandardButtons(QMessageBox.Close))
Exemple #20
0
 def exitP(self):
     result = QMessageBox.information(
         self, "Notice", "Are you sure to exit",
         QMessageBox.StandardButtons(QMessageBox.Yes | QMessageBox.No))
     if result == QMessageBox.Yes:
         self.close()
Exemple #21
0
 def Warning_QMessageBox(self, content):
     warning = QMessageBox.warning(
         self, ("警告"), content,
         QMessageBox.StandardButtons(QMessageBox.Retry))
Exemple #22
0
 def Information_QMessageBox(self, content):
     information = QMessageBox.information(
         self, '提示', content, QMessageBox.StandardButtons(QMessageBox.Ok))
Exemple #23
0
 def returnHome(self):
     if hasattr(self,'temp_patient'):
         reply = QMessageBox.question(self,'Commit?','Would you like to save all unsaved changes (if any)?',QMessageBox.StandardButtons(QMessageBox.Yes|QMessageBox.No|QMessageBox.Cancel))
         if reply == QMessageBox.Yes:
             self.set_patient_params()
             self.close()
         elif reply == QMessageBox.Cancel:
             pass
         else:
             self.close()
     else:
         #no pt selected
         self.close()
Exemple #24
0
 def __getFNISPath(self):
     savedPath = self.__organizer.pluginSetting(self.name(), "fnis-path")
     # FNIS must be installed within the game's data directory, so needs to either be within that or a mod folder
     modDirectory = self.__getModDirectory()
     gameDataDirectory = pathlib.Path(
         self.__organizer.managedGame().dataDirectory().absolutePath())
     pathlibPath = pathlib.Path(savedPath)
     inGoodLocation = self.__withinDirectory(pathlibPath, modDirectory)
     inGoodLocation |= self.__withinDirectory(pathlibPath,
                                              gameDataDirectory)
     if not pathlibPath.is_file() or not inGoodLocation:
         QMessageBox.information(
             self.__parentWidget, self.__tr("Find FNIS"),
             self.__tr(
                 "Fore's New Idles in Skyrim can't be found using the location saved in Mod Organizer's settings. Please find GenerateFNISforUsers.exe in the file picker. FNIS must be visible within the VFS, so choose an installation either within the game's data directory or within a mod folder. This setting can be updated in the Plugins tab of the Mod Organizer Settings menu."
             ))
         while True:
             path = QFileDialog.getOpenFileName(
                 self.__parentWidget,
                 self.__tr("Locate GenerateFNISforUsers.exe"),
                 str(modDirectory), "FNIS (GenerateFNISforUsers.exe)")[0]
             if path == "":
                 # Cancel was pressed
                 raise FNISMissingException
             pathlibPath = pathlib.Path(path)
             inGoodLocation = self.__withinDirectory(
                 pathlibPath, modDirectory)
             inGoodLocation |= self.__withinDirectory(
                 pathlibPath, gameDataDirectory)
             if pathlibPath.is_file() and inGoodLocation:
                 self.__organizer.setPluginSetting(self.name(), "fnis-path",
                                                   path)
                 savedPath = path
                 break
             else:
                 QMessageBox.information(
                     self.__parentWidget,
                     self.__tr("Not a compatible location..."),
                     self.__tr(
                         "Fore's New Idles in Skyrim only works when within the VFS, so must be installed to the game's data directory or within a mod folder. Please select a different FNIS installation."
                     ))
     # Check the mod is actually enabled
     if self.__withinDirectory(pathlibPath, modDirectory):
         fnisModName = None
         for path in pathlibPath.parents:
             if path.parent.samefile(modDirectory):
                 fnisModName = path.name
                 break
         if (self.__organizer.modList().state(fnisModName)
                 & mobase.ModState.active) == 0:
             # FNIS is installed to an inactive mod
             result = QMessageBox.question(
                 self.__parentWidget, self.__tr("FNIS mod deactivated"),
                 self.__tr(
                     "Fore's New Idles in Skyrim is installed to an inactive mod. Press OK to activate it or Cancel to quit the tool"
                 ),
                 QMessageBox.StandardButtons(QMessageBox.Ok
                                             | QMessageBox.Cancel))
             if result == QMessageBox.Ok:
                 self.__organizer.modList().setActive(fnisModName, True)
             else:
                 raise FNISInactiveException
     return savedPath
 def on_pushButton_write_pressed(self):
     """
     Writing everything.
     """
     from _workbench import workbench
     import random
     from _workbench import configs
     config_obj = configs.configs()
     last_file_id = config_obj.read_config('Last_Setup', 'Last_File_ID')
     current_version = config_obj.read_config('Basic', 'Version')
     username = config_obj.read_config('Basic', 'User')
     logging.info(
         'Started Writing   ~~  Version: %s   ~~  User: %s  ~~  Run ID: %s',
         current_version, username, last_file_id)
     global rgb_basis
     rgb_basis = list((rgb_basis_r, rgb_basis_g, rgb_basis_b))
     if fileName is None or fileName is '':
         QMessageBox.critical(
             self, self.tr("No File"),
             self.
             tr("""No file has been loaded.\nYou need to first load a file."""
                ), QMessageBox.StandardButtons(QMessageBox.Cancel))
         return
     else:
         logging.info(
             'Parameters: startID=%d Culture=%s Religion=%s Terrain=%s is_tribal=%s rgb_base=%s',
             startID, culture, religion, terrain, str(is_tribal), rgb_basis)
         if flag_removal is True:
             logging.info('Flag Removal turned on')
             enough_flags_check = workbench.province.read.flags.check_if_enough(
                 fileName)
             if enough_flags_check is False:
                 QMessageBox.critical(
                     self, self.tr("Not Enough Flags"),
                     self.
                     tr("""Flag Removal is selected, but there are more provinces than there are flags in the folder."""
                        ), QMessageBox.StandardButtons(QMessageBox.Cancel))
                 logging.info('~~~ Aborted: Not enough flags in folder.')
                 return
             else:
                 import os
                 psueod_flag_log_rel_path = "Databases\\Flags\\Removed\\"
                 pseudo_log_path = psueod_flag_log_rel_path + 'removed_flag_list.log'
                 os.makedirs(os.path.dirname(pseudo_log_path),
                             exist_ok=True)  # create folder
                 with open(pseudo_log_path, "w+") as file:
                     file.write("~~~~~~~~~~~~~~\nFor run ID %s\n" %
                                (last_file_id))
                 pass
         workbench.execute.write(fileName, startID, culture, religion,
                                 is_tribal, terrain, rgb_basis,
                                 flag_removal, templeDist)
         logging.info('----- Exited Writing ----- ')
         deus_vult_mode = random.randrange(0, 15)
         if deus_vult_mode < 2:
             logging.info('DEUS VULT')
             print("DEUS VULT INFIDEL")
             for x in range(3):
                 print("DEUS VULT DEUS VULT DEUS VULT")
             for x in range(3):
                 QMessageBox.information(
                     self, "DEUS VULT INFIDEL",
                     "DEUS VULT DEUS VULT DEUS VULT\nDEUS VULT DEUS VULT DEUS VULT\nDEUS VULT DEUS VULT DEUS VULT\n"
                 )
             import webbrowser
             webbrowser.open('https://webmshare.com/play/ZQDQw')
         else:
             QMessageBox.information(self, "Complete",
                                     "Complete\n\nCheck the Output folder")
         from _workbench import configs
         logging.info('Writing Config')
         last_file_id_int: int = int(last_file_id)
         last_file_id_int += 1
         last_file_id = str(last_file_id_int)
         config_obj.edit_config('Last_Setup', 'Last_File_ID',
                                str(last_file_id))
         if startID is not '':
             config_obj.edit_config('Last_Setup', 'startid', str(startID))
         if culture is not '':
             config_obj.edit_config('Last_Setup', 'culture', culture)
         if religion is not '':
             config_obj.edit_config('Last_Setup', 'religion', religion)
         if terrain is not '':
             config_obj.edit_config('Last_Setup', 'terrain', terrain)
         config_obj.edit_config('Last_Setup', 'is_tribal', str(is_tribal))
         config_obj.edit_config('Last_Setup', 'rgb_basis', str(rgb_basis))
         config_obj.edit_config('Last_Setup', 'Last_fileName',
                                str(fileName))
         logging.info('EXECUTION COMPLETE')
         logging.info(
             "----------------------------------------------------------------------------------------------------------------------------"
         )
Exemple #26
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        # centra janela no ecran
        self.centralwidget = QWidget(self)
        self.setWindowIcon(QIcon('./img/books.png'))
        self.setCentralWidget(self.centralwidget)
        self.setWindowTitle('Livros')
        # vars
        gl.refresh = False
        gl.SQLglobal = ''
        gl.DATAglobal = ''
        gl.current_path = './'
        print('loading datasets...')
        self.status = ['Todos']
        self.types = ['Todos']
        gl.db_params = stdio.read_config_file('gabo.ini')
        if not gl.db_params[0]:
            QMessageBox.critical(
                None, "Erro Fatal",
                """O ficheiro de configuração não foi encontrado ou está corrompido!""",
                QMessageBox.StandardButtons(QMessageBox.Close),
                QMessageBox.Close)
            self.close()
        gl.db_params = gl.db_params[1]
        gl.conn_string = "host=" + gl.db_params['db_host'] + ' port=' + gl.db_params['db_port'] + ' dbname=' + gl.db_params['db_database'] +\
        ' user='******'db_user'] + ' password='******'db_password']
        data_access.get_autores()
        data_access.get_status()
        data_access.get_types()
        data_access.get_params()
        data_access.load_preps()
        data_access.get_areas()
        data_access.get_special_tags()
        data_access.get_locals()
        print('ending loading datasets!')
        self.status.extend(gl.dsStatus)
        self.types.extend(gl.ds_types)
        self.resize(1200, 768)
        self.center()
        gl.DEBUG = True
        QApplication.setStyle(QStyleFactory.create('Fusion'))

        mainLayout = QVBoxLayout(self.centralwidget)
        # barra de pesquisa
        """ primeira pesquisa"""
        self.mainSearchCbox = QComboBox()
        self.mainSearchCbox.setMaximumWidth(90)
        self.mainSearchCbox.setMinimumWidth(90)
        self.mainSearchCbox.addItems(['Titulo', 'ISBN', 'Etiqueta'])
        self.mainSearchCbox.setCurrentIndex(0)

        self.mainToSearchEdt = QLineEdit()
        self.mainToSearchEdt.setMaximumWidth(300)
        self.mainToSearchEdt.setMinimumWidth(300)

        mainSearchBtn = QToolButton()
        mainSearchBtn.setToolTip('Pesquisa texto')
        mainSearchBtn.setIcon(QIcon('./img/search.png'))
        # self.set_icon_size(firstSearchBtn)
        mainSearchBtn.clicked.connect(self.main_search_click)

        mainSearchClearBtn = QToolButton()
        mainSearchClearBtn.setToolTip('Limpa Pesquisa')
        mainSearchClearBtn.setIcon(QIcon('./img/clear.png'))
        # self.set_icon_size(firstSearchBtn)
        # mainSearchBtn.clicked.connect(self.main_search_clear_click)

        authorsBtn = QToolButton()
        authorsBtn.setToolTip('Autores')
        authorsBtn.setIcon(QIcon('./img/authors.png'))
        authorsBtn.clicked.connect(self.authors_click)

        secondClearBtn = QToolButton()
        secondClearBtn.setToolTip('Limpa Pesquisa')
        secondClearBtn.setIcon(QIcon('./img/clear.png'))
        # self.set_icon_size(secondClearBtn)
        secondClearBtn.clicked.connect(self.second_field_clear_click)

        cotasBtn = QToolButton()
        cotasBtn.setToolTip('Cotas Locais')
        cotasBtn.setIcon(QIcon('./img/locals.png'))
        cotasBtn.clicked.connect(self.locals_click)

        search_tags_Btn = QToolButton()
        search_tags_Btn.setToolTip('Pesquisa tags')
        search_tags_Btn.setIcon(QIcon('./img/search_tags.png'))
        # self.set_icon_size(search_tags_Btn)
        search_tags_Btn.clicked.connect(self.search_tags_mode_click)

        clear_tags_Btn = QToolButton()
        clear_tags_Btn.setToolTip('Limpa Tags')
        clear_tags_Btn.setIcon(QIcon('./img/clear.png'))
        # self.set_icon_size(clear_tags_Btn)
        clear_tags_Btn.clicked.connect(self.clear_tags_search)

        self.tags_browserBtn = QToolButton()
        self.tags_browserBtn.setToolTip('Gere Etiquetas')
        self.tags_browserBtn.setIcon(QIcon('./img/tags.png'))
        # self.set_icon_size(self.tags_browserBtn)
        self.tags_browserBtn.clicked.connect(self.tags_browser_click)

        # drop add menu
        bookAddBtn = QPushButton('Novo')
        bookAddBtn.setToolTip('Adiciona Livro')
        bookAddBtn.clicked.connect(self.record_add_click)

        bookAddIsbnBtn = QPushButton('Wook')
        bookAddIsbnBtn.setToolTip('Adiciona livro pela WOOK')
        bookAddIsbnBtn.clicked.connect(self.record_add_wook_click)

        self.addBookBtn = QPushButton()
        self.addBookBtn.setToolTip('Adicionar Livro')
        self.addBookBtn.setIcon(QIcon('./img/addbook.png'))

        printBtn = QToolButton()
        printBtn.setIcon(QIcon('./img/print.png'))
        # self.set_icon_size(printBtn)
        printBtn.clicked.connect(self.print_click)

        self.last_fiveBtn = QPushButton()
        self.last_fiveBtn.setText('Ultimos ' + gl.SHOW_RECORDS)
        self.last_fiveBtn.clicked.connect(self.last_records_click)

        double1_Btn = QPushButton()
        double1_Btn.setText('Duplica')
        double1_Btn.clicked.connect(self.double1_click)

        clone_Btn = QPushButton()
        clone_Btn.setText('&Clona')
        clone_Btn.clicked.connect(self.clone_click)

        aboutBtn = QToolButton()
        aboutBtn.setToolTip('Acerca')
        aboutBtn.setIcon(QIcon('./img/info.png'))
        # self.set_icon_size(aboutBtn)
        aboutBtn.clicked.connect(self.about_click)

        closeBtn = QToolButton()
        closeBtn.setToolTip('Sair')
        closeBtn.setIcon(QIcon('./img/close.png'))
        # self.set_icon_size(closeBtn)
        closeBtn.clicked.connect(self.closeBtn_click)

        self.sortByCbox = QComboBox()
        self.sortByCbox.setCurrentIndex(0)
        self.sortByCbox.addItems(
            ['Nada', 'Autor', 'Titulo', 'Tipos', 'Local', 'Volume', 'Ano'])
        self.sortByCbox.setCurrentIndex(0)
        self.sortByCbox.currentIndexChanged.connect(self.sort_by_change)
        self.recordLimitEdt = QLineEdit()
        self.recordLimitEdt.setMaximumWidth(40)
        self.recordLimitEdt.setMaxLength(4)
        self.recordLimitEdt.setText(gl.SHOW_RECORDS)
        self.recordLimitEdt.editingFinished.connect(self.limit_change)

        self.typesCbox = QComboBox()
        self.typesCbox.addItems(self.types)
        self.typesCbox.setCurrentIndex(0)
        self.typesCbox.currentIndexChanged.connect(self.types_change)
        self.statusCbox = QComboBox()
        self.statusCbox.setCurrentIndex(0)

        self.statusCbox.addItems(self.status)
        self.statusCbox.currentIndexChanged.connect(self.status_change)
        widthSumBtn = QToolButton()
        widthSumBtn.setToolTip('Espaço')
        widthSumBtn.setIcon(QIcon('./img/width_sigma.png'))
        # self.set_icon_size(widthSumBtn)
        widthSumBtn.clicked.connect(self.width_sum_click)

        mainLayout.addLayout(
            qlib.addHLayout([
                bookAddBtn, bookAddIsbnBtn, self.last_fiveBtn, double1_Btn,
                clone_Btn, printBtn, True, aboutBtn, closeBtn
            ]))
        mainLayout.addLayout(
            qlib.addHLayout([
                self.mainSearchCbox, self.mainToSearchEdt, mainSearchBtn,
                mainSearchClearBtn, self.tags_browserBtn, authorsBtn, cotasBtn,
                widthSumBtn, True, 'Ordena:', self.sortByCbox, 'Tipos',
                self.typesCbox, 'Estado', self.statusCbox, True, 'Registos',
                self.recordLimitEdt
            ], 60))

        mainLayout.addLayout(
            qlib.addHLayout(
                ['AUTOR:eça,POR:nenhum,TIPO:todos,ESTADO:todos', True], 400))

        # grid
        self.grid = QTableWidget(self)
        self.grid.setSelectionBehavior(QTableWidget.SelectRows)
        self.grid.setSelectionMode(QTableWidget.SingleSelection)
        self.grid.setEditTriggers(QTableWidget.NoEditTriggers)
        self.grid.verticalHeader().setDefaultSectionSize(20)
        self.grid.setAlternatingRowColors(True)
        self.grid.verticalHeader().setVisible(False)
        self.grid.setStyleSheet("alternate-background-color: #d2e5ff;")
        self.grid.doubleClicked.connect(self.grid_double_click)

        mainLayout.addWidget(self.grid)
        # sub menus
        author_pub = QAction("Obras do Autor", self)
        author_pub.triggered.connect(self.author_pub_click)
        self.grid.addAction(author_pub)

        local_pub = QAction("Obras nesta Cota", self)
        local_pub.triggered.connect(self.local_pub_click)
        self.grid.addAction(local_pub)
        self.grid.setContextMenuPolicy(2)

        self.last_records_click()
        try:
            if GetSystemMetrics(1) <= 768:
                self.showMaximized()
        except NameError:
            pass
    def __testQt42(self):
        """
        Private method to test the selected options for Qt 4.2.0.
        """
        buttons = QMessageBox.NoButton
        if self.abortCheck.isChecked():
            buttons |= QMessageBox.Abort
        if self.applyCheck.isChecked():
            buttons |= QMessageBox.Apply
        if self.cancelCheck.isChecked():
            buttons |= QMessageBox.Cancel
        if self.closeCheck.isChecked():
            buttons |= QMessageBox.Close
        if self.discardCheck.isChecked():
            buttons |= QMessageBox.Discard
        if self.helpCheck.isChecked():
            buttons |= QMessageBox.Help
        if self.ignoreCheck.isChecked():
            buttons |= QMessageBox.Ignore
        if self.noCheck.isChecked():
            buttons |= QMessageBox.No
        if self.notoallCheck.isChecked():
            buttons |= QMessageBox.NoToAll
        if self.okCheck.isChecked():
            buttons |= QMessageBox.Ok
        if self.openCheck.isChecked():
            buttons |= QMessageBox.Open
        if self.resetCheck.isChecked():
            buttons |= QMessageBox.Reset
        if self.restoreCheck.isChecked():
            buttons |= QMessageBox.RestoreDefaults
        if self.retryCheck.isChecked():
            buttons |= QMessageBox.Retry
        if self.saveCheck.isChecked():
            buttons |= QMessageBox.Save
        if self.saveallCheck.isChecked():
            buttons |= QMessageBox.SaveAll
        if self.yesCheck.isChecked():
            buttons |= QMessageBox.Yes
        if self.yestoallCheck.isChecked():
            buttons |= QMessageBox.YesToAll
        if buttons == QMessageBox.NoButton:
            buttons = QMessageBox.Ok

        defaultButton = self.buttonsCodeListBinary[
            self.defaultCombo.currentIndex()]

        if self.rInformation.isChecked():
            QMessageBox.information(self, self.eCaption.text(),
                                    self.eMessage.toPlainText(),
                                    QMessageBox.StandardButtons(buttons),
                                    defaultButton)
        elif self.rQuestion.isChecked():
            QMessageBox.question(self, self.eCaption.text(),
                                 self.eMessage.toPlainText(),
                                 QMessageBox.StandardButtons(buttons),
                                 defaultButton)
        elif self.rWarning.isChecked():
            QMessageBox.warning(self, self.eCaption.text(),
                                self.eMessage.toPlainText(),
                                QMessageBox.StandardButtons(buttons),
                                defaultButton)
        elif self.rCritical.isChecked():
            QMessageBox.critical(self, self.eCaption.text(),
                                 self.eMessage.toPlainText(),
                                 QMessageBox.StandardButtons(buttons),
                                 defaultButton)
Exemple #28
0
 def apk_error_dialog(self):
     self.layout.textEdit_apppath.setText("")
     QMessageBox.information(self, ("Warning"),
                             ("""Apk cannot be resolved"""),
                             QMessageBox.StandardButtons(QMessageBox.Yes))
Exemple #29
0
    def __getLogOutputPath(self):
        path = self.__organizer.pluginSetting(self.name(), "output-logs-path")
        pathlibPath = pathlib.Path(path)
        modDirectory = self.__getModDirectory()
        fnisOutputPath = pathlib.Path(self.__getOutputPath())
        isAMod = pathlibPath.parent.samefile(modDirectory)
        isSameAsFnisOutput = pathlibPath.samefile(fnisOutputPath)
        if not pathlibPath.is_dir() or not isAMod or isSameAsFnisOutput:
            QMessageBox.information(
                self.__parentWidget, self.__tr("Choose an output mod"),
                self.__tr(
                    "Please choose an output mod for logs for Fore's New Idles in Skyrim. This must be a directory in Mod Organizer's mods directory, must not be the same as the FNIS output mod, and you can create one if you do not have one already. This setting can be updated in the Plugins tab of the Mod Organizer Settings menu."
                ))
            while not pathlibPath.is_dir() or not isAMod or isSameAsFnisOutput:
                path = QFileDialog.getExistingDirectory(
                    self.__parentWidget, self.__tr("Choose a log output mod"),
                    str(modDirectory), QFileDialog.ShowDirsOnly)
                if not path:
                    # cancel was pressed
                    raise UnknownOutputPreferenceException
                pathlibPath = pathlib.Path(path)
                isAMod = pathlibPath.parent.samefile(modDirectory)
                if not isAMod:
                    QMessageBox.information(
                        self.__parentWidget, self.__tr("Not a mod..."),
                        self.__tr(
                            "The selected directory is not a Mod Organizer managed mod. Please choose a directory within the mods directory."
                        ))
                    continue
                isSameAsFnisOutput = pathlibPath.samefile(fnisOutputPath)
                if isSameAsFnisOutput:
                    QMessageBox.information(
                        self.__parentWidget, self.__tr("Same as FNIS output"),
                        self.__tr(
                            "The selected mod is the same as the FNIS output mod.  Please choose a different mod."
                        ))
                    continue
                empty = True
                for item in pathlibPath.iterdir():
                    if item.name != "meta.ini":
                        empty = False
                        break
                if not empty:
                    if QMessageBox.question(
                            self.__parentWidget, self.__tr("Mod not empty"),
                            self.__tr(
                                "The selected mod already contains files. Are you sure want to use it as the output mod?"
                            ),
                            QMessageBox.StandardButtons(
                                QMessageBox.Yes
                                | QMessageBox.No)) == QMessageBox.Yes:
                        # Proceed normally - the user is happy
                        pass
                    else:
                        # Restart outer loop - the user wants to pick again
                        isAMod = False

            # The user may have created a new mod in the MO mods directory, so we must trigger a refresh
            self.__organizer.refreshModList()
            self.__organizer.setPluginSetting(self.name(), "output-logs-path",
                                              path)
        return path
Exemple #30
0
 def NextConfirm(self):
     res = QMessageBox.question(
         self, ('确认进入下一步吗?'), ('确认选择'),
         QMessageBox.StandardButtons(QMessageBox.Yes | QMessageBox.No))
     if res == QMessageBox.No: return False
     return True