Example #1
0
    def testResetScriptFolder(self):
        # if folder exist
        defaultScriptFolder = ScriptUtils.defaultScriptsFolder()
        folder = ScriptUtils.resetScriptFolder(defaultScriptFolder)
        self.assertEqual(folder, defaultScriptFolder)
        folder = ScriptUtils.resetScriptFolder('.')
        self.assertEqual(folder, '.')
        # if folder does not exist and not absolute
        folder = ScriptUtils.resetScriptFolder('fake')
        self.assertEqual(folder, None)
        # if absolute but not relative to QgsApplication.qgisSettingsDirPath()
        folder = os.path.join(tempfile.gettempdir(), 'fakePath')
        newFolder = ScriptUtils.resetScriptFolder(folder)
        self.assertEqual(newFolder, folder)

        # if absolute profile but poiting somewhere
        # reset the path as pointing to profile into the current settings
        folder = QgsApplication.qgisSettingsDirPath()

        # modify default profile changing absolute path pointing somewhere
        paths = folder.split(os.sep)
        paths[0] = '/'
        paths[1] = 'fakelocation'
        folder = os.path.join(*paths)

        folder = ScriptUtils.resetScriptFolder(folder)
        self.assertEqual(folder, QgsApplication.qgisSettingsDirPath())
def customProfileFiles():
    customProfileFilepath = os.path.join(QgsApplication.qgisSettingsDirPath(), 'profiles')

    if os.path.exists(customProfileFilepath):
        return glob.glob(os.path.join(customProfileFilepath, '*.json'))
    else:
        return []
Example #3
0
 def new_profile(self):
     """Create a new profile by name.
     """
     # noinspection PyCallByClass,PyTypeChecker
     dir = os.path.join(QgsApplication.qgisSettingsDirPath(),
                        'inasafe', 'minimum_needs')
     file_name, __ = QFileDialog.getSaveFileName(
         self,
         self.tr('Create a minimum needs profile'),
         expanduser(dir),
         self.tr('JSON files (*.json *.JSON)'),
         options=QFileDialog.DontUseNativeDialog)
     if not file_name:
         return
     file_name = basename(file_name)
     if self.profile_combo.findText(file_name) == -1:
         minimum_needs = {
             'resources': [], 'provenance': '', 'profile': file_name}
         self.minimum_needs.update_minimum_needs(minimum_needs)
         self.minimum_needs.save_profile(file_name)
         self.profile_combo.addItem(file_name)
         self.clear_resource_list()
         self.profile_combo.setCurrentIndex(
             self.profile_combo.findText(file_name))
     else:
         self.profile_combo.setCurrentIndex(
             self.profile_combo.findText(file_name))
         self.select_profile_by_name(file_name)
Example #4
0
 def save_profile_as(self):
     """Save the minimum needs under a new profile name.
     """
     # noinspection PyCallByClass,PyTypeChecker
     file_name_dialog = QFileDialog(self)
     file_name_dialog.setAcceptMode(QFileDialog.AcceptSave)
     file_name_dialog.setNameFilter(self.tr('JSON files (*.json *.JSON)'))
     file_name_dialog.setDefaultSuffix('json')
     dir = os.path.join(QgsApplication.qgisSettingsDirPath(),
                        'inasafe', 'minimum_needs')
     file_name_dialog.setDirectory(expanduser(dir))
     if file_name_dialog.exec_():
         file_name = file_name_dialog.selectedFiles()[0]
     else:
         return
     file_name = basename(file_name)
     file_name = file_name.replace('.json', '')
     minimum_needs = {'resources': []}
     self.mark_current_profile_as_saved()
     for index in range(self.resources_list.count()):
         item = self.resources_list.item(index)
         minimum_needs['resources'].append(item.resource_full)
     minimum_needs['provenance'] = self.provenance.text()
     minimum_needs['profile'] = file_name
     self.minimum_needs.update_minimum_needs(minimum_needs)
     self.minimum_needs.save()
     self.minimum_needs.save_profile(file_name)
     if self.profile_combo.findText(file_name) == -1:
         self.profile_combo.addItem(file_name)
     self.profile_combo.setCurrentIndex(
         self.profile_combo.findText(file_name))
Example #5
0
def installFromStandardPath():
    """Also install all plugins from "standard" location
    """
    dirName = os.path.join(QgsApplication.qgisSettingsDirPath(), firstRunPluginsPath)
    if os.path.isdir(dirName):
        installAllFromDirectory(dirName)
        shutil.rmtree(dirName)
