def qmb_exclude_geometries(): """ :return: """ msgBox = QMessageBox() msgBox.setText( 'Choose which type of polygons you would like to delete? All polygons based on your selection will be deleted!' ) msgBox.setWindowTitle("BAWS (%s) Question" % __version__) red_button = msgBox.addButton('Only red', QMessageBox.YesRole) yellow_button = msgBox.addButton('Only yellow', QMessageBox.NoRole) both_button = msgBox.addButton('Both red and yellow', QMessageBox.ActionRole) cancel_button = msgBox.addButton('Cancel', QMessageBox.RejectRole) msgBox.exec_() if msgBox.clickedButton() == red_button: return [3] elif msgBox.clickedButton() == yellow_button: return [2] elif msgBox.clickedButton() == both_button: return [2, 3] elif msgBox.clickedButton() == cancel_button: return [] else: return []
def finished(self, result): self.progress.close() if self.feasibleConfiguration and self.testConfiguration: msgBox = QMessageBox() msgBox.setStandardButtons(QMessageBox.Yes) msgBox.addButton(QMessageBox.No) msgBox.setWindowTitle("Automatic Detection Successful") msgBox.setText(self.message) if msgBox.exec() != QMessageBox.Yes: return else: self.comboBox.addItem(self.triplestorename) self.tripleStoreChooser.addItem(self.triplestorename) index = len(self.triplestoreconf) self.triplestoreconf.append({}) self.triplestoreconf[index] = self.configuration self.addTripleStore = False self.prefixes.append("") for prefix in self.configuration["prefixes"]: self.prefixes[ index] += "PREFIX " + prefix + ":<" + self.configuration[ "prefixes"][prefix] + ">\n" elif self.feasibleConfiguration: msgBox = QMessageBox() msgBox.setText(self.message) msgBox.setWindowTitle("Automatic Detection Successful") msgBox.exec() else: msgBox = QMessageBox() msgBox.setText(self.message) msgBox.setWindowTitle("Automatic Detection Failed") msgBox.exec() iface.messageBar().pushMessage("Detect Triple Store Configuration", "OK", level=Qgis.Success)
def open_copyright_message(dialog: QDialog): """Display a window to bring a reminder of the OSM copyrights.""" def read_copyright(): open_webpage('https://www.openstreetmap.org/copyright') set_setting("copyright_dialog", "OpenStreetMap") def know_copyright(): set_setting("copyright_dialog", "OpenStreetMap") if not get_setting("copyright_dialog"): message = QMessageBox(dialog) text = tr( 'OpenStreetMap® is open data, licensed under the' ' Open Data Commons Open Database License (ODbL) ' 'by the OpenStreetMap Foundation.' ) + '\n' text += tr( 'The Foundation requires that you use the credit ' '“© OpenStreetMap contributors” on any product using OSM data.' ) + '\n' text += tr( 'You should read https://www.openstreetmap.org/copyright' ) message.setText(text) message.setIcon(QMessageBox.Question) no_button = QPushButton(tr('I understand the copyrights, access to the plugin'), message) yes_button = QPushButton(tr('I want to read the copyrights'), message) message.addButton(no_button, QMessageBox.NoRole) message.addButton(yes_button, QMessageBox.YesRole) yes_button.clicked.connect(read_copyright) no_button.clicked.connect(know_copyright) message.exec()
def deLayer(self): if len(self.tableView_2.selectedIndexes())!=1: return msgBox = QMessageBox() msgBox.setInformativeText("Do you delete the layer?") msgBox.addButton(QMessageBox.Yes) msgBox.addButton(QMessageBox.No) msgBox.setDefaultButton(QMessageBox.No) msgBox.setWindowTitle("Confirmation") msgBox.setIcon(QMessageBox.Question) if msgBox.exec_() == QMessageBox.Yes: self.db.open() idx = self.tableView_2.selectionModel().selectedIndexes()[0] tname = str(self.model2.itemData(idx)[0]) sql = "drop table %s" % tname q = self.db.exec_(sql) sql = "delete from geometry_columns where f_table_name='%s'" % tname q = self.db.exec_(sql) sql = "delete from geometry_columns_auth where f_table_name='%s'" % tname q = self.db.exec_(sql) sql = "delete from geometry_columns_field_infos where f_table_name='%s'" % tname q = self.db.exec_(sql) sql = "delete from geometry_columns_statistics where f_table_name='%s'" % tname q = self.db.exec_(sql) sql = "delete from geometry_columns_time where f_table_name='%s'" % tname q = self.db.exec_(sql) self.db.commit() self.db.close() self.loadLayers()
def show_message_associate_geometry_creation(self, message): msg = QMessageBox(self) msg.setIcon(QMessageBox.Question) msg.setText(message) msg.setWindowTitle( QCoreApplication.translate(self.WIZARD_NAME, "Continue editing?")) msg.addButton( QPushButton(QCoreApplication.translate(self.WIZARD_NAME, "Yes")), QMessageBox.YesRole) msg.addButton( QPushButton( QCoreApplication.translate(self.WIZARD_NAME, "Close wizard")), QMessageBox.NoRole) reply = msg.exec_() if reply == 1: # 1 close wizard, 0 yes # stop edition in close_wizard crash qgis if self._layers[self.EDITING_LAYER_NAME][LAYER].isEditable(): self._layers[self.EDITING_LAYER_NAME][LAYER].rollBack() message = QCoreApplication.translate( self.WIZARD_NAME, "'{}' tool has been closed.").format(self.WIZARD_TOOL_NAME) self.close_wizard(message) else: # Continue creating geometry pass
def mbox_with_parent_params(wdg_parent, title, text, informative_text): mbox = QMessageBox(wdg_parent) mbox.setTextFormat(Qt.RichText) mbox.setWindowTitle(title) mbox.setText(text) mbox.setInformativeText(informative_text) mbox.addButton("OK", QMessageBox.AcceptRole) mbox.setIcon(QMessageBox.Warning) return mbox
def CustomMessage(title, msg, informative="", icon="Critical"): ''' Custom Informative Message ''' d = QMessageBox() d.setWindowTitle(title) d.setText(msg) d.setInformativeText(informative) d.setIconPixmap(QgsUtils.GetIcon(icon)) d.addButton(QMessageBox.Yes) d.addButton(QMessageBox.No) d.setDefaultButton(QMessageBox.No) ret = d.exec_() return ret
def __init__(self): """ Initialize data objects, starts fetching if appropriate, and warn about/removes obsolete plugins """ QObject.__init__( self) # initialize QObject in order to to use self.tr() repositories.load() plugins.getAllInstalled() if repositories.checkingOnStart() and repositories.timeForChecking( ) and repositories.allEnabled(): # start fetching repositories self.statusLabel = QLabel(iface.mainWindow().statusBar()) iface.mainWindow().statusBar().addPermanentWidget(self.statusLabel) self.statusLabel.linkActivated.connect( self.showPluginManagerWhenReady) repositories.checkingDone.connect(self.checkingDone) for key in repositories.allEnabled(): repositories.requestFetching(key) else: # no fetching at start, so mark all enabled repositories as requesting to be fetched. for key in repositories.allEnabled(): repositories.setRepositoryData(key, "state", 3) # look for obsolete plugins updates (the user-installed one is older than the core one) for key in plugins.obsoletePlugins: plugin = plugins.localCache[key] msg = QMessageBox() msg.setIcon(QMessageBox.Warning) msg.setWindowTitle(self.tr("QGIS Python Plugin Installer")) msg.addButton(self.tr("Uninstall (recommended)"), QMessageBox.AcceptRole) msg.addButton(self.tr("I will uninstall it later"), QMessageBox.RejectRole) msg.setText("%s <b>%s</b><br/><br/>%s" % ( self.tr("Obsolete plugin:"), plugin["name"], self. tr("QGIS has detected an obsolete plugin that masks its more recent version shipped with this copy of QGIS. This is likely due to files associated with a previous installation of QGIS. Do you want to remove the old plugin right now and unmask the more recent version?" ))) msg.exec_() if not msg.result(): settings = QgsSettings() plugin_is_active = settings.value("/PythonPlugins/" + key, False, type=bool) # uninstall the update, update utils and reload if enabled self.uninstallPlugin(key, quiet=True) updateAvailablePlugins() if plugin_is_active: settings.setValue("/PythonPlugins/watchDog/" + key, True) loadPlugin(key) startPlugin(key) settings.remove("/PythonPlugins/watchDog/" + key)
def deleteOperation(self): message = QMessageBox() message.setModal(True) message.setWindowTitle(u'Remover operação?') message.setIcon(QMessageBox.Warning) message.setText(u"Tem a certeza que pretende remover a operação?") message.addButton(u'Remover', QMessageBox.AcceptRole) message.addButton(u'Cancelar', QMessageBox.RejectRole) ret = message.exec_() if ret == QMessageBox.AcceptRole: self.parent.remove_operation(self) else: return
def custom_ask(parent, title, question, *buttons_labels): """Ask for custom operation confirmation.""" msg_box = QMessageBox(parent) msg_box.setIcon(QMessageBox.Question) msg_box.setWindowTitle(title) msg_box.setTextFormat(Qt.RichText) msg_box.setText(question) for button_txt in buttons_labels: msg_box.addButton(QPushButton(button_txt), QMessageBox.YesRole) msg_box.exec_() clicked_button = msg_box.clickedButton() clicked_button_text = clicked_button.text() return clicked_button_text
def __init__(self): """ Initialize data objects, starts fetching if appropriate, and warn about/removes obsolete plugins """ QObject.__init__(self) # initialize QObject in order to to use self.tr() repositories.load() plugins.getAllInstalled() if repositories.checkingOnStart() and repositories.timeForChecking() and repositories.allEnabled(): # start fetching repositories self.statusLabel = QLabel(self.tr("Looking for new plugins...") + " ", iface.mainWindow().statusBar()) iface.mainWindow().statusBar().insertPermanentWidget(0, self.statusLabel) self.statusLabel.linkActivated.connect(self.showPluginManagerWhenReady) repositories.checkingDone.connect(self.checkingDone) for key in repositories.allEnabled(): repositories.requestFetching(key) else: # no fetching at start, so mark all enabled repositories as requesting to be fetched. for key in repositories.allEnabled(): repositories.setRepositoryData(key, "state", 3) # look for obsolete plugins (the user-installed one is newer than core one) for key in plugins.obsoletePlugins: plugin = plugins.localCache[key] msg = QMessageBox() msg.setIcon(QMessageBox.Warning) msg.setWindowTitle(self.tr("QGIS Python Plugin Installer")) msg.addButton(self.tr("Uninstall (recommended)"), QMessageBox.AcceptRole) msg.addButton(self.tr("I will uninstall it later"), QMessageBox.RejectRole) msg.setText( "%s <b>%s</b><br/><br/>%s" % ( self.tr("Obsolete plugin:"), plugin["name"], self.tr( "QGIS has detected an obsolete plugin that masks its more recent version shipped with this copy of QGIS. This is likely due to files associated with a previous installation of QGIS. Do you want to remove the old plugin right now and unmask the more recent version?" ), ) ) msg.exec_() if not msg.result(): # uninstall, update utils and reload if enabled self.uninstallPlugin(key, quiet=True) updateAvailablePlugins() settings = QSettings() if settings.value("/PythonPlugins/" + key, False, type=bool): settings.setValue("/PythonPlugins/watchDog/" + key, True) loadPlugin(key) startPlugin(key) settings.remove("/PythonPlugins/watchDog/" + key)
def deLayer(self): if len(self.tableView_layers.selectedIndexes()) != 1: return msgBox = QMessageBox() msgBox.setInformativeText("Do you delete the layer?") msgBox.addButton(QMessageBox.Yes) msgBox.addButton(QMessageBox.No) msgBox.setDefaultButton(QMessageBox.No) msgBox.setWindowTitle("Confirmation") msgBox.setIcon(QMessageBox.Question) if msgBox.exec_() == QMessageBox.Yes: self.db.open() idx = self.tableView_layers.selectionModel().selectedIndexes()[0] tname = str(self.model2.itemData(idx)[0]) #Check if layer is loaded on the TOC. #If layer is present will be removed and added from the TOC lyrs = [ layer for layer in QgsProject.instance().mapLayers().values() ] for l in lyrs: if type(l).__name__ == 'QgsVectorLayer': if tname == l.name(): #TODO: how get the self.db path or database name? if l.providerType() == 'spatialite': QgsProject.instance().removeMapLayer(l.id()) sql = "drop table %s" % tname q = self.db.exec_(sql) sql = "delete from geometry_columns where f_table_name='%s'" % tname q = self.db.exec_(sql) sql = "delete from geometry_columns_auth where f_table_name='%s'" % tname q = self.db.exec_(sql) sql = "delete from geometry_columns_field_infos where f_table_name='%s'" % tname q = self.db.exec_(sql) sql = "delete from geometry_columns_statistics where f_table_name='%s'" % tname q = self.db.exec_(sql) sql = "delete from geometry_columns_time where f_table_name='%s'" % tname q = self.db.exec_(sql) self.db.commit() self.db.close() self.loadLayers()
def qmb_change_attribute_value(): """ :return: """ msgBox = QMessageBox() msgBox.setText('Swap geometry class values with..') msgBox.setWindowTitle("BAWS (%s) Question" % __version__) red_button = msgBox.addButton('Red (3)', QMessageBox.YesRole) yellow_button = msgBox.addButton('Yellow (2)', QMessageBox.NoRole) cancel_button = msgBox.addButton('Cancel', QMessageBox.RejectRole) msgBox.exec_() if msgBox.clickedButton() == red_button: return 3 elif msgBox.clickedButton() == yellow_button: return 2 elif msgBox.clickedButton() == cancel_button: return None else: return None
def CustomMessage(title, msg, informative="", icon="Critical"): ''' Custom Informative Message ''' d = QMessageBox() d.setTextFormat(Qt.RichText) d.setWindowTitle(title) d.setWindowIcon(QIcon(QPixmap(":/imgFMV/images/icon.png"))) d.setText(msg) d.setInformativeText(informative) d.setIconPixmap(QgsUtils.GetIcon(icon)) d.addButton(QMessageBox.Yes) d.addButton(QMessageBox.No) d.setDefaultButton(QMessageBox.No) # Trick resize QMessageBox horizontalSpacer = QSpacerItem(500, 0, QSizePolicy.Minimum, QSizePolicy.Expanding) layout = d.layout() layout.addItem(horizontalSpacer, layout.rowCount(), 0, 1, layout.columnCount()) ret = d.exec_() return ret
def finished(self, result): self.progress.close() if self.feasibleConfiguration and self.testConfiguration: msgBox=QMessageBox() msgBox.setStandardButtons(QMessageBox.Yes) msgBox.addButton(QMessageBox.No) msgBox.setWindowTitle("Automatic Detection Successful") msgBox.setText(self.message) if msgBox.exec()!=QMessageBox.Yes: return else: self.comboBox.addItem(self.triplestorename) if self.tripleStoreChooser!=None: self.tripleStoreChooser.addItem(self.triplestorename) index=len(self.triplestoreconf) self.triplestoreconf.append({}) self.triplestoreconf[index]=self.configuration self.addTripleStore=False self.prefixes.append("") for prefix in self.configuration["prefixes"]: self.prefixes[index]+="PREFIX "+prefix+":<"+self.configuration["prefixes"][prefix]+">\n" if self.permanentAdd!=None and self.permanentAdd: __location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))) f = open(os.path.join(__location__, 'triplestoreconf_personal.json'), "w") f.write(json.dumps(self.triplestoreconf,indent=2)) f.close() if self.parentdialog!=None: self.parentdialog.close() elif self.feasibleConfiguration: msgBox=QMessageBox() msgBox.setText(self.message) msgBox.setWindowTitle("Automatic Detection Successful") msgBox.exec() else: msgBox=QMessageBox() msgBox.setText(self.message) msgBox.setWindowTitle("Automatic Detection Failed") msgBox.exec() iface.messageBar().pushMessage("Detect Triple Store Configuration", "OK", level=Qgis.Success)
def qmb_reanalysis(): """ :return: """ msgBox = QMessageBox() msgBox.setText( 'You have selected an old date. \nWould you like to load raw data or old data from a previous production work?' ) msgBox.setWindowTitle("BAWS (%s) Question" % __version__) raw_button = msgBox.addButton('Raw data', QMessageBox.YesRole) old_button = msgBox.addButton('Old production data', QMessageBox.NoRole) cancel_button = msgBox.addButton('Cancel', QMessageBox.RejectRole) msgBox.exec_() if msgBox.clickedButton() == raw_button: return 'raw' elif msgBox.clickedButton() == old_button: return 'old' elif msgBox.clickedButton() == cancel_button: return None else: return None
def mergePullRequest(self): # import pydevd # pydevd.settrace('localhost', port=65432, stdoutToServer=True, stderrToServer=True, # trace_only_current_thread=False, overwrite_prev_trace=True, patch_multiprocessing=True, # suspend=False) pr = self.prs[self.comboPr.currentText()] merged = self.server.mergePullRequest(self.user, self.repo, pr["id"]) if not merged: msgBox = QMessageBox() msgBox.setText("Conflicts in PR") msgBox.setInformativeText( "There are conflicts.\n" "Source repo needs to be synchronized and conflicts solved.\n" "This will modify the source repo.") msgBox.setIcon(QMessageBox.Warning) syncButton = msgBox.addButton("Continue", QMessageBox.ActionRole) abortButton = msgBox.addButton(QMessageBox.Abort) msgBox.exec_() if msgBox.clickedButton() == syncButton: # do sync syncDialog = SynchronizeDialog( pr["sourceRepo"]["owner"]["identity"], pr["sourceRepo"]["identity"], self.server, pr["targetRepo"]["owner"]["identity"], pr["targetRepo"]["identity"], False) syncDialog.exec_() if syncDialog.synced: self.mergePullRequest() else: self.close() elif msgBox.clickedButton() == abortButton: self.close() else: self.close()
def exportVersion(self, repo, layer, commitId): trackedlayer = getTrackingInfoForGeogigLayer(repo.url, layer) if trackedlayer: if os.path.exists(trackedlayer.geopkg): try: con = sqlite3.connect(trackedlayer.geopkg) cursor = con.cursor() cursor.execute( "SELECT commit_id FROM geogig_audited_tables WHERE table_name='%s';" % layer) currentCommitId = cursor.fetchone()[0] cursor.close() con.close() if commitId != currentCommitId: msgBox = QMessageBox() msgBox.setWindowTitle("Layer was already exported") msgBox.setText( "This layer was exported already at a different commit.\n" "Which one would you like to add to your QGIS project?" ) msgBox.addButton( QPushButton('Use previously exported commit'), QMessageBox.YesRole) msgBox.addButton( QPushButton('Use latest commit from this branch'), QMessageBox.NoRole) msgBox.addButton(QPushButton('Cancel'), QMessageBox.RejectRole) QApplication.restoreOverrideCursor() ret = msgBox.exec_() if ret == 0: checkoutLayer(repo, layer, None, currentCommitId) elif ret == 1: try: layer = checkoutLayer(repo, layer, None, commitId) repoWatcher.layerUpdated.emit(layer) except HasLocalChangesError: QMessageBox.warning( config.iface.mainWindow(), 'Cannot export this commit', "The layer has local changes that would be overwritten.\n" "Either sync layer with branch or revert local changes " "before changing commit", QMessageBox.Ok) except: checkoutLayer(repo, layer, None, currentCommitId) else: checkoutLayer(repo, layer, None, commitId)
def solveModifyAndDelete(self, path, modified): msgBox = QMessageBox() msgBox.setText("The feature has been modified in one version and deleted in the other one.\n" "How do you want to solve the conflict?") msgBox.addButton(QPushButton('Modify'), QMessageBox.YesRole) msgBox.addButton(QPushButton('Delete'), QMessageBox.NoRole) msgBox.addButton(QPushButton('Cancel'), QMessageBox.RejectRole) ret = msgBox.exec_() if ret == 0: self.resolvedConflicts[path] = modified self._afterSolve() elif ret == 1: self.resolvedConflicts[path] = self.DELETE self._afterSolve() else: pass
def solveModifyAndDelete(self, path, modified): msgBox = QMessageBox() msgBox.setText( "The feature has been modified in one version and deleted in the other one.\n" "How do you want to solve the conflict?") msgBox.addButton(QPushButton('Modify'), QMessageBox.YesRole) msgBox.addButton(QPushButton('Delete'), QMessageBox.NoRole) msgBox.addButton(QPushButton('Cancel'), QMessageBox.RejectRole) ret = msgBox.exec_() if ret == 0: self.resolvedConflicts[path] = modified self._afterSolve() elif ret == 1: self.resolvedConflicts[path] = self.DELETE self._afterSolve() else: pass
def __init__(self, question="YesNo", msg = '', dialogtitle='User input needed', parent=None): self.result = '' if question == 'YesNo': # Yes/No dialog reply = QMessageBox.information(parent, dialogtitle, msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if reply==QMessageBox.Yes: self.result = 1 #1 = "yes" else: self.result = 0 #0="no" elif question == 'AllSelected': # All or Selected Dialog btnAll = QPushButton("All") # = "0" btnSelected = QPushButton("Selected") # = "1" #btnAll.clicked.connect(lambda x: self.DoForAll()) #btnSelected.clicked.connect(lambda x: self.DoForSelected()) msgBox = QMessageBox(parent) msgBox.setText(msg) msgBox.setWindowTitle(dialogtitle) #msgBox.setWindowModality(Qt.ApplicationModal) msgBox.addButton(btnAll, QMessageBox.ActionRole) msgBox.addButton(btnSelected, QMessageBox.ActionRole) msgBox.addButton(QMessageBox.Cancel) reply = msgBox.exec_() self.result = reply # ALL=0, SELECTED=1 elif question == 'DateShift': supported_units = ['microseconds', 'milliseconds', 'seconds', 'minutes', 'hours', 'days', 'weeks'] while True: answer = str(QInputDialog.getText(None, "User input needed", "Give needed adjustment of date/time for the data.\nSupported format: +- X <resolution>\nEx: 1 hours, -1 hours, -1 days\nSupported units:\n%s"%', '.join(supported_units), QLineEdit.Normal, '0 hours')[0]) if not answer: self.result = 'cancel' break else: adjustment_unit = answer.split() if len(adjustment_unit) == 2: if adjustment_unit[1] in supported_units: self.result = adjustment_unit break else: pop_up_info("Failure:\nOnly support resolutions\n%s"%', '.join(supported_units)) else: pop_up_info("Failure:\nMust write time resolution also.\n")
def exportVersion(self, repo, layer, commitId): trackedlayer = getTrackingInfoForGeogigLayer(repo.url, layer) if trackedlayer: if os.path.exists(trackedlayer.geopkg): try: con = sqlite3.connect(trackedlayer.geopkg) cursor = con.cursor() cursor.execute("SELECT commit_id FROM geogig_audited_tables WHERE table_name='%s';" % layer) currentCommitId = cursor.fetchone()[0] cursor.close() con.close() if commitId != currentCommitId: msgBox = QMessageBox() msgBox.setWindowTitle("Layer was already exported") msgBox.setText("This layer was exported already at a different commit.\n" "Which one would you like to add to your QGIS project?") msgBox.addButton(QPushButton('Use previously exported commit'), QMessageBox.YesRole) msgBox.addButton(QPushButton('Use latest commit from this branch'), QMessageBox.NoRole) msgBox.addButton(QPushButton('Cancel'), QMessageBox.RejectRole) QApplication.restoreOverrideCursor() ret = msgBox.exec_() if ret == 0: checkoutLayer(repo, layer, None, currentCommitId) elif ret == 1: try: layer = checkoutLayer(repo, layer, None, commitId) repoWatcher.layerUpdated.emit(layer) except HasLocalChangesError: QMessageBox.warning(config.iface.mainWindow(), 'Cannot export this commit', "The layer has local changes that would be overwritten.\n" "Either sync layer with branch or revert local changes " "before changing commit",QMessageBox.Ok) except: checkoutLayer(repo, layer, None, currentCommitId) else: checkoutLayer(repo, layer, None, commitId)
def installFromZipFile(self, filePath): if not os.path.isfile(filePath): return settings = QgsSettings() settings.setValue(settingsGroup + '/lastZipDirectory', QFileInfo(filePath).absoluteDir().absolutePath()) with zipfile.ZipFile(filePath, 'r') as zf: pluginName = os.path.split(zf.namelist()[0])[0] pluginFileName = os.path.splitext(os.path.basename(filePath))[0] if not pluginName: msg_box = QMessageBox() msg_box.setIcon(QMessageBox.Warning) msg_box.setWindowTitle(self.tr("QGIS Python Install from ZIP Plugin Installer")) msg_box.setText(self.tr("The Zip file is not a valid QGIS python plugin. No root folder was found inside.")) msg_box.setStandardButtons(QMessageBox.Ok) more_info_btn = msg_box.addButton(self.tr("More Information"), QMessageBox.HelpRole) msg_box.exec() if msg_box.clickedButton() == more_info_btn: QgsHelp.openHelp("plugins/plugins.html#the-install-from-zip-tab") return pluginsDirectory = qgis.utils.home_plugin_path if not QDir(pluginsDirectory).exists(): QDir().mkpath(pluginsDirectory) pluginDirectory = QDir.cleanPath(os.path.join(pluginsDirectory, pluginName)) # If the target directory already exists as a link, # remove the link without resolving QFile(pluginDirectory).remove() password = None infoString = None success = False keepTrying = True while keepTrying: try: # Test extraction. If fails, then exception will be raised and no removing occurs unzip(filePath, pluginsDirectory, password) # Removing old plugin files if exist removeDir(pluginDirectory) # Extract new files unzip(filePath, pluginsDirectory, password) keepTrying = False success = True except Exception as e: success = False if 'password' in str(e): infoString = self.tr('Aborted by user') if 'Bad password' in str(e): msg = self.tr('Wrong password. Please enter a correct password to the zip file.') else: msg = self.tr('The zip file is encrypted. Please enter password.') # Display a password dialog with QgsPasswordLineEdit dlg = QDialog() dlg.setWindowTitle(self.tr('Enter password')) buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal) buttonBox.rejected.connect(dlg.reject) buttonBox.accepted.connect(dlg.accept) lePass = QgsPasswordLineEdit() layout = QVBoxLayout() layout.addWidget(QLabel(msg)) layout.addWidget(lePass) layout.addWidget(buttonBox) dlg.setLayout(layout) keepTrying = dlg.exec_() password = lePass.text() else: infoString = self.tr("Failed to unzip the plugin package\n{}.\nProbably it is broken".format(filePath)) keepTrying = False if success: updateAvailablePlugins() self.processDependencies(pluginName) loadPlugin(pluginName) plugins.getAllInstalled() plugins.rebuild() if settings.contains('/PythonPlugins/' + pluginName): if settings.value('/PythonPlugins/' + pluginName, False, bool): startPlugin(pluginName) reloadPlugin(pluginName) else: unloadPlugin(pluginName) loadPlugin(pluginName) else: if startPlugin(pluginName): settings.setValue('/PythonPlugins/' + pluginName, True) self.exportPluginsToManager() msg = "<b>%s</b>" % self.tr("Plugin installed successfully") else: msg = "<b>%s:</b> %s" % (self.tr("Plugin installation failed"), infoString) level = Qgis.Info if success else Qgis.Critical iface.pluginManagerInterface().pushMessage(msg, level)
def run(self): """Plugin initial run""" if platform.system() == 'Linux': try: from lxml import etree except ImportError: message = QMessageBox() message.setModal(True) message.setWindowTitle(u'Módulo LXML Não Instalado') message.setWindowIcon( QIcon(":/resourcesFolder/icons/main_icon.png")) message.setIcon(QMessageBox.Critical) message.setInformativeText( u"<a href=\"http://lxml.de/installation.html\">Como instalar</a>" ) message.setText( u"O plugin necessita do módulo Lxml instalado.") message.addButton(u'Sair', QMessageBox.RejectRole) message.exec_() return if os.path.exists( os.path.join(os.path.dirname(__file__), "userFiles/.meLock")): message = QMessageBox() message.setModal(True) message.setWindowTitle(u'O Editor já se encontra a correr?') message.setWindowIcon( QIcon(":/resourcesFolder/icons/main_icon.png")) message.setIcon(QMessageBox.Warning) message.setText( u"Verifique,\npor favor, se já existe outra instância do Editor de Metadados aberta.\n" u"Só é permitida uma instância para evitar conflitos.") message.setInformativeText(u"Deseja continuar?") message.addButton(u'Continuar', QMessageBox.AcceptRole) message.addButton(u'Sair', QMessageBox.RejectRole) ret = message.exec_() if ret != QMessageBox.AcceptRole: return # Create and display the splash screen splash_pix = QPixmap(":/resourcesFolder/splash.png") splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) #splash.showMessage("A Carregar...", alignment=Qt.AlignBottom | Qt.AlignHCenter, color=Qt.white) splash.setWindowFlags(splash.windowFlags() | Qt.WindowStaysOnTopHint) splash.show() QApplication.processEvents() start = time.time() while time.time() < start + 2: QApplication.processEvents() splash.close() f = open(os.path.join(os.path.dirname(__file__), "userFiles/.meLock"), "w") f.close() self.dialog = editorMetadadosMarswInforbiomares.EditorMetadadosMarswInforbiomares( self._iface, self) self.dialog.setWindowIcon( QIcon(":/resourcesFolder/icons/main_icon.png")) self.dialog.show()
def installBaseMap(self): authcfg = get_oauth_authcfg() if authcfg is None: self._showMessage('Could not find a valid authentication configuration!', QgsMessageBar.WARNING) return False authId = authcfg.id() mapBoxStreets = basemaputils.getMapBoxStreetsMap(self.token) if os.path.isfile(basemaputils.defaultProjectPath()): # default project already exists, make a backup copy backup = basemaputils.defaultProjectPath().replace( '.qgs', '-%s.qgs' % datetime.now().strftime('%Y-%m-%d-%H_%M_%S')) shutil.copy2(basemaputils.defaultProjectPath(), backup) self._showMessage("A backup copy of the previous default project " "has been saved to {}".format(backup)) msgBox = QMessageBox() msgBox.setIcon(QMessageBox.Question) msgBox.setText("A default project already exists. Do you " "wish to add the Boundless basemap to your " "existing default project or create a new " "default project?") btnAdd = msgBox.addButton("Add", QMessageBox.ActionRole) btnCreateNew = msgBox.addButton("Create New", QMessageBox.ActionRole) msgBox.exec_() if msgBox.clickedButton() == btnAdd: if not basemaputils.addToDefaultProject([mapBoxStreets], ["Mapbox Streets"], authId): self._showMessage("Could not update default project with basemap!", QgsMessageBar.WARNING) return False elif msgBox.clickedButton() == btnCreateNew: template = basemaputils.PROJECT_DEFAULT_TEMPLATE prj = basemaputils.createDefaultProject([mapBoxStreets], ["Mapbox Streets"], template, authId) if prj is None or prj == '': self._showMessage("Could not create a valid default project from the template '{}'!".format(template), QgsMessageBar.WARNING) return False if not basemaputils.writeDefaultProject(prj): self._showMessage("Could not write the default project on disk!", QgsMessageBar.WARNING) return False else: # no default project, create one template = basemaputils.PROJECT_DEFAULT_TEMPLATE prj = basemaputils.createDefaultProject([mapBoxStreets], ["Mapbox Streets"], template, authId) if prj is None or prj == '': self._showMessage("Could not create a valid default project from the template '{}'!".format(template), QgsMessageBar.WARNING) return False if not basemaputils.writeDefaultProject(prj): self._showMessage("Could not write the default project on disk!", QgsMessageBar.WARNING) return False self._showMessage("Basemap added to the default project.") return True