def run(self): appdef = None projFile = QgsProject.instance().fileName() if projFile: appdefFile = projFile + ".appdef" if os.path.exists(appdefFile): if pluginSetting("askreload") == "Ask": ret = QMessageBox.question( self.iface.mainWindow(), "Web app builder", "This project has been already published as a web app.\n" "Do you want to reload app configuration?", QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if ret == QMessageBox.Yes: appdef = loadAppdef(appdefFile) elif pluginSetting("askreload") == "Open last configuration": appdef = loadAppdef(appdefFile) initialize() # reset credential token in case related credentials are changed utils.resetCachedToken() try: dlg = MainDialog(appdef) dlg.exec_() except: dlg.progressBar.setMaximum(100) dlg.progressBar.setValue(0) dlg.progressBar.setVisible(False) dlg.progressLabel.setVisible(False) QApplication.restoreOverrideCursor() QgsMessageLog.logMessage(traceback.format_exc(), "WebAppBuilder", level=QgsMessageLog.CRITICAL) QMessageBox.critical( self.iface.mainWindow(), "Unmanaged error. See QGIS log for more details.")
def refreshContent(self): showDescription = pluginSetting( "ShowDescription", "geoserverexplorer", typ=bool) or True self.description.setVisible(showDescription) showToolbar = pluginSetting( "ShowToolbar", "geoserverexplorer", typ=bool) or True self.toolbar.setVisible(showToolbar) self.refreshDescription()
def setScaleFactor(): """Manage size scale factor basing if QGIS is able to manage or not SLD unit parameter (uom). """ global SIZE_FACTOR if pluginSetting("SldUomManaging"): SIZE_FACTOR = SIZE_FACTOR_IF_UOM else: SIZE_FACTOR = SIZE_FACTOR_IF_NO_UOM if pluginSetting("SldScaleFactor"): SIZE_FACTOR = pluginSetting("SldScaleFactor")
def initConfigParams(self): folder = pluginSetting("gpkgfolder") if folder.strip() == "": setPluginSetting( "gpkgfolder", os.path.join(os.path.expanduser('~'), 'geogig', 'repos')) folder = pluginSetting("difffolder") if folder.strip() == "": setPluginSetting( "difffolder", os.path.join(os.path.expanduser('~'), 'geogig', 'diff'))
def testCustomRepoUrl(self): """Test that Connect read custom repository URL and apply it""" oldRepoUrl = pluginSetting('repoUrl') setPluginSetting('repoUrl', 'test') self.assertEqual('test', pluginSetting('repoUrl')) fName = os.path.join(QgsApplication.qgisSettingsDirPath(), repoUrlFile) with open(fName, 'w') as f: f.write('[general]\nrepoUrl=http://dummyurl.com') utils.setRepositoryUrl() self.assertTrue('http://dummyurl.com', pluginSetting('repoUrl')) setPluginSetting('repoUrl', oldRepoUrl) if os.path.isfile(fName): os.remove(fName)
def preprocess(self, layer): ''' Preprocesses the layer with the corresponding preprocess hook and returns the path to the resulting layer. If no preprocessing is performed, it returns the input layer itself ''' if not processingOk: return layer if layer.type() == layer.RasterLayer: try: hookFile = pluginSetting("PreuploadRasterHook") if hookFile: alg = self.getAlgorithmFromHookFile(hookFile) if (len(alg.parameters) == 1 and isinstance(alg.parameters[0], ParameterRaster) and len(alg.outputs) == 1 and isinstance(alg.outputs[0], OutputRaster)): alg.parameters[0].setValue(layer) if runalg(alg, SilentProgress()): return load(alg.outputs[0].value) return layer else: return layer except: QgsMessageLog.logMessage( "Could not apply hook to layer upload. Wrong Hook", level=QgsMessageLog.WARNING) return layer elif layer.type() == layer.VectorLayer: try: hookFile = pluginSetting("PreuploadVectorHook") if hookFile: alg = self.getAlgorithmFromHookFile(hookFile) if (len(alg.parameters) == 1 and isinstance(alg.parameters[0], ParameterVector) and len(alg.outputs) == 1 and isinstance(alg.outputs[0], OutputVector)): alg.parameters[0].setValue(layer) if runalg(alg, SilentProgress()): return load(alg.outputs[0].value) return layer else: return layer except: QgsMessageLog.logMessage( "Could not apply hook to layer upload. Wrong Hook", level=QgsMessageLog.WARNING) return layer
def updatePublishedStyle(layer): global _currentMessageBarLayer track = pluginSetting("TrackLayers") if track and isTrackedLayer(layer): if iface.messageBar().currentItem() is None: _resetCurrentMessageBarLayer() if _currentMessageBarLayer != layer: _currentMessageBarLayer = layer widget = iface.messageBar().createMessage("", "This layer was uploaded to a geoserver catalog. Do you want to update the published style?") updateButton = QtWidgets.QPushButton(widget) updateButton.setText("Update") def updateStyle(): url = getTrackingInfo(layer) catalog = Catalog(url) wrapper = CatalogWrapper(catalog) wrapper.publishStyle(layer) iface.messageBar().popWidget() _resetCurrentMessageBarLayer() updateButton.pressed.connect(updateStyle) widget.layout().addWidget(updateButton) stopTrackingButton = QtWidgets.QPushButton(widget) stopTrackingButton.setText("Stop tracking this layer") def stopTracking(): removeTrackedLayer(layer) iface.messageBar().popWidget() _resetCurrentMessageBarLayer() stopTrackingButton.pressed.connect(stopTracking) widget.layout().addWidget(stopTrackingButton) iface.messageBar().pushWidget(widget, Qgis.Info) iface.messageBar().currentItem().geoserverLayer = layer
def upload(self, layer, workspace=None, overwrite=True, name=None): '''uploads the specified layer''' if isinstance(layer, basestring): layer = layers.resolveLayer(layer) name = name or layer.name() title = name name = name.replace(" ", "_") restApi = pluginSetting("UseRestApi") if layer.type() not in (layer.RasterLayer, layer.VectorLayer): msg = layer.name() + ' is not a valid raster or vector layer' raise Exception(msg) provider = layer.dataProvider() try: if provider.name() == 'postgres': self._publishPostgisLayer(layer, workspace, overwrite, name) elif restApi: self._uploadRest(layer, workspace, overwrite, name) else: self._uploadImporter(layer, workspace, overwrite, name) except UploadError, e: msg = ('Could not save the layer %s, there was an upload ' 'error: %s' % (layer.name(), str(e))) e.args = (msg, ) raise
def getUserInfo(): """Return user information from the settings dialog""" user = pluginSetting(USERNAME).strip() email = pluginSetting(EMAIL).strip() if not (user and email): configdlg = UserConfigDialog(iface.mainWindow()) configdlg.exec_() if configdlg.user is not None: user = configdlg.user email = configdlg.email setPluginSetting(USERNAME, user) setPluginSetting(EMAIL, email) return user, email else: return None, None return user, email
def createGeoServerCatalog(service_url="http://localhost:8080/geoserver/rest", username="******", password="******", authid=None, authtype=None, disable_ssl_certificate_validation=False): # if not authid use basic auth if not authid or not authtype: catalog = BaseCatalog(service_url, username, password, disable_ssl_certificate_validation) elif QGis.QGIS_VERSION_INT < 21200: # if autcfg, then get certs and ca and create a PKICatalog certfile, keyfile, cafile = pem.getPemPkiPaths(authid, authtype) # set connection catalog = PKICatalog(service_url, keyfile, certfile, cafile) # set authid parameter used by uri.py functions to manage # uri creation with pki credential catalog.authid = authid else: # For QGIS > 2.12, use the new AuthCatalog and QgsNetworkAccessManager cache_time = pluginSetting("AuthCatalogXMLCacheTime") catalog = AuthCatalog(service_url, authid, cache_time) return CatalogWrapper(catalog)
def updatePublishedStyle(layer): global _currentMessageBarLayer track = pluginSetting("TrackLayers") if track and isTrackedLayer(layer): if iface.messageBar().currentItem() is None: _resetCurrentMessageBarLayer() if _currentMessageBarLayer != layer: _currentMessageBarLayer = layer widget = iface.messageBar().createMessage("", "This layer was uploaded to a geoserver catalog. Do you want to update the published style?") updateButton = QtGui.QPushButton(widget) updateButton.setText("Update") def updateStyle(): url = getTrackingInfo(layer) catalog = Catalog(url) wrapper = CatalogWrapper(catalog) wrapper.publishStyle(layer) iface.messageBar().popWidget() _resetCurrentMessageBarLayer() updateButton.pressed.connect(updateStyle) widget.layout().addWidget(updateButton) stopTrackingButton = QtGui.QPushButton(widget) stopTrackingButton.setText("Stop tracking this layer") def stopTracking(): removeTrackedLayer(layer) iface.messageBar().popWidget() _resetCurrentMessageBarLayer() stopTrackingButton.pressed.connect(stopTracking) widget.layout().addWidget(stopTrackingButton) iface.messageBar().pushWidget(widget, QgsMessageBar.INFO) iface.messageBar().currentItem().geoserverLayer = layer
def addBoundlessRepository(): """Add Boundless plugin repository to list of the available plugin repositories if it is not presented here """ repoUrl = pluginSetting('repoUrl') if repoUrl == '': repoUrl = setRepositoryUrl() if isRepositoryInDirectory(): return settings = QSettings() settings.beginGroup(reposGroup) hasBoundlessRepository = False for repo in settings.childGroups(): url = settings.value(repo + '/url', '') if url == repoUrl: hasBoundlessRepository = True # Boundless repository not found, so we add it to the list if not hasBoundlessRepository: settings.setValue(boundlessRepoName + '/url', repoUrl) settings.setValue(boundlessRepoName + '/authcfg', '') settings.endGroup()
def zoomTo(self): apikey = pluginSetting("apiKey") if apikey is None or apikey == "": self._showMessage('what3words API key is not set. Please set it and try again.', QgsMessageBar.WARNING) return self.zoomToDialog.setApiKey(apikey) self.zoomToDialog.show()
def createOrStopApp(self): # check if app is compiling if self.onCreatingApp: stopAppCreation() return # start compilation try: appdef = self.createAppDefinition() problems = checkAppCanBeCreated(appdef) if pluginSetting("compileinserver"): try: from boundlessconnect import connect except ImportError: QMessageBox.warning( self, "Cannot compile in server", "To compile the WebApp in the server, the Connect plugin is needed.\n" "Connect plugin could not be found. Install it or disable the 'Use SDK Service to compile app' option in the plugin settings", QMessageBox.Close) return QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) try: checkSDKServerVersion() except VersionMismatchError, e: problems.append(str(e)) except Exception, e: QApplication.restoreOverrideCursor() QMessageBox.warning(self, "Problem checking SDK version", str(e), QMessageBox.Close) return
def appSDKification(folder, progress): ''' zip app folder and send to WAB compiler to apply SDK compilation. The returned zip will be the official webapp ''' progress.oscillate() progress.setText("Get Authorization token") try: global __appSDKification_doAgain if __appSDKification_doAgain: QgsMessageLog.logMessage("Renew token in case of it is expired and retry", level=QgsMessageLog.WARNING) utils.resetCachedToken() token = utils.getToken() except Exception as e: pub.sendMessage(utils.topics.endAppSDKification, success=False, reason=str(e)) return # zip folder to send for compiling progress.setText("Preparing data to compile") zipFileName = tempFilenameInTempFolder("webapp.zip", "webappbuilder") try: with zipfile.ZipFile(zipFileName, "w") as zf: relativeFrom = os.path.dirname(folder) for dirname, subdirs, files in os.walk(folder): # exclude data folder if 'data' in subdirs: subdirs.remove('data') if relativeFrom in dirname: zf.write(dirname, dirname[len(relativeFrom):]) for filename in files: fiename = os.path.join(dirname, filename) zf.write(fiename, fiename[len(relativeFrom):]) except: msg = "Could not zip webapp folder: {}".format(folder) pub.sendMessage(utils.topics.endAppSDKification, success=False, reason=msg) return # prepare data for WAB compiling request with open(zipFileName, 'rb') as f: fileContent = f.read() fields = { 'file': (os.path.basename(zipFileName), fileContent) } payload, content_type = encode_multipart_formdata(fields) headers = {} headers["authorization"] = "Bearer {}".format(token) headers["Content-Type"] = content_type # prepare request (as in NetworkAccessManager) but without blocking request # do http post progress.setText("Wait compilation") global __anam if __anam: del __anam __anam = None __anam = NetworkAccessManager(debug=pluginSetting("logresponse")) __anam.request(utils.wabCompilerUrl(), method='POST', body=payload, headers=headers, blocking=False) __anam.reply.finished.connect( lambda: manageFinished(__anam, zipFileName, folder, progress) )
def confirmDelete(): askConfirmation = pluginSetting("ConfirmDelete") if not askConfirmation: return True msg = "You confirm that you want to delete the selected elements?" reply = QMessageBox.question(None, "Delete confirmation", msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.No) return reply != QMessageBox.No
def parentReposFolder(): folder = pluginSetting(config.REPOS_FOLDER) if folder.strip() == "": folder = os.path.join(os.path.expanduser('~'), 'geogig', 'repos') try: os.makedirs(folder) except os.error: pass return folder
def confirmDelete(): askConfirmation = pluginSetting("ConfirmDelete") if not askConfirmation: return True msg = "You confirm that you want to delete the selected elements?" reply = QtGui.QMessageBox.question(None, "Delete confirmation", msg, QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No) return reply != QtGui.QMessageBox.No
def setTool(self): apikey = pluginSetting("apiKey") if apikey is None or apikey == "": self._showMessage('what3words API key is not set. Please set it and try again.', QgsMessageBar.WARNING) return if self.mapTool is None: self.mapTool = W3WMapTool(self.iface.mapCanvas()) self.toolAction.setChecked(True) self.iface.mapCanvas().setMapTool(self.mapTool)
def okPressed(self): self.url = self.comboBox.currentText() endpoints = pluginSetting(self.ENDPOINTS) if endpoints: endpoints = set(endpoints.split(";")) endpoints.add(self.url) setPluginSetting(self.ENDPOINTS, ";".join(endpoints)) else: setPluginSetting(self.ENDPOINTS, self.url) self.close()
def installAllPlugins(): """Install all available plugins from Boundless plugins repository """ repoUrl = pluginSetting('repoUrl') if isRepositoryInDirectory(): pluginsDirectory = os.path.abspath(repoUrl) installAllFromDirectory(pluginsDirectory) else: installAllFromRepository()
def setTool(self): self._showMessage('Loading the images Continuosly.') self.logger.info("Loading the images Continuosly.") self.refreshInterval = pluginSetting("refreshInterval") self.doAdd = True while self.doAdd: if time.time() - self.start_time >= self.refreshInterval: self.getNewImages() self.start_time = time.time() QCoreApplication.processEvents()
def orders_download_folder(): download_folder = settings.pluginSetting(ORDERS_DOWNLOAD_FOLDER) if not os.path.exists(download_folder): try: os.makedirs(download_folder) except OSError: download_folder = os.path.join(QgsApplication.qgisSettingsDirPath(), DEFAULT_ORDERS_FOLDERNAME) if not os.path.exists(download_folder): os.makedirs(download_folder) return download_folder
def setRepositoryAuth(authConfigId): """Add auth to the repository """ repoUrl = pluginSetting('repoUrl') settings = QSettings() settings.beginGroup(reposGroup) for repo in settings.childGroups(): url = settings.value(repo + '/url', '') if url == repoUrl: settings.setValue(repo + '/authcfg', authConfigId) settings.endGroup()
def _gpkgPath(self): folder = pluginSetting("difffolder") or os.path.join(os.path.expanduser('~'), 'geogig', 'diff') filename = str(uuid.uuid4()).replace("-","") path = os.path.join(folder, self.user, self.repo) if not os.path.exists(path): try: os.makedirs(path) except: path = os.path.join(os.path.expanduser('~'), 'geogig', 'diff', self.user, self.repo) if not os.path.exists(path): os.makedirs(path) return os.path.join(path, filename + ".gpkg")
def createGeoServerCatalog(service_url = "http://localhost:8080/geoserver/rest", username="******", password="******", authid=None): # if not authid use basic auth if authid is None: catalog = BaseCatalog(service_url, username, password) else: cache_time = pluginSetting("AuthCatalogXMLCacheTime") catalog = AuthCatalog(service_url, authid, cache_time) return CatalogWrapper(catalog)
def createGeoServerCatalog(service_url="http://localhost:8080/geoserver/rest", username="******", password="******", authid=None): # if not authid use basic auth if authid is None: catalog = BaseCatalog(service_url, username, password) else: cache_time = pluginSetting("AuthCatalogXMLCacheTime") catalog = AuthCatalog(service_url, authid, cache_time) return CatalogWrapper(catalog)
def __init__(self): self.url = None super(EndpointSelectionDialog, self).__init__(None) self.setupUi(self) self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) endpoints = pluginSetting(self.ENDPOINTS) if endpoints: items = endpoints.split(";") self.comboBox.addItems(items)
def __init__(self, parent=None, iface=None, visible=False): super(PlanetExplorerDockWidget, self).__init__(parent) self.setupUi(self) self.setVisible(visible) self._iface = iface # noinspection PyArgumentList self._auth_man = QgsApplication.authManager() self.p_client = None self.api_key = None self._save_creds = bool( pluginSetting(SAVE_CREDS_KEY, namespace=SETTINGS_NAMESPACE, typ='bool')) self.leUser.addAction( QIcon(':/plugins/planet_explorer/envelope-gray.svg'), QLineEdit.LeadingPosition) self.lblSignUp.linkActivated[str].connect( lambda: open_link_with_browser(SIGNUP_URL)) self.lblTermsOfService.linkActivated[str].connect( lambda: open_link_with_browser(TOS_URL)) self.lblForgotPass.linkActivated[str].connect( lambda: open_link_with_browser(FORGOT_PASS_URL)) self.btn_ok = self.buttonBoxLogin.button(QDialogButtonBox.Ok) self.btn_ok.setText('Sign In') self.btn_api_key = self.buttonBoxLogin.button(QDialogButtonBox.Abort) """:type: QPushButton""" self.btn_api_key.setText('Use API key') self.btn_api_key.hide() self.buttonBoxLogin.accepted.connect(self.login) self.buttonBoxLogin.rejected.connect(self.api_key_login) self.tabWidgetResourceType.currentChanged[int].connect( self._item_group_changed) self._setup_daily_images_panel() self._setup_mosaics_panel() # Set default group type and filter widget self.tabWidgetResourceType.setCurrentIndex(0) # noinspection PyTypeChecker self._terms_browser = None self.msg_log = QgsMessageLog() # Local QgsMessageBar self.msgBar.hide()
def setRepositoryUrl(): """Adds Boundless repository URL to Connect settings""" fName = os.path.join(QgsApplication.qgisSettingsDirPath(), repoUrlFile) if os.path.exists(fName): cfg = ConfigParser() cfg.read(fName) url = cfg.get('general', 'repoUrl') os.remove(fName) else: url = pluginSetting('repoUrl') setPluginSetting('repoUrl', url) return url
def setUpClass(cls): # do workspace popuplation super(DeleteTests, cls).setUpClass() cls.ws = cls.cat.get_workspaces(WORKSPACE)[0] # load project projectFile = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "test.qgs") if os.path.normcase(projectFile) != os.path.normcase(QgsProject.instance().fileName()): iface.addProject(projectFile) # set flags to instruct GUI interaction cls.confirmDelete = pluginSetting("ConfirmDelete") setPluginSetting("ConfirmDelete", False)
def initGui(self): self.progressMaximum = 0 self.isProgressVisible = False self.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) self.dockWidgetContents = QWidget() self.setWindowTitle('GeoServer Explorer') self.splitter = QSplitter() self.splitter.setOrientation(Qt.Vertical) self.subwidget = QWidget() self.explorerTree = self.tree = ExplorerTreeWidget(self) showToolbar = pluginSetting( "ShowToolbar", "geoserverexplorer", typ=bool) or True self.toolbar = QToolBar() self.toolbar.setToolButtonStyle(Qt.ToolButtonIconOnly) self.toolbar.setVisible(showToolbar) self.setToolbarActions([]) self.splitter.addWidget(self.explorerTree) self.log = QTextEdit() self.description = QWidget() self.descriptionLayout = QVBoxLayout() self.descriptionLayout.setSpacing(2) self.descriptionLayout.setMargin(0) self.description.setLayout(self.descriptionLayout) self.splitter.addWidget(self.description) self.setDescriptionWidget() showDescription = pluginSetting( "ShowDescription", "geoserverexplorer", typ=bool) or True self.description.setVisible(showDescription) self.progress = None self.layout = QVBoxLayout() self.layout.setSpacing(2) self.layout.setMargin(0) self.layout.addWidget(self.toolbar) self.layout.addWidget(self.splitter) self.dockWidgetContents.setLayout(self.layout) self.setWidget(self.dockWidgetContents) self.topLevelChanged.connect(self.dockStateChanged)
def testPreuploadVectorHook(self): if not catalog.processingOk: print 'skipping testPreuploadVectorHook, processing not installed' return oldHookFile = pluginSetting("PreuploadVectorHook") hookFile = os.path.join(os.path.dirname(__file__), "resources", "vector_hook.py") setPluginSetting("PreuploadVectorHook", hookFile) try: hookFile = pluginSetting("PreuploadVectorHook") try: self.cat.getAlgorithmFromHookFile(hookFile) except: raise Exception("Processing hook cannot be executed") self.cat.publishLayer(PT1, self.ws, name=HOOK) self.assertIsNotNone(self.cat.catalog.get_layer(HOOK)) self.cat.addLayerToProject(HOOK) layer = layers.resolveLayer(HOOK) self.assertEqual(1, layer.featureCount()) QgsMapLayerRegistry.instance().removeMapLayer(layer.id()) finally: setPluginSetting("PreuploadVectorHook", oldHookFile) self.cat.catalog.delete(self.cat.catalog.get_layer(HOOK), recurse=True)
def setUpClass(cls): # do workspace popuplation super(DeleteTests, cls).setUpClass() cls.ws = cls.cat.get_workspaces(WORKSPACE)[0] # load project projectFile = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "test.qgs") if os.path.normcase(projectFile) != os.path.normcase( QgsProject.instance().fileName()): iface.addProject(projectFile) # set flags to instruct GUI interaction cls.confirmDelete = pluginSetting("ConfirmDelete") setPluginSetting("ConfirmDelete", False)
def setUpClass(cls): cls.explorer = GeoServerExplorer() # Disable cache cls.cache_time = pluginSetting("AuthCatalogXMLCacheTime") setPluginSetting("AuthCatalogXMLCacheTime", 1) cls.catWrapper = utils.getGeoServerCatalog() cls.cat = cls.catWrapper.catalog utils.populateCatalog(cls.cat) cls.catalogItem = GsCatalogItem(cls.cat, "catalog") cls.explorer.explorerTree.gsItem.addChild(cls.catalogItem) cls.catalogItem.populate() cls.tree = cls.explorer.tree projectFile = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "test.qgs") iface.addProject(projectFile)
def askForFiles(parent, msg=None, isSave=False, allowMultiple=False, exts="*"): ''' Asks for a file or files, opening the corresponding dialog with the last path that was selected when this same function was invoked from the calling method. :param parent: The parent window :param msg: The message to use for the dialog title :param isSave: true if we are asking for file to save :param allowMultiple: True if should allow multiple files to be selected. Ignored if isSave == True :param exts: Extensions to allow in the file dialog. Can be a single string or a list of them. Use "*" to add an option that allows all files to be selected :returns: A string with the selected filepath or an array of them, depending on whether allowMultiple is True of False ''' msg = msg or 'Select file' caller = _callerName().split(".") name = "/".join([LAST_PATH, caller[-1]]) namespace = caller[0] path = pluginSetting(name, namespace) f = None if not isinstance(exts, list): exts = [exts] extString = ";; ".join([ " %s files (*.%s)" % (e.upper(), e) if e != "*" else "All files (*.*)" for e in exts ]) if allowMultiple: ret = QtWidgets.QFileDialog.getOpenFileNames(parent, msg, path, '*.' + extString) if ret: f = ret[0] else: f = ret = None else: if isSave: ret = QtWidgets.QFileDialog.getSaveFileName( parent, msg, path, '*.' + extString) or None if ret is not None and not ret.endswith(exts[0]): ret += "." + exts[0] else: ret = QtWidgets.QFileDialog.getOpenFileName( parent, msg, path, '*.' + extString) or None f = ret if f is not None: setPluginSetting(name, os.path.dirname(f), namespace) return ret
def _gpkgPath(self): folder = pluginSetting("gpkgfolder") or os.path.join( os.path.expanduser('~'), 'geogig', 'repos') subfolder = str(uuid.uuid4()).replace("-", "") path = os.path.join(folder, self.user, self.repo, self.layername, subfolder) if not os.path.exists(path): try: os.makedirs(path) except: path = os.path.join(os.path.expanduser('~'), 'geogig', 'repos', self.user, self.repo, self.layername, subfolder) if not os.path.exists(path): os.makedirs(path) return os.path.join(path, self.layername + ".gpkg")
def lessonPluginBaseFolder(): """Returns the base folder where to store lessons and data. If only folder name specified instead of full path, the folder will be created in the $HOME """ folder = pluginSetting("BaseFolder") # check if the value is only a basename and create directory in $HOME if not QDir(folder).exists(): if folder == os.path.basename(folder): folder = os.path.join(os.path.expanduser("~"), folder) setPluginSetting("BaseFolder", folder) if not QDir(folder).exists(): QDir().mkpath(folder) return QDir.toNativeSeparators(folder)
def screenshotsPluginBaseFolder(): """Returns the base folder where to store sessions and data. If only folder name specified instead of full path, the folder will be created in the $HOME """ folder = pluginSetting("BaseFolder") # check if the value is only a basename and create directory in $HOME if not QDir(folder).exists(): if folder == os.path.basename(folder): folder = os.path.join(os.path.expanduser("~"), folder) setPluginSetting("BaseFolder", folder) if not QDir(folder).exists(): QDir().mkpath(folder) return QDir.toNativeSeparators(folder)
def endCreateAppListener(self, success, reason): self.onCreatingApp = False # reset button status and cursor self.buttonCreateOrStopApp.setText(self.createAppButtonText) QApplication.restoreOverrideCursor() from pubsub import pub pub.unsubscribe(self.endCreateAppListener, utils.topics.endFunction) if success: if pluginSetting("compileinserver"): QMessageBox.information( self, self.tr("Web app"), self.tr("Web app was correctly created and built.")) else: QMessageBox.information( self, self.tr("Web app"), self. tr("Web app file were correctly created.\n" "A web app can be built from them using Boundless WebSDK" )) elif reason: QgsMessageLog.logMessage("WebAppBuilder: {}".format(reason), level=QgsMessageLog.CRITICAL) if 'Request cancelled by user' in reason: # do nothing pass elif 'Cannot post preview webapp: Network error #5: Operation canceled' in reason: QMessageBox.critical( self, self.tr("Error creating web app"), self. tr("Network error due to a timeout.\n" "Please configure a longer timeout going to:\n" "Settings->Options->Network->Timeout for network requests (ms)." )) elif 'Permission denied' in reason: QMessageBox.critical( self, self.tr("Error creating web app"), self.tr( "Permission denied with current Connect credentials")) else: QMessageBox.critical( self, self.tr("Error creating web app"), self. tr("Could not create web app.\nCheck the QGIS log for more details." ))
def askForFolder(parent, msg=None): ''' Asks for a folder, opening the corresponding dialog with the last path that was selected when this same function was invoked from the calling method :param parent: The parent window :param msg: The message to use for the dialog title ''' msg = msg or 'Select folder' caller = _callerName().split(".") name = "/".join([LAST_PATH, caller[-1]]) namespace = caller[0] path = pluginSetting(name, namespace) folder = QtWidgets.QFileDialog.getExistingDirectory(parent, msg, path) if folder: setPluginSetting(name, folder, namespace) return folder
def initGui(self): icon = QIcon(os.path.dirname(__file__) + "/images/geoserver.png") self.explorerAction = QAction(icon, "GeoServer Explorer", self.iface.mainWindow()) self.explorerAction.triggered.connect(self.openExplorer) self.iface.addPluginToWebMenu(u"GeoServer", self.explorerAction) self.explorer = GeoServerExplorer() self.iface.addDockWidget(Qt.RightDockWidgetArea, self.explorer) if not pluginSetting("ExplorerVisible"): self.explorer.hide() self.explorer.visibilityChanged.connect(self._explorerVisibilityChanged) addSettingsMenu("GeoServer", self.iface.addPluginToWebMenu) addHelpMenu("GeoServer", self.iface.addPluginToWebMenu) addAboutMenu("GeoServer", self.iface.addPluginToWebMenu) layerwatcher.connectLayerWasAdded(self.explorer)
def testDeleteLayerAndStyle(self): # step 1: publish a layer. publish load layer and style self.catWrapper.publishLayer(PT1, self.ws, name=PT1) layer = self.cat.get_layer(PT1) self.assertIsNotNone(layer) style = self.cat.get_styles(PT1)[0] self.assertIsNotNone(style) self.getLayersItem().refreshContent(self.explorer) self.getStylesItem().refreshContent(self.explorer) # step 2: set flag to remove also style deleteStyle = pluginSetting("DeleteStyle") setPluginSetting("DeleteStyle", True) # step 3: then remove layer and style layerItem = self.getLayerItem(PT1) self.assertIsNotNone(layerItem) layerItem.deleteLayer(self.tree, self.explorer) layerItem = self.getLayerItem(PT1) self.assertIsNone(layerItem) styleItem = self.getStyleItem(PT1) self.assertIsNone(styleItem) # step 4: republish PT1 and it's style self.catWrapper.publishLayer(PT1) layer = self.cat.get_layer(PT1) self.assertIsNotNone(layer) style = self.cat.get_styles(PT1)[0] self.assertIsNotNone(style) self.getLayersItem().refreshContent(self.explorer) self.getStylesItem().refreshContent(self.explorer) # step 5: set flag to remove layer BUT not style setPluginSetting("DeleteStyle", False) # step 6: remove layer and check style is not erased layerItem = self.getLayerItem(PT1) layerItem.deleteLayer(self.tree, self.explorer) layerItem = self.getLayerItem(PT1) self.assertIsNone(layerItem) styleItem = self.getStyleItem(PT1) self.assertIsNotNone(styleItem) # step 7: then remove style styleItem.deleteStyle(self.tree, self.explorer) styleItem = self.getStyleItem(PT1) self.assertIsNone(styleItem) # step 8: set flag in original mode setPluginSetting("DeleteStyle", deleteStyle)
def initPluginManager(installer, boundlessOnly=False): """Prepare plugin manager content """ repoUrl = pluginSetting('repoUrl') repositories.load() if installer.statusLabel: iface.mainWindow().statusBar().removeWidget(installer.statusLabel) # Load plugins from remote repositories and export repositories # to Plugin Manager installer.fetchAvailablePlugins(True) installer.exportRepositoriesToManager() # If Boundless repository is a local directory, add plugins # from it to Plugin Manager if isRepositoryInDirectory(): repositoryData = {'url': repoUrl, 'authcfg': '' } repositories.mRepositories.update({boundlessRepoName: repositoryData}) localPlugins.getAllInstalled() localPlugins.load() localPlugins.rebuild() plugins.mPlugins.update(localPlugins.all()) if boundlessOnly: for pluginName, pluginDesc in list(plugins.mPlugins.items()): if not isBoundlessPlugin(pluginDesc): del plugins.mPlugins[pluginName] # Export all plugins to Plugin Manager installer.exportPluginsToManager() if installer.statusLabel: iface.mainWindow().statusBar().removeWidget(installer.statusLabel)
def initConfigParams(): folder = pluginSetting(REPOS_FOLDER) if folder.strip() == "": folder = os.path.join(os.path.expanduser('~'), 'geogig', 'repos') setPluginSetting(REPOS_FOLDER, folder)
def load(self): repoUrl = pluginSetting('repoUrl') repoPath = os.path.abspath(repoUrl) repoFile = os.path.join(repoPath, 'plugins.xml') repoXML = QDomDocument() with codecs.open(repoFile, 'r', encoding='utf-8') as f: content = f.read() repoXML.setContent(content) pluginNodes = repoXML.elementsByTagName('pyqgis_plugin') if pluginNodes.size(): for i in range(pluginNodes.size()): fileName = pluginNodes.item(i).firstChildElement('file_name').text().strip() if not fileName: fileName = QFileInfo(pluginNodes.item(i).firstChildElement('download_url').text().strip().split('?')[0]).fileName() name = fileName.partition('.')[0] experimental = False if pluginNodes.item(i).firstChildElement('experimental').text().strip().upper() in ['TRUE', 'YES']: experimental = True deprecated = False if pluginNodes.item(i).firstChildElement('deprecated').text().strip().upper() in ['TRUE', 'YES']: deprecated = True icon = pluginNodes.item(i).firstChildElement('icon').text().strip() if pluginNodes.item(i).toElement().hasAttribute('plugin_id'): plugin_id = pluginNodes.item(i).toElement().attribute('plugin_id') else: plugin_id = None plugin = { 'id': name, 'plugin_id': plugin_id, 'name': pluginNodes.item(i).toElement().attribute('name'), 'version_available': pluginNodes.item(i).toElement().attribute('version'), 'description': pluginNodes.item(i).firstChildElement('description').text().strip(), 'about': pluginNodes.item(i).firstChildElement('about').text().strip(), 'author_name': pluginNodes.item(i).firstChildElement('author_name').text().strip(), 'homepage': pluginNodes.item(i).firstChildElement('homepage').text().strip(), 'download_url': 'file:///{}'.format(os.path.join(repoPath, fileName)), 'category': pluginNodes.item(i).firstChildElement('category').text().strip(), 'tags': pluginNodes.item(i).firstChildElement('tags').text().strip(), 'changelog': pluginNodes.item(i).firstChildElement('changelog').text().strip(), 'author_email': pluginNodes.item(i).firstChildElement('author_email').text().strip(), 'tracker': pluginNodes.item(i).firstChildElement('tracker').text().strip(), 'code_repository': pluginNodes.item(i).firstChildElement('repository').text().strip(), 'downloads': pluginNodes.item(i).firstChildElement('downloads').text().strip(), 'average_vote': pluginNodes.item(i).firstChildElement('average_vote').text().strip(), 'rating_votes': pluginNodes.item(i).firstChildElement('rating_votes').text().strip(), 'icon': icon, 'experimental': experimental, 'deprecated': deprecated, 'filename': fileName, 'installed': False, 'available': True, 'status': 'not installed', 'error': '', 'error_details': '', 'version_installed': '', "zip_repository": boundlessRepoName, 'library': '', 'readonly': False } qgisMinimumVersion = pluginNodes.item(i).firstChildElement('qgis_minimum_version').text().strip() if not qgisMinimumVersion: qgisMinimumVersion = '2' qgisMaximumVersion = pluginNodes.item(i).firstChildElement('qgis_maximum_version').text().strip() if not qgisMaximumVersion: qgisMaximumVersion = qgisMinimumVersion[0] + '.99' # If compatible, add the plugin to the list if not pluginNodes.item(i).firstChildElement('disabled').text().strip().upper() in ['TRUE', 'YES']: if isCompatible(QGis.QGIS_VERSION, qgisMinimumVersion, qgisMaximumVersion): # Add the plugin to the cache repo = boundlessRepoName try: self.repoCache[repo] += [plugin] except: self.repoCache[repo] = [plugin]
def isRepositoryInDirectory(): """Return True if plugin repository is a plain directory """ repoUrl = pluginSetting('repoUrl') return repoUrl != '' and os.path.isdir(os.path.abspath(repoUrl))