Example #6
0
    def root_directory(self):
        """Map the root directory to ~/.qgis2/inasafe so the minimum needs
           profile will be placed there (~/.qgis2/inasafe/minimum_needs).

        :returns: root directory
        :rtype: QString
        """
        if not QgsApplication.qgisSettingsDirPath() or (
                    QgsApplication.qgisSettingsDirPath() == ''):
            self._root_directory = None
        else:
            # noinspection PyArgumentList
            self._root_directory = os.path.join(
                QgsApplication.qgisSettingsDirPath(),
                'inasafe')

        return self._root_directory
def storeCurrentConfiguration():
    global userProfile
    folder = os.path.join(QgsApplication.qgisSettingsDirPath(), 'profiles')
    filepath = os.path.join(folder, 'profile%s.json' % str(time.time()))
    name = time.strftime("%b %d %Y %H:%M:%S", time.gmtime(time.time()))
    description = "This profile was created based on your QGIS configuration at %s" % name
    if not os.path.exists(folder):
        os.mkdir(folder)
    saveCurrentStatus(filepath, name, description=description)
Example #8
0
def getTemplates():
    fl = os.path.join(QgsApplication.qgisSettingsDirPath(),
                      "qgis2web",
                      "templates")
    if not os.path.exists(fl):
        shutil.copytree(os.path.join(os.path.dirname(__file__),
                                     "templates"),
                        fl)
    return tuple(f[:f.find(".")] for f in reversed(os.listdir(fl))
                 if f.endswith("html"))
Example #9
0
def load_packages():
    # Load all the Python modules found in the users command bar folder
    folder = os.path.join(QgsApplication.qgisSettingsDirPath(), "python",
                          "commandbar")
    try:
        os.makedirs(folder)
    except OSError:
        pass

    command.load_packages([folder])
Example #10
0
 def setStyleLayer(qml):
   qmlFile = "%saddlayersql_action_temp.qml" % ( QgsApplication.qgisSettingsDirPath() )
   if os.path.exists(qmlFile):
     os.remove( qmlFile )
   f = codecs.open( qmlFile, 'w', encoding='utf8')
   f.write( qml )
   f.close()
   #
   layerQuery.loadNamedStyle( qmlFile )
   #
   os.remove( qmlFile )
Example #11
0
def is_plugin_installed(name):
    """Check if a plugin is installed, even if it's not enabled.

    :param name: Name of the plugin to check.
    :type name: string

    :return: If the plugin is installed.
    :rtype: bool
    """
    directory = QgsApplication.qgisSettingsDirPath()
    return isdir(join(directory, 'python', 'plugins', name))
Example #12
0
def replaceInTemplate(template, values):
    path = os.path.join(QgsApplication.qgisSettingsDirPath(),
                        "qgis2web",
                        "templates",
                        template)
    with open(path) as f:
        lines = f.readlines()
    s = "".join(lines)
    for name, value in values.items():
        s = s.replace(name, value)
    return s
Example #13
0
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
Example #14
0
def setRepositoryUrl():
    """Adds Boundless repository URL to Connect settings"""
    fName = os.path.join(QgsApplication.qgisSettingsDirPath(), repoUrlFile)
    if os.path.exists(fName):
        cfg = ConfigParser.SafeConfigParser()
        cfg.read(fName)
        url = cfg.get('general', 'repoUrl')
        os.remove(fName)
    else:
        url = defaultRepoUrl

    settings = QSettings('Boundless', 'BoundlessConnect')
    settings.setValue('repoUrl', url)
def _downgradePlugin(pluginName, corePlugin=True):
    if corePlugin:
        metadataPath = os.path.join(QgsApplication.pkgDataPath(), 'python', 'plugins', pluginName, 'metadata.txt')
    else:
        metadataPath = os.path.join(QgsApplication.qgisSettingsDirPath()(), 'python', 'plugins', pluginName, 'metadata.txt')

    cfg = ConfigParser()
    cfg.read(metadataPath)
    global originalVersion
    originalVersion = cfg.get('general', 'version')
    cfg.set('general', 'version', '0.0.1')
    with open(metadataPath, 'wb') as f:
        cfg.write(f)
Example #16
0
def load_init_file():
    # Read the init file from the python\commandbar folder
    folder = os.path.join(QgsApplication.qgisSettingsDirPath(), "python", "commandbar")
    initfile = os.path.join(folder, "init")
    try:
        os.makedirs(folder)
    except OSError:
        pass

    if not os.path.exists(initfile):
        header = "# Command bar init file. Lines starting with # are ignored"
        with open(initfile, "w") as f:
            f.write(header)
    command.load_from_file(initfile)
    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)
Example #18
0
def load_init_file():
    # Read the init file from the python\commandbar folder
    folder = os.path.join(QgsApplication.qgisSettingsDirPath(), "python",
                          "commandbar")
    initfile = os.path.join(folder, "init.qgsc")
    try:
        os.makedirs(folder)
    except OSError:
        pass

    if not os.path.exists(initfile):
        header = ";; Command bar init file. Commands inside ( ) e.g (point-at x y)"
        with open(initfile, "w") as f:
            f.write(header)
    command.load_from_file(initfile)
    def testCustomRepoUrl(self):
        """Test that Connect read custom repository URL and apply it"""
        settings = QSettings('Boundless', 'BoundlessConnect')
        oldRepoUrl = settings.value('repoUrl', '', unicode)

        settings.setValue('repoUrl', 'test')
        self.assertEqual('test', settings.value('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', settings.value('repoUrl', '', unicode))
        settings.setValue('repoUrl', oldRepoUrl)
Example #20
0
def getTemplates():
    src = os.path.join(os.path.dirname(__file__), "templates")
    dst = os.path.join(QgsApplication.qgisSettingsDirPath(), "qgis2web",
                       "templates")
    if not os.path.exists(dst):
        shutil.copytree(src, dst)
    else:
        for fname in os.listdir(src):
            with open(os.path.join(src, fname)) as s:
                srcCode = s.read()
            with open(os.path.join(dst, os.path.basename(fname)), 'w') as d:
                d.seek(0)
                d.write(srcCode)
                d.truncate()
    return tuple(f[:f.find(".")] for f in reversed(os.listdir(dst))
                 if f.endswith("html"))
Example #21
0
    def root_directory(self):
        """Get the home root directory

        :returns: root directory
        :rtype: QString
        """
        if self._root_directory is None or self._root_directory == '':
            try:
                # noinspection PyArgumentList
                self._root_directory = QgsApplication.qgisSettingsDirPath()
            except NameError:
                # This only happens when running only one test on its own
                self._root_directory = None
            if self._root_directory is None or self._root_directory == '':
                self._root_directory = os.path.join(
                    os.environ['HOME'], '.qgis2')
        return self._root_directory
Example #22
0
def quickosm_user_folder():
    """
    Get the QuickOSM user folder.

    If the folder does not exist, it will create it.

    On Linux: .local/share/QGIS/QGIS3/profiles/default/QuickOSM

    @rtype: str
    @return: path
    """
    path = abspath(join(QgsApplication.qgisSettingsDirPath(), 'QuickOSM'))

    if not QDir(path).exists():
        QDir().mkdir(path)

    return path
    def setUpClass(cls):
        if not cls._BaseSetup:
            TestQgsPalLabeling.setUpClass()
        MAPSERV.startup()
        MAPSERV.web_dir_install(glob.glob(cls._PalDataDir + os.sep + "*.qml"))
        MAPSERV.web_dir_install(glob.glob(cls._PalDataDir + os.sep + "*.qgs"))

        # noinspection PyArgumentList
        cls._TestProj = QgsProject.instance()
        cls._TestProjName = "test-labeling.qgs"
        cls._TestProj.setFileName(os.path.join(MAPSERV.web_dir(), cls._TestProjName))

        # the blue background (set via layer style) to match renderchecker's
        TestQgsPalLabeling.loadFeatureLayer("background", True)

        settings = QSettings()
        # noinspection PyArgumentList
        cls._CacheDir = settings.value(
            "cache/directory", os.path.join(unicode(QgsApplication.qgisSettingsDirPath()), "cache"), type=unicode
        )
Example #24
0
def resetScriptFolder(folder):
    """Check if script folder exist. If not, notify and try to check if it is absolute to another user setting.
    If so, modify folder to change user setting to the current user setting."""

    newFolder = folder
    if os.path.exists(newFolder):
        return newFolder

    QgsMessageLog.logMessage(QgsApplication .translate("loadAlgorithms", "Script folder {} does not exist").format(newFolder),
                             QgsApplication.translate("loadAlgorithms", "Processing"),
                             Qgis.Warning)

    if not os.path.isabs(newFolder):
        return None

    # try to check if folder is absolute to other QgsApplication.qgisSettingsDirPath()

    # isolate "QGIS3/profiles/"
    appIndex = -4
    profileIndex = -3
    currentSettingPath = QgsApplication.qgisSettingsDirPath()
    paths = currentSettingPath.split(os.sep)
    commonSettingPath = os.path.join(paths[appIndex], paths[profileIndex])

    if commonSettingPath in newFolder:
        # strip not common folder part. e.g. preserve the profile path
        # stripping the heading part that come from another location
        tail = newFolder[newFolder.find(commonSettingPath):]
        # tail folder with the actual userSetting path
        header = os.path.join(os.sep, os.path.join(*paths[:appIndex]))
        newFolder = os.path.join(header, tail)

        # skip if it does not exist
        if not os.path.exists(newFolder):
            return None

        QgsMessageLog.logMessage(QgsApplication .translate("loadAlgorithms", "Script folder changed into {}").format(newFolder),
                                 QgsApplication.translate("loadAlgorithms", "Processing"),
                                 Qgis.Warning)

    return newFolder
Example #25
0
    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = QFileInfo(QgsApplication.qgisSettingsDirPath()).path() + "/python/plugins/distromap"
        # initialize locale
        localePath = ""
        locale = QSettings().value("locale/userLocale")[0:2]

        if QFileInfo(self.plugin_dir).exists():
            localePath = self.plugin_dir + "/i18n/distromap_" + locale + ".qm"

        if QFileInfo(localePath).exists():
            self.translator = QTranslator()
            self.translator.load(localePath)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        # Create the dialog (after translation) and keep reference
        self.dlg = DistroMapDialog()
Example #26
0
    def move_old_profile(self, locale_minimum_needs_dir):
        """Move old minimum needs profile under ~/.qgis2/minimum_needs.
           This function is to get rid the old min needs profile came
           from InaSAFE < 4.0.

        :param locale_minimum_needs_dir: User local minimum needs profile path.
        :type locale_minimum_needs_dir: str
        """
        old_profile_path = os.path.join(
            QgsApplication.qgisSettingsDirPath(), 'minimum_needs')

        if os.path.exists(old_profile_path):
            for filename in os.listdir(old_profile_path):
                source_file = os.path.join(old_profile_path, filename)
                destination_file = os.path.join(
                    locale_minimum_needs_dir, filename)
                if not os.path.exists(destination_file):
                    copy(source_file, destination_file)
                if os.path.exists(destination_file):
                    os.remove(source_file)
            # remove old profile path
            rmtree(old_profile_path)
Example #27
0
def map_report_component(component, custom_template_dir=None):
    """Get a map report component based on custom qpt if exists

    :param component: Component as dictionary.
    :type component: dict

    :param custom_template_dir: The directory where the custom template stored.
    :type custom_template_dir: basestring

    :returns: Map report component.
    :rtype: dict
    """
    copy_component = deepcopy(component)
    if not custom_template_dir:
        custom_template_dir = join(
            QgsApplication.qgisSettingsDirPath(), 'inasafe')

    for component in copy_component['components']:
        qpt_file_name = component['template'].split('/')[-1]
        custom_qpt_path = join(custom_template_dir, qpt_file_name)
        if exists(custom_qpt_path):
            component['template'] = custom_qpt_path

    return copy_component
Example #28
0
def userFolder():
    userDir = os.path.join(QgsApplication.qgisSettingsDirPath(), 'processing')
    if not QDir(userDir).exists():
        QDir().mkpath(userDir)

    return str(QDir.toNativeSeparators(userDir))
Example #29
0
        # As user expression functions should be registered with qgsfunction
        # just importing the file is enough to get it to load the functions into QGIS
        try:
            __import__("expressions.{0}".format(name), locals(), globals())
        except:
            error = traceback.format_exc()
            msgtitle = QCoreApplication.translate("UserExpressions",
                                                  "User expressions")
            msg = QCoreApplication.translate(
                "UserExpressions",
                "The user expression {0} is not valid").format(name)
            QgsMessageLog.logMessage(msg + "\n" + error, msgtitle,
                                     QgsMessageLog.WARNING)


userpythonhome = os.path.join(QgsApplication.qgisSettingsDirPath(), "python")
expressionspath = os.path.join(userpythonhome, "expressions")

sys.path.append(userpythonhome)

if not os.path.exists(expressionspath):
    os.makedirs(expressionspath)

initfile = os.path.join(expressionspath, "__init__.py")
if not os.path.exists(initfile):
    open(initfile, "w").close()

template = """\"\"\"
Define new functions using @qgsfunction. feature and parent must always be the
last args. Use args=-1 to pass a list of values as arguments
\"\"\"
Example #30
0
                        QsciScintillaBase,
                        QsciLexerPython,
                        QsciAPIs)

import sys
import os
import code
import codecs
import re

from qgis.core import QgsApplication
from ui_console_history_dlg import Ui_HistoryDialogPythonConsole

_init_commands = ["from qgis.core import *", "import qgis.utils",
                  "from qgis.utils import iface"]
_historyFile = unicode( QgsApplication.qgisSettingsDirPath() + "console_history.txt" )

class ShellScintilla(QsciScintilla, code.InteractiveInterpreter):
    def __init__(self, parent=None):
        super(ShellScintilla,self).__init__(parent)
        code.InteractiveInterpreter.__init__(self, locals=None)

        self.parent = parent

        self.opening = ['(', '{', '[', "'", '"']
        self.closing = [')', '}', ']', "'", '"']

        self.settings = QSettings()

        # Enable non-ascii chars for editor
        self.setUtf8(True)
Example #31
0
def userFolder():
    userDir = os.path.join(QgsApplication.qgisSettingsDirPath(), 'processing')
    if not QDir(userDir).exists():
        QDir().mkpath(userDir)

    return str(QDir.toNativeSeparators(userDir))
def repositories_cache_path():
    """Get the path to the repositories cache."""
    return Path(QgsApplication.qgisSettingsDirPath(), 'resource_sharing',
                'repositories_cache')
Example #33
0
File: user.py Project: enzogis/QGIS
    names = [os.path.basename(f)[:-3] for f in modules]
    for name in names:
        if name == "__init__":
            continue
        # As user expression functions should be registered with qgsfunction
        # just importing the file is enough to get it to load the functions into QGIS
        try:
            __import__("expressions.{0}".format(name), locals(), globals())
        except:
            error = traceback.format_exc()
            msgtitle = QCoreApplication.translate("UserExpressions", "User expressions")
            msg = QCoreApplication.translate("UserExpressions", "The user expression {0} is not valid").format(name)
            QgsMessageLog.logMessage(msg + "\n" + error, msgtitle, QgsMessageLog.WARNING)


userpythonhome = os.path.join(QgsApplication.qgisSettingsDirPath(), "python")
expressionspath = os.path.join(userpythonhome, "expressions")

sys.path.append(userpythonhome)

if not os.path.exists(expressionspath):
    os.makedirs(expressionspath)

initfile = os.path.join(expressionspath, "__init__.py")
if not os.path.exists(initfile):
    open(initfile, "w").close()

template = """\"\"\"
Define a new function using the @qgsfunction decorator.

The function accept the following parameters
Example #34
0
# -*- coding: utf-8 -*-
###############################################################################
#
# Copyright (c) 2019 HERE Europe B.V.
#
# SPDX-License-Identifier: MIT
# License-Filename: LICENSE
#
###############################################################################

import os

from qgis.core import QgsApplication

from . import __version__ as version
from .xyz_qgis.common import override_config

TAG_PLUGIN = "XYZ Hub Connector"
PLUGIN_FULL_NAME = "XYZ Hub Connector"
PLUGIN_NAME = __package__
PLUGIN_VERSION = version
PLUGIN_DIR = os.path.dirname(os.path.abspath(__file__))
USER_DIR = os.path.abspath(QgsApplication.qgisSettingsDirPath())
USER_PLUGIN_DIR = os.path.join(USER_DIR, PLUGIN_NAME)
TMP_DIR = os.path.join(USER_DIR, PLUGIN_NAME, "tmp")
LOG_FILE = os.path.join(USER_DIR, PLUGIN_NAME, "qgis.log")

os.makedirs(TMP_DIR, exist_ok=True)

override_config(dict(filter(lambda kv: kv[0].isupper(), locals().items())))