Example #1
0
def init():
  a = QgsApplication(sys.argv, True)
  a.setApplicationName("Teste PyCharm")
  QgsApplication.setPrefixPath("C:\\PROGRA~2\\QGISWI~1\\apps\\qgis", True)
  print QgsApplication.showSettings()


  QgsApplication.initQgis()
#  providers = QgsProviderRegistry.instance().providerList()
#  for provider in providers:
#    print provider
  return a
Example #2
0
def start_app(cleanup=True):
    """
    Will start a QgsApplication and call all initialization code like
    registering the providers and other infrastructure. It will not load
    any plugins.

    You can always get the reference to a running app by calling `QgsApplication.instance()`.

    The initialization will only happen once, so it is safe to call this method repeatedly.

        Parameters
        ----------

        cleanup: Do cleanup on exit. Defaults to true.

        Returns
        -------
        QgsApplication

        A QgsApplication singleton
    """
    global QGISAPP

    try:
        QGISAPP
    except NameError:
        myGuiFlag = True  # All test will run qgis in gui mode

        try:
            sys.argv
        except:
            sys.argv = ['']

        # In python3 we need to convert to a bytes object (or should
        # QgsApplication accept a QString instead of const char* ?)
        try:
            argvb = list(map(os.fsencode, sys.argv))
        except AttributeError:
            argvb = sys.argv

        # Note: QGIS_PREFIX_PATH is evaluated in QgsApplication -
        # no need to mess with it here.
        QGISAPP = QgsApplication(argvb, myGuiFlag)

        QGISAPP.initQgis()
        print(QGISAPP.showSettings())

        def debug_log_message(message, tag, level):
            print('{}({}): {}'.format(tag, level, message))

        QgsApplication.instance().messageLog().messageReceived.connect(debug_log_message)

        if cleanup:
            import atexit

            @atexit.register
            def exitQgis():
                QGISAPP.exitQgis()

    return QGISAPP
Example #3
0
def init_qgis(verbose=False):
    """ Initialize qgis application
    """
    from qgis.core import Qgis, QgsApplication
    global qgis_application

    qgisPrefixPath = os.environ.get('QGIS_PREFIX_PATH', '/usr/')
    sys.path.append(os.path.join(qgisPrefixPath, "share/qgis/python/plugins/"))

    # Set offscreen mode when no display
    # This will prevent Qt tryning to connect to display
    if os.environ.get('DISPLAY') is None:
        os.environ['QT_QPA_PLATFORM'] = 'offscreen'

    qgis_application = QgsApplication([], False)
    qgis_application.setPrefixPath(qgisPrefixPath, True)
    qgis_application.initQgis()

    os.environ['QGIS_PREFIX_PATH'] = qgisPrefixPath

    # Auto cleanup
    @atexit.register
    def extQgis():
        global qgis_application
        if qgis_application:
            qgis_application.exitQgis()
            del qgis_application

    if verbose:
        print(qgis_application.showSettings(), file=sys.stderr)

    # Install logging hook
    install_message_hook(verbose)
Example #4
0
def init_qgis(verbose=False):
    """ Initialize qgis application
    """
    from qgis.core import Qgis, QgsApplication
    global qgis_application 

    qgisPrefixPath = os.environ.get('QGIS_PREFIX_PATH','/usr/')
    sys.path.append(os.path.join(qgisPrefixPath, "share/qgis/python/plugins/"))

    # Set offscreen mode when no display 
    # This will prevent Qt tryning to connect to display
    if os.environ.get('DISPLAY') is None:
        os.environ['QT_QPA_PLATFORM'] = 'offscreen'

    qgis_application = QgsApplication([], False )
    qgis_application.setPrefixPath(qgisPrefixPath, True)
    qgis_application.initQgis()

    os.environ['QGIS_PREFIX_PATH'] = qgisPrefixPath

    # Auto cleanup
    @atexit.register
    def extQgis():
        global qgis_application
        if qgis_application:
            qgis_application.exitQgis()
            del qgis_application

    if verbose:
         print(qgis_application.showSettings(),file=sys.stderr)
    
    # Install logging hook
    install_message_hook( verbose )
def globalQgis():
    """Singleton implementation for a global QGIS app instance.

    Args:
        None
    Returns:
        A QGIS Application instance
    Raises:
        None
    """

    global QGISAPP

    if QGISAPP is None:
        myGuiFlag = True  # All test will run qgis in gui mode
        QGISAPP = QgsApplication(sys.argv, myGuiFlag)
        if 'QGISPATH' in os.environ:
            myPath = os.environ['QGISPATH']
            myUseDefaultPathFlag = True
            QGISAPP.setPrefixPath(myPath, myUseDefaultPathFlag)

        QGISAPP.initQgis()
        s = QGISAPP.showSettings()
        print s
    return QGISAPP
Example #6
0
def start_app(cleanup=True):
    """
    Will start a QgsApplication and call all initialization code like
    registering the providers and other infrastructure. It will not load
    any plugins.

    You can always get the reference to a running app by calling `QgsApplication.instance()`.

    The initialization will only happen once, so it is safe to call this method repeatedly.

        Parameters
        ----------

        cleanup: Do cleanup on exit. Defaults to true.

        Returns
        -------
        QgsApplication

        A QgsApplication singleton
    """
    global QGISAPP

    try:
        QGISAPP
    except NameError:
        myGuiFlag = True  # All test will run qgis in gui mode

        try:
            sys.argv
        except:
            sys.argv = ['']

        # In python3 we need to convert to a bytes object (or should
        # QgsApplication accept a QString instead of const char* ?)
        try:
            argvb = list(map(os.fsencode, sys.argv))
        except AttributeError:
            argvb = sys.argv

        # Note: QGIS_PREFIX_PATH is evaluated in QgsApplication -
        # no need to mess with it here.
        QGISAPP = QgsApplication(argvb, myGuiFlag)

        QGISAPP.initQgis()
        print(QGISAPP.showSettings())

        def debug_log_message(message, tag, level):
            print('{}({}): {}'.format(tag, level, message))

        QgsApplication.instance().messageLog().messageReceived.connect(debug_log_message)

        if cleanup:
            import atexit

            @atexit.register
            def exitQgis():
                QGISAPP.exitQgis()

    return QGISAPP
def main(args=None):

    # supply path to qgis install location
    QgsApplication.setPrefixPath("/usr", True)

    # create a reference to the QgsApplication
    # setting the second argument to True enables the IquaView GUI,
    # which we need to do since this is a custom application
    qgs = QgsApplication([], True)

    # init splash screen
    splash_pix = QPixmap(':/resources/iquaview.png')
    splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
    splash.setMask(splash_pix.mask())

    light_blue = QColor(165, 197, 192)
    dark_blue = QColor(11, 52, 70)
    # adding progress bar
    progress_bar = QProgressBar(splash)
    p = progress_bar.palette()
    p.setColor(QPalette.Highlight, light_blue)
    p.setColor(QPalette.HighlightedText, dark_blue)
    progress_bar.setPalette(p)
    progress_bar.setMaximum(10)
    progress_bar.setGeometry(0,
                             splash_pix.height() - 50, splash_pix.width(), 20)

    splash.show()
    splash.showMessage("Initializing interface...",
                       Qt.AlignBottom | Qt.AlignCenter, light_blue)

    # progress bar...
    for i in range(1, 11):
        progress_bar.setValue(i)
        t = time()
        if i == 5:
            splash.showMessage("Loading providers...",
                               Qt.AlignBottom | Qt.AlignCenter, light_blue)
            # load providers
            qgs.initQgis()
            LOGGER.info(qgs.showSettings())
        if i == 10:
            # exec iquaview window
            window = MainWindow()
            window.setWindowIcon(QIcon(":/resources/iquaview_vector.svg"))
            splash.showMessage("IQUAview ready!",
                               Qt.AlignBottom | Qt.AlignCenter, light_blue)

        while time() < t + 0.1:
            qgs.processEvents()

    window.showMaximized()
    splash.finish(window)

    qgs.exec_()
    window.deleteLater()
    # when app terminates, call exitQgis() to remove the provider and layer registries from memory
    qgs.exitQgis()
def ensure_qgis_app_is_initialized():
    """Make sure qgis is initialized for testing."""
    # Note: if you just need the QT app to be there, you can use the qtbot fixture
    # from https://pytest-qt.readthedocs.io/en/latest/index.html
    if "app" not in _singletons:
        app = QgsApplication([], False)
        app.initQgis()
        logger.debug("Initialized qgis (for testing). Settings: %s", app.showSettings())
        _singletons["app"] = app
Example #9
0
def get_qgis_app():
    """ Start one QGIS application to test against.

    :returns: Handle to QGIS app, canvas, iface and parent. If there are any
        errors the tuple members will be returned as None.
    :rtype: (QgsApplication, CANVAS, IFACE, PARENT)

    If QGIS is already running the handle to that app will be returned.
    """
    global QGIS_APP, PARENT, IFACE, CANVAS  # pylint: disable=W0603

    if iface:
        from qgis.core import QgsApplication
        QGIS_APP = QgsApplication
        CANVAS = iface.mapCanvas()
        PARENT = iface.mainWindow()
        IFACE = iface
        return QGIS_APP, CANVAS, IFACE, PARENT

    try:
        from PyQt4 import QtGui, QtCore
        from qgis.core import QgsApplication
        from qgis.gui import QgsMapCanvas

    except ImportError:
        return None, None, None, None

    global QGIS_APP  # pylint: disable=W0603

    if QGIS_APP is None:
        gui_flag = True  # All test will run qgis in gui mode
        # noinspection PyPep8Naming
        QGIS_APP = QgsApplication(sys.argv, gui_flag)
        # Make sure QGIS_PREFIX_PATH is set in your env if needed!
        QGIS_APP.initQgis()
        s = QGIS_APP.showSettings()
        LOGGER.debug(s)

    global PARENT  # pylint: disable=W0603
    if PARENT is None:
        # noinspection PyPep8Naming
        PARENT = QtGui.QWidget()

    global CANVAS  # pylint: disable=W0603
    if CANVAS is None:
        # noinspection PyPep8Naming
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QtCore.QSize(400, 400))

    global IFACE  # pylint: disable=W0603
    if IFACE is None:
        # QgisInterface is a stub implementation of the QGIS plugin interface
        # noinspection PyPep8Naming
        # IFACE = QgisInterface(CANVAS)
        IFACE = None

    return QGIS_APP, CANVAS, IFACE, PARENT
Example #10
0
def get_qgis_app():
    """ Start one QGIS application to test against.

    :returns: Handle to QGIS app, canvas, iface and parent. If there are any
        errors the tuple members will be returned as None.
    :rtype: (QgsApplication, CANVAS, IFACE, PARENT)

    If QGIS is already running the handle to that app will be returned.
    """
    global QGIS_APP, PARENT, IFACE, CANVAS  # pylint: disable=W0603

    if iface:
        from qgis.core import QgsApplication
        QGIS_APP = QgsApplication
        CANVAS = iface.mapCanvas()
        PARENT = iface.mainWindow()
        IFACE = iface
        return QGIS_APP, CANVAS, IFACE, PARENT

    try:
        from PyQt4 import QtGui, QtCore
        from qgis.core import QgsApplication
        from qgis.gui import QgsMapCanvas

    except ImportError:
        return None, None, None, None

    global QGIS_APP  # pylint: disable=W0603

    if QGIS_APP is None:
        gui_flag = True  # All test will run qgis in gui mode
        # noinspection PyPep8Naming
        QGIS_APP = QgsApplication(sys.argv, gui_flag)
        # Make sure QGIS_PREFIX_PATH is set in your env if needed!
        QGIS_APP.initQgis()
        s = QGIS_APP.showSettings()
        LOGGER.debug(s)

    global PARENT  # pylint: disable=W0603
    if PARENT is None:
        # noinspection PyPep8Naming
        PARENT = QtGui.QWidget()

    global CANVAS  # pylint: disable=W0603
    if CANVAS is None:
        # noinspection PyPep8Naming
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QtCore.QSize(400, 400))

    global IFACE  # pylint: disable=W0603
    if IFACE is None:
        # QgisInterface is a stub implementation of the QGIS plugin interface
        # noinspection PyPep8Naming
        # IFACE = QgisInterface(CANVAS)
        IFACE = None

    return QGIS_APP, CANVAS, IFACE, PARENT
Example #11
0
def qgisMainInfo():
    """Returns general QGIS information like version, code revision,
    lib and app paths, etc.
    """

    if iface is None:
        try:
            app = QgsApplication(sys.argv, False)
            app.initQgis()
            appState = app.showSettings().replace("\t\t", " ").split("\n")[1:]
            prefixPath = app.prefixPath()
            libraryPath = app.libraryPath()
            libExecPath = app.libexecPath()
            pkgDataPath = app.pkgDataPath()
        except:
            appState = ["Could not read QGIS settings"]
            prefixPath = "Not available"
            libraryPath = "Not available"
            libExecPath = "Not available"
            pkgDataPath = "Not available"
    else:
        appState = QgsApplication.showSettings().replace("\t\t",
                                                         " ").split("\n")[1:]
        prefixPath = QgsApplication.prefixPath()
        libraryPath = QgsApplication.libraryPath()
        libExecPath = QgsApplication.libexecPath()
        pkgDataPath = QgsApplication.pkgDataPath()

    return {
        "QGIS information": {
            "QGIS version":
            "{} ({})".format(Qgis.QGIS_VERSION, Qgis.QGIS_DEV_VERSION),
            "QGIS prefix path":
            prefixPath,
            "QGIS library path":
            libraryPath,
            "QGIS lib exec path":
            libExecPath,
            "QGIS pkg data path":
            pkgDataPath,
            "QGIS application state":
            appState
        }
    }
Example #12
0
def get_qgis_app():
    """ Start one QGIS application to test against.

    :returns: Handle to QGIS app, canvas, iface and parent. If there are any
        errors the tuple members will be returned as None.
    :rtype: (QgsApplication, CANVAS, IFACE, PARENT)

    If QGIS is already running the handle to that app will be returned.
    """

    from PyQt4 import QtGui, QtCore
    from qgis.core import QgsApplication
    from qgis.gui import QgsMapCanvas

    # TODO: fix iface interface for testing
    #from qgis_interface import QgisInterface

    global QGIS_APP  # pylint: disable=W0603

    if QGIS_APP is None:

        #Fixed for MACOS
        sys.path.append('/Applications/QGis.app/Contents/Resources/python')

        gui_flag = True  # All test will run qgis in gui mode
        #noinspection PyPep8Naming
        QGIS_APP = QgsApplication(sys.argv, gui_flag)

        #MacOSX Test fix
        QgsApplication.setPrefixPath(r"/Applications/QGIS.app/Contents/MacOS",
                                     True)

        # Make sure QGIS_PREFIX_PATH is set in your env if needed!
        QGIS_APP.initQgis()
        s = QGIS_APP.showSettings()
        LOGGER.debug(s)

    global PARENT  # pylint: disable=W0603
    if PARENT is None:
        #noinspection PyPep8Naming
        PARENT = QtGui.QWidget()

    global CANVAS  # pylint: disable=W0603
    if CANVAS is None:
        #noinspection PyPep8Naming
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QtCore.QSize(400, 400))

    # TODO: fix iface interface for testing
    global IFACE  # pylint: disable=W0603
    #if IFACE is None:
    #    # QgisInterface is a stub implementation of the QGIS plugin interface
    #    #noinspection PyPep8Naming
    #    IFACE = QgisInterface(CANVAS)

    return QGIS_APP, CANVAS, IFACE, PARENT
Example #13
0
def get_qgis_app():
    """ Start one QGIS application to test against.

    :returns: Handle to QGIS app, canvas, iface and parent. If there are any
        errors the tuple members will be returned as None.
    :rtype: (QgsApplication, CANVAS, IFACE, PARENT)

    If QGIS is already running the handle to that app will be returned.
    """

    from qgis.PyQt import QtGui, QtCore
    from qgis.core import QgsApplication
    from qgis.gui import QgsMapCanvas
    from svir.test.qgis_interface import QgisInterface

    global QGIS_APP  # pylint: disable=W0603

    if QGIS_APP is None:
        gui_flag = True  # All test will run qgis in gui mode
        #noinspection PyPep8Naming
        QGIS_APP = QgsApplication(sys.argv, gui_flag)
        # Make sure QGIS_PREFIX_PATH is set in your env if needed!
        QGIS_APP.initQgis()
        s = QGIS_APP.showSettings()
        LOGGER.debug(s)

    global PARENT  # pylint: disable=W0603
    if PARENT is None:
        #noinspection PyPep8Naming
        PARENT = QtGui.QWidget()

    global CANVAS  # pylint: disable=W0603
    if CANVAS is None:
        #noinspection PyPep8Naming
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QtCore.QSize(400, 400))

    global IFACE  # pylint: disable=W0603
    if IFACE is None:
        # QgisInterface is a stub implementation of the QGIS plugin interface
        #noinspection PyPep8Naming
        IFACE = QgisInterface(CANVAS)

        # add some fake methods, where the actual ones were missing
        # FIXME: in QgisInterface, legendInterface is returning the canvas
        # instead of the legendInterface, which breaks things like setting the
        # active layer or refreshing the layer symbology.
        def do_nothing(layer):
            pass

        IFACE.legendInterface().refreshLayerSymbology = do_nothing

    return QGIS_APP, CANVAS, IFACE, PARENT
def get_qgis_app():
    """ Start one QGis application to test against

    Input
        NIL

    Output
        handle to qgis app


    If QGis is already running the handle to that app will be returned
    """

    global QGIS_APP  # pylint: disable=W0603

    if QGIS_APP is None:
        gui_flag = True  # All test will run qgis in safe_qgis mode
        # noinspection PyPep8Naming
        QGIS_APP = QgsApplication(sys.argv, gui_flag)

        # Note: This block is not needed for  QGIS > 1.8 which will
        # automatically check the QGIS_PREFIX_PATH var so it is here
        # for backwards compatibility only
        if "QGIS_PREFIX_PATH" in os.environ:
            path = os.environ["QGIS_PREFIX_PATH"]
            use_default_path_flag = True
            QGIS_APP.setPrefixPath(path, use_default_path_flag)

        QGIS_APP.initQgis()
        s = QGIS_APP.showSettings()
        LOGGER.debug(s)

    global PARENT  # pylint: disable=W0603
    if PARENT is None:
        # noinspection PyPep8Naming
        PARENT = QtGui.QWidget()

    global CANVAS  # pylint: disable=W0603
    if CANVAS is None:
        # noinspection PyPep8Naming
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QtCore.QSize(400, 400))

    global IFACE  # pylint: disable=W0603
    if IFACE is None:
        # QgisInterface is a stub implementation of the QGIS plugin interface
        # noinspection PyPep8Naming
        IFACE = QgisInterface(CANVAS)

    return QGIS_APP, CANVAS, IFACE, PARENT
def get_qgis_app():
    """ Start one QGis application to test against

    Input
        NIL

    Output
        handle to qgis app


    If QGis is already running the handle to that app will be returned
    """

    global QGIS_APP  # pylint: disable=W0603

    if QGIS_APP is None:
        gui_flag = True  # All test will run qgis in safe_qgis mode
        #noinspection PyPep8Naming
        QGIS_APP = QgsApplication(sys.argv, gui_flag)

        # Note: This block is not needed for  QGIS > 1.8 which will
        # automatically check the QGIS_PREFIX_PATH var so it is here
        # for backwards compatibility only
        if 'QGIS_PREFIX_PATH' in os.environ:
            path = os.environ['QGIS_PREFIX_PATH']
            use_default_path_flag = True
            QGIS_APP.setPrefixPath(path, use_default_path_flag)

        QGIS_APP.initQgis()
        s = QGIS_APP.showSettings()
        LOGGER.debug(s)

    global PARENT  # pylint: disable=W0603
    if PARENT is None:
        #noinspection PyPep8Naming
        PARENT = QtGui.QWidget()

    global CANVAS  # pylint: disable=W0603
    if CANVAS is None:
        #noinspection PyPep8Naming
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QtCore.QSize(400, 400))

    global IFACE  # pylint: disable=W0603
    if IFACE is None:
        # QgisInterface is a stub implementation of the QGIS plugin interface
        #noinspection PyPep8Naming
        IFACE = QgisInterface(CANVAS)

    return QGIS_APP, CANVAS, IFACE, PARENT
Example #16
0
    def setUp(self):
        model = Point
        generate_data(model=model, count=5)

        print('QGIS settings: %s' % QgsApplication.showSettings())

        registry = QgsProviderRegistry.instance()
        metadata = QgsProviderMetadata(DjangoProvider.providerKey(),
                                       DjangoProvider.description(),
                                       DjangoProvider.createProvider)
        self.assertTrue(registry.registerProvider(metadata))
        self.assertTrue(
            registry.providerMetadata(DjangoProvider.providerKey()) ==
            metadata)
Example #17
0
def get_qgis_app():
    """Start one QGIS application to test against.

    This method has been copied from PluginBuilder generated code by Gary
    Sherman: https://github.com/g-sherman/Qgis-Plugin-Builder

    :returns: Handle to QGIS app, canvas, iface and parent. If there are any
        errors the tuple members will be returned as None.
    :rtype: (QgsApplication, CANVAS, IFACE, PARENT)

    If QGIS is already running the handle to that app will be returned.
    """
    try:
        from PyQt4 import QtGui, QtCore
        from qgis.core import QgsApplication
        from qgis.gui import QgsMapCanvas
        from qgis_interface import QgisInterface
    except ImportError:
        return None, None, None, None

    global QGIS_APP  # pylint: disable=W0603

    if QGIS_APP is None:
        gui_flag = True  # All test will run qgis in gui mode
        #noinspection PyPep8Naming
        QGIS_APP = QgsApplication(sys.argv, gui_flag)
        # Make sure QGIS_PREFIX_PATH is set in your env if needed!
        QGIS_APP.initQgis()
        s = QGIS_APP.showSettings()
        LOGGER.debug(s)

    global PARENT  # pylint: disable=W0603
    if PARENT is None:
        #noinspection PyPep8Naming
        PARENT = QtGui.QWidget()

    global CANVAS  # pylint: disable=W0603
    if CANVAS is None:
        #noinspection PyPep8Naming
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QtCore.QSize(400, 400))

    global IFACE  # pylint: disable=W0603
    if IFACE is None:
        # QgisInterface is a stub implementation of the QGIS plugin interface
        #noinspection PyPep8Naming
        IFACE = QgisInterface(CANVAS)

    return QGIS_APP, CANVAS, IFACE, PARENT
Example #18
0
def get_qgis_app():
    """
    Start one QGIS application to test against.

    If QGIS is already running the handle to that app is returned.

    :returns:
     | A tuple containing:
     |    - *QgsApplication* -- QGIS application
     |    - *QgisInterface* -- QGIS interface
     |    - *QgsMapCanvas* -- QGIS map canvas
     |    - *QWidget* -- parent
    :rtype: tuple
    """

    try:
        from PyQt4 import QtGui, QtCore
        from qgis.core import QgsApplication
        from qgis.gui import QgsMapCanvas
        from qgis_interface import QgisInterface
    except ImportError:
        return None, None, None, None

    global QGIS_APP

    if QGIS_APP is None:
        # All test will run qgis in gui mode
        gui_flag = True
        QGIS_APP = QgsApplication(sys.argv, gui_flag)
        # make sure QGIS_PREFIX_PATH is set in your env if needed
        QGIS_APP.initQgis()
        s = QGIS_APP.showSettings()
        LOGGER.debug(s)

    global PARENT
    if PARENT is None:
        PARENT = QtGui.QWidget()

    global CANVAS
    if CANVAS is None:
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QtCore.QSize(400, 400))

    global IFACE
    if IFACE is None:
        # QgisInterface is a stub implementation of the QGIS plugin interface
        IFACE = QgisInterface(CANVAS)

    return QGIS_APP, IFACE, CANVAS, PARENT
Example #19
0
def getQgisTestApp():
    """ Start one QGis application to test agaist

    Input
        NIL

    Output
        handle to qgis app


    If QGis is already running the handle to that app will be returned
    """

    global QGISAPP  # pylint: disable=W0603

    if QGISAPP is None:
        myGuiFlag = True  # All test will run qgis in gui mode

        # In python3 we need to conver to a bytes object (or should
        # QgsApplication accept a QString instead of const char* ?)
        try:
            argvb = list(map(os.fsencode, sys.argv))
        except AttributeError:
            argvb = sys.argv

        # Note: QGIS_PREFIX_PATH is evaluated in QgsApplication -
        # no need to mess with it here.
        QGISAPP = QgsApplication(argvb, myGuiFlag)

        QGISAPP.initQgis()
        s = QGISAPP.showSettings()
        print(s)

    global PARENT  # pylint: disable=W0603
    if PARENT is None:
        PARENT = QWidget()

    global CANVAS  # pylint: disable=W0603
    if CANVAS is None:
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QSize(400, 400))

    global IFACE  # pylint: disable=W0603
    if IFACE is None:
        # QgisInterface is a stub implementation of the QGIS plugin interface
        IFACE = QgisInterface(CANVAS)

    return QGISAPP, CANVAS, IFACE, PARENT
Example #20
0
def getQgisTestApp():
    """ Start one QGis application to test agaist

    Input
        NIL

    Output
        handle to qgis app


    If QGis is already running the handle to that app will be returned
    """

    global QGISAPP  # pylint: disable=W0603

    if QGISAPP is None:
        myGuiFlag = True  # All test will run qgis in gui mode

        # In python3 we need to conver to a bytes object (or should
        # QgsApplication accept a QString instead of const char* ?)
        try:
            argvb = list(map(os.fsencode, sys.argv))
        except AttributeError:
            argvb = sys.argv

        # Note: QGIS_PREFIX_PATH is evaluated in QgsApplication -
        # no need to mess with it here.
        QGISAPP = QgsApplication(argvb, myGuiFlag)

        QGISAPP.initQgis()
        s = QGISAPP.showSettings()
        print(s)

    global PARENT  # pylint: disable=W0603
    if PARENT is None:
        PARENT = QWidget()

    global CANVAS  # pylint: disable=W0603
    if CANVAS is None:
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QSize(400, 400))

    global IFACE  # pylint: disable=W0603
    if IFACE is None:
        # QgisInterface is a stub implementation of the QGIS plugin interface
        IFACE = QgisInterface(CANVAS)

    return QGISAPP, CANVAS, IFACE, PARENT
Example #21
0
def getQgisTestApp():
    """ Start one QGis application to test agaist

    Input
        NIL

    Output
        handle to qgis app


    If QGis is already running the handle to that app will be returned
    """

    global QGISAPP

    if QGISAPP is None:
        myGuiFlag = True  # All test will run qgis in gui mode
        QGISAPP = QgsApplication(sys.argv, myGuiFlag)
        if 'QGISPATH' in os.environ:
            myPath = os.environ['QGISPATH']
            myUseDefaultPathFlag = True
            QGISAPP.setPrefixPath(myPath, myUseDefaultPathFlag)
        else:
            print 'Warning: QGISPATH is not set'

        QGISAPP.initQgis()
        s = QGISAPP.showSettings()
        print s

    global PARENT
    if PARENT is None:
        PARENT = QtGui.QWidget()

    global CANVAS
    if CANVAS is None:
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QtCore.QSize(400, 400))

    global IFACE
    if IFACE is None:
        # QgisInterface is a stub implementation of the QGIS plugin
        # interface
        IFACE = QgisInterface(CANVAS)

    return (QGISAPP, CANVAS, IFACE, PARENT)
Example #22
0
def getQgisTestApp():
    """ Start one QGis application to test agaist

    Input
        NIL

    Output
        handle to qgis app


    If QGis is already running the handle to that app will be returned
    """

    global QGISAPP

    if QGISAPP is None:
        myGuiFlag = True  # All test will run qgis in gui mode
        QGISAPP = QgsApplication(sys.argv, myGuiFlag)
        if 'QGISPATH' in os.environ:
            myPath = os.environ['QGISPATH']
            myUseDefaultPathFlag = True
            QGISAPP.setPrefixPath(myPath, myUseDefaultPathFlag)
        else:
            print 'Warning: QGISPATH is not set'

        QGISAPP.initQgis()
        s = QGISAPP.showSettings()
        print s

    global PARENT
    if PARENT is None:
        PARENT = QtGui.QWidget()

    global CANVAS
    if CANVAS is None:
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QtCore.QSize(400, 400))

    global IFACE
    if IFACE is None:
        # QgisInterface is a stub implementation of the QGIS plugin
        # interface
        IFACE = QgisInterface(CANVAS)

    return (QGISAPP, CANVAS, IFACE, PARENT)
Example #23
0
def getQgisTestApp():
    """ Start one QGis application to test agaist

    Input
        NIL

    Output
        handle to qgis app


    If QGis is already running the handle to that app will be returned
    """

    global QGISAPP  # pylint: disable=W0603

    if QGISAPP is None:
        myGuiFlag = True  # All test will run qgis in gui mode

        # Note: QGIS_PREFIX_PATH is evaluated in QgsApplication -
        # no need to mess with it here.
        QGISAPP = QgsApplication(sys.argv, myGuiFlag)

        QGISAPP.initQgis()
        s = QGISAPP.showSettings()
        print s

    global PARENT  # pylint: disable=W0603
    if PARENT is None:
        PARENT = QtGui.QWidget()

    global CANVAS  # pylint: disable=W0603
    if CANVAS is None:
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QtCore.QSize(400, 400))

    global IFACE  # pylint: disable=W0603
    if IFACE is None:
        # QgisInterface is a stub implementation of the QGIS plugin interface
        IFACE = QgisInterface(CANVAS)

    return QGISAPP, CANVAS, IFACE, PARENT
Example #24
0
def getQgisTestApp():
    """ Start one QGis application to test agaist

    Input
        NIL

    Output
        handle to qgis app


    If QGis is already running the handle to that app will be returned
    """

    global QGISAPP  # pylint: disable=W0603

    if QGISAPP is None:
        myGuiFlag = True  # All test will run qgis in gui mode

        # Note: QGIS_PREFIX_PATH is evaluated in QgsApplication -
        # no need to mess with it here.
        QGISAPP = QgsApplication(sys.argv, myGuiFlag)

        QGISAPP.initQgis()
        s = QGISAPP.showSettings()
        print s

    global PARENT  # pylint: disable=W0603
    if PARENT is None:
        PARENT = QWidget()

    global CANVAS  # pylint: disable=W0603
    if CANVAS is None:
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QSize(400, 400))

    global IFACE  # pylint: disable=W0603
    if IFACE is None:
        # QgisInterface is a stub implementation of the QGIS plugin interface
        IFACE = QgisInterface(CANVAS)

    return QGISAPP, CANVAS, IFACE, PARENT
Example #25
0
def start_app():
    """
    Will start a QgsApplication and call all initialization code like
    registering the providers and other infrastructure. It will not load
    any plugins.

    You can always get the reference to a running app by calling `QgsApplication.instance()`.

    The initialization will only happen once, so it is safe to call this method repeatedly.

        Returns
        -------
        QgsApplication

        A QgsApplication singleton
    """
    global QGISAPP

    try:
        QGISAPP
    except NameError:
        myGuiFlag = True  # All test will run qgis in gui mode

        # In python3 we need to convert to a bytes object (or should
        # QgsApplication accept a QString instead of const char* ?)
        try:
            argvb = list(map(os.fsencode, sys.argv))
        except AttributeError:
            argvb = sys.argv

        # Note: QGIS_PREFIX_PATH is evaluated in QgsApplication -
        # no need to mess with it here.
        QGISAPP = QgsApplication(argvb, myGuiFlag)

        QGISAPP.initQgis()
        s = QGISAPP.showSettings()
        print(s)

    return QGISAPP
Example #26
0
    def start_qgis(self):
        """Start a QgsApplication without any arguments and with *GUI mode turned off*. Also call
        its initialization method.

        The initialization will only happen once, so it is safe to call this method repeatedly.
        """
        if isinstance(self.app, QgsApplication):
            return
        self.profile_folder = tempfile.TemporaryDirectory(
            prefix='QGIS-PythonTestConfigPath')
        os.environ['QGIS_CUSTOM_CONFIG_PATH'] = self.profile_folder.name
        self.app = QgsApplication([b''], False)
        _init_qgis_app()
        print(QgsApplication.showSettings())
        _init_processing()
        sys_plugin_path = pathlib.Path(
            QgsApplication.pkgDataPath()) / 'python' / 'plugins'
        home_plugin_path = pathlib.Path(
            QgsApplication.qgisSettingsDirPath()) / 'python' / 'plugins'
        _add_plugin_paths_to_qgis(sys_plugin_path, home_plugin_path)
        _deploy_plugin_to_qgis(home_plugin_path)
        qgis.utils.updateAvailablePlugins()
Example #27
0
def start_app():
    """
    Will start a QgsApplication and call all initialization code like
    registering the providers and other infrastructure. It will not load
    any plugins.

    You can always get the reference to a running app by calling `QgsApplication.instance()`.

    The initialization will only happen once, so it is safe to call this method repeatedly.

        Returns
        -------
        QgsApplication

        A QgsApplication singleton
    """
    global QGISAPP

    try:
        QGISAPP
    except NameError:
        myGuiFlag = True  # All test will run qgis in gui mode

        # In python3 we need to convert to a bytes object (or should
        # QgsApplication accept a QString instead of const char* ?)
        try:
            argvb = list(map(os.fsencode, sys.argv))
        except AttributeError:
            argvb = sys.argv

        # Note: QGIS_PREFIX_PATH is evaluated in QgsApplication -
        # no need to mess with it here.
        QGISAPP = QgsApplication(argvb, myGuiFlag)

        QGISAPP.initQgis()
        s = QGISAPP.showSettings()
        print(s)

    return QGISAPP
Example #28
0
import roam
import roam.yaml as yaml
import roam.utils
from roam.mainwindow import MainWindow

def excepthook(errorhandler, exctype, value, traceback):
    errorhandler(exctype, value, traceback)
    roam.utils.error("Uncaught exception", exc_info=(exctype, value, traceback))

start = time.time()
roam.utils.info("Loading Roam")

QgsApplication.setPrefixPath(prefixpath, True)
QgsApplication.initQgis()

roam.utils.info(QgsApplication.showSettings())
roam.utils.info(QgsProviderRegistry.instance().pluginList())
roam.utils.info(QImageReader.supportedImageFormats())
roam.utils.info(QImageWriter.supportedImageFormats())
roam.utils.info(QgsApplication.libraryPaths())

QApplication.setStyle("Plastique")
QApplication.setFont(QFont('Segoe UI'))

class Settings:
    def __init__(self, path):
        self.path = path
        self.settings = {}

    def load(self):
        settingspath = self.path
Example #29
0
def get_qgis_app(requested_locale='en_US', qsetting=''):
    """ Start one QGIS application to test against.

    :param locale: The locale we want the qgis to launch with.
    :type locale: str

    :param qsetting: String to specify the QSettings. By default,
        use empty string.
    :type qsetting: str

    :returns: Handle to QGIS app, canvas, iface and parent. If there are any
        errors the tuple members will be returned as None.
    :rtype: (QgsApplication, CANVAS, IFACE, PARENT)

    If QGIS is already running the handle to that app will be returned.
    """
    global QGIS_APP, PARENT, IFACE, CANVAS  # pylint: disable=W0603

    from qgis.PyQt.QtCore import QSettings
    if qsetting:
        settings = QSettings(qsetting)
    else:
        settings = QSettings()

    default_user_directory = setting('defaultUserDirectory')
    current_locale = general_setting(
        'locale/userLocale', default='en_US', qsettings=settings)
    locale_match = current_locale == requested_locale

    if iface and locale_match:
        from qgis.core import QgsApplication
        QGIS_APP = QgsApplication
        CANVAS = iface.mapCanvas()
        PARENT = iface.mainWindow()
        IFACE = iface

    try:
        from qgis.core import QgsApplication
        from qgis.gui import QgsMapCanvas  # pylint: disable=no-name-in-module
        # noinspection PyPackageRequirements
        from qgis.PyQt import QtWidgets, QtCore  # pylint: disable=W0621
        # noinspection PyPackageRequirements
        from qgis.PyQt.QtCore import QCoreApplication, QSettings
        from safe.test.qgis_interface import QgisInterface
    except ImportError:
        return None, None, None, None

    if qsetting:
        settings = QSettings(qsetting)
    else:
        settings = QSettings()

    if not QGIS_APP:
        gui_flag = True  # All test will run qgis in gui mode

        # AG: For testing purposes, we use our own configuration file
        # instead of using the QGIS apps conf of the host
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setOrganizationName('QGIS')
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setOrganizationDomain('qgis.org')
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setApplicationName('QGIS2InaSAFETesting')

        # We disabled message bars for now for extent selector as
        # we don't have a main window to show them in TS - version 3.2
        set_setting('show_extent_warnings', False, settings)
        set_setting('showRubberBands', True, settings)
        set_setting('show_extent_confirmations', False, settings)
        set_setting('analysis_extents_mode', HAZARD_EXPOSURE, settings)
        if default_user_directory:
            set_setting(
                'defaultUserDirectory', default_user_directory, settings)

        # noinspection PyPep8Naming
        if 'argv' in dir(sys):
            QGIS_APP = QgsApplication([p.encode('utf-8')
                                       for p in sys.argv], gui_flag)
        else:
            QGIS_APP = QgsApplication([], gui_flag)

        # Make sure QGIS_PREFIX_PATH is set in your env if needed!
        QGIS_APP.initQgis()

        # Initialize processing
        processing.Processing.initialize()

        s = QGIS_APP.showSettings()
        LOGGER.debug(s)

    if not locale_match:
        """Setup internationalisation for the plugin."""

        # Save some settings
        set_general_setting('locale/overrideFlag', True, settings)
        set_general_setting('locale/userLocale', requested_locale, settings)

        locale_name = str(requested_locale).split('_')[0]
        # Also set the system locale to the user overridden local
        # so that the inasafe library functions gettext will work
        # .. see:: :py:func:`common.utilities`
        os.environ['LANG'] = str(locale_name)

        inasafe_translation_path = os.path.join(
            safe_dir('i18n'), 'inasafe_' + str(locale_name) + '.qm')

        if os.path.exists(inasafe_translation_path):
            if isinstance(QGIS_APP, sip.wrappertype):
                translator = QTranslator()
            else:
                translator = QTranslator(QGIS_APP)
            result = translator.load(inasafe_translation_path)
            if not result:
                message = 'Failed to load translation for %s' % locale_name
                raise Exception(message)
            # noinspection PyTypeChecker,PyCallByClass
            QCoreApplication.installTranslator(translator)

        # at the end, reload InaSAFE modules so it will get translated too
        reload_inasafe_modules()

    if PARENT is None:
        # noinspection PyPep8Naming
        PARENT = QtWidgets.QWidget()

    if CANVAS is None:
        # noinspection PyPep8Naming
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QtCore.QSize(400, 400))

    if IFACE is None:
        # QgisInterface is a stub implementation of the QGIS plugin interface
        # noinspection PyPep8Naming
        IFACE = QgisInterface(CANVAS)

    return QGIS_APP, CANVAS, IFACE, PARENT
Example #30
0
import roam.project
import roam.resources_rc

from configmanager.ui.configmanagerdialog import ConfigManagerDialog

import configmanager.settings
import configmanager.logger as logger

logger.info("Loading Roam Config Manager")
roamapp = roam.environ.setup(sys.argv)

app = QgsApplication(sys.argv, True)
QgsApplication.setPrefixPath(roamapp.prefixpath, True)
QgsApplication.initQgis()

logger.info(QgsApplication.showSettings())
logger.info(QgsProviderRegistry.instance().pluginList())
logger.info(QgsApplication.libraryPaths())

logger.info("Roam Version: {}".format(roam.__version__))
logger.info("QGIS Version: {}".format(str(QGis.QGIS_VERSION)))

QApplication.setStyle("Plastique")
QApplication.setFont(QFont('Segoe UI'))
QApplication.setWindowIcon(QIcon(':/branding/logo'))
QApplication.setApplicationName("IntraMaps Roam Config Manager")

configmanager.settings.load(roamapp.settingspath)

projectpath = roam.environ.projectpath(sys.argv)
projects = list(roam.project.getProjects(projectpath))
Example #31
0
def main(user='', masterpass='', pkidir=''):
    if not user or not pkidir:
        print 'Missing parameters for user or pkidir'
        print '  user: {0}'.format(user)
        print '  pkidir: {0}'.format(pkidir)
        sys.exit(1)

    # Get user's pre-defined QGIS master password.
    # This can be done in a variety of ways, depending upon user auth
    # systems (queried from LDAP, etc.), using a variety of Python packages.
    # As an example, we could hard-code define it as a standard password that
    # must be changed later by user, OR if we know the user's defined password.
    #masterpass = some_user_query_function(user)

    if not masterpass:
        print 'Master password must be defined'
        sys.exit(1)

    print 'Setting authentication config using:'
    print '  user: {0}'.format(user)
    print '  master pass: {0}'.format(masterpass)
    print '  pkidir: {0}'.format(pkidir)

    # instantiate QGIS
    qgsapp = QgsApplication(sys.argv, True)

    # These are for referencing the correct QSettings for the QGIS app
    QCoreApplication.setOrganizationName('QGIS')
    QCoreApplication.setOrganizationDomain('qgis.org')
    QCoreApplication.setApplicationName('QGIS2')

    # Initialize QGIS
    qgsapp.initQgis()
    print qgsapp.showSettings()

    # Initialize the auth system
    # noinspection PyArgumentList
    authm = QgsAuthManager.instance()
    authm.init()
    # This will use the standard qgis-auth.db location, but the rest of this
    # script will not work if qgis-auth.db already exists and you do NOT know
    # the user's chosen master password already stored in it.

    # If you want to generate individual qgis-auth.db for a list of users, just
    # do:
    #   authdbdir = tempfile.mkdtemp()
    #   authm.init(authdbdir)
    # Note that the saved paths to PKI components in the db will need to be the
    # same absolute paths as when the auth db is copied to the user's machine.
    # This means paths with the current user's name in them will not work when
    # copied to a different user (unless names are the same).

    print authm.authenticationDbPath()

    # Define pool of users and loop through them, or use the current user.
    #users = ["user"]
    #for user in users:

    # Set master password for QGIS and (optionally) store it in qgis-auth.db.
    # This also verifies the set password against by comparing password
    # against its derived hash stored in auth db.
    if not authm.setMasterPassword(masterpass, True):
        print 'Failed to verify or store/verify password'
        sys.exit(1)

    # Now that we have a master password set/stored, we can use it to
    # encrypt and store authentication configurations.
    # There are 3 configurations that can be stored (as of Nov 2014), and
    # examples of their initialization are in the unit tests for
    # QGIS-with-PKI source tree (test_qgsauthsystem_api-sample.py).

    # Add authentication configuration.
    # You can add as many auth configs as needed, but only one can be linked
    # to a given custom server config; although, you can create as many custom
    # server configs as needed. In this example, we are defining only one auth
    # config and linking it to multiple custom server configs, representing
    # different OWS services located at the same domain.

    # NOTE: PKI file components need to *already* exist on the filesystem in a
    # location that doesn't change, as their paths are stored in the auth db.

    # # Basic configuration
    # configname = 'My Basic Config'
    # config = QgsAuthConfigBasic()
    # config.setName(kind)
    # config.setUri('https://localhost:8443')
    # config.setUsername('username')
    # config.setPassword('password')  # will need queried or set per user
    # config.setRealm('Realm')

    # ^^  OR  vv

    # # PKI-Paths (PEM-based) configuration
    # configname = 'My PKI Paths Config'
    # config = QgsAuthConfigPkiPaths()
    # config.setName(configname)
    # config.setUri('https://localhost:8443')
    # config.setCertId(os.path.join(pkidir, '{0}_cert.pem'.format(user)))
    # config.setKeyId(os.path.join(pkidir, '{0}_key.pem'.format(user)))
    # config.setKeyPassphrase('')  # will need queried and set per user
    # config.setIssuerId(os.path.join(pkidir, 'ca.pem'))
    # config.setIssuerSelfSigned(True)

    # ^^  OR  vv

    # PKI-PKCS#12 (*.p12-based) configuration
    configname = 'My PKI PKCS#12 Config'
    config = QgsAuthConfigPkiPkcs12()
    config.setName(configname)
    config.setUri('https://localhost:8443')
    config.setBundlePath(os.path.join(pkidir, '{0}.p12'.format(user)))
    config.setBundlePassphrase(
        'password')  # will need queried and set per user
    config.setIssuerPath(os.path.join(pkidir, 'ca.pem'))
    config.setIssuerSelfSigned(True)

    # Securely store the config in database (encrypted with master password)
    res = authm.storeAuthenticationConfig(config)
    if not res[0]:
        print 'Failed to store {0} config'.format(configname)
        sys.exit(1)

    # The auth config has been given a unique ID from the auth system when it
    # was stored; retrieve it, so it can be linked to a custom server config.
    configid = config.id()

    # If the user does not have the OWS connection(s) that this auth config is
    # meant to connect to, define now.
    # NOTE: this assumes the individual connections do not already exist. If the
    # connection settings do exist, this will OVERWRITE them.

    settings = QSettings()  # get application's settings object

    print 'settings.fileName(): {0}'.format(settings.fileName())
    print 'settings.organizationName(): {0}'.format(
        settings.organizationName())
    print 'settings.applicationName(): {0}'.format(settings.applicationName())

    # WMS
    connkind = 'WMS'
    connname = 'My {0} SSL Server'.format(connkind)
    credskey = '/Qgis/{0}/{1}'.format(connkind, connname)
    connkey = '/Qgis/connections-{0}/{1}'.format(connkind.lower(), connname)

    settings.setValue(credskey + '/authid', configid)  # link to auth config
    settings.setValue(credskey + '/username',
                      '')  # deprecated; use auth config
    settings.setValue(credskey + '/password',
                      '')  # deprecated; use auth config

    settings.setValue(connkey + '/url', 'https://localhost:8443/geoserver/wms')

    # Optional settings for WMS (these are the defaults)
    # dpiMode: 0=Off, 1=QGIS, 2=UMN, 4=GeoServer, 7=All (default)
    settings.setValue(connkey + '/dpiMode', 7)
    settings.setValue(connkey + '/ignoreAxisOrientation', False)
    settings.setValue(connkey + '/ignoreGetFeatureInfoURI', False)
    settings.setValue(connkey + '/ignoreGetMapURI', False)
    settings.setValue(connkey + '/invertAxisOrientation', False)
    settings.setValue(connkey + '/referer', '')
    settings.setValue(connkey + '/smoothPixmapTransform', False)

    # WCS
    connkind = 'WCS'
    connname = 'My {0} SSL Server'.format(connkind)
    credskey = '/Qgis/{0}/{1}'.format(connkind, connname)
    connkey = '/Qgis/connections-{0}/{1}'.format(connkind.lower(), connname)

    settings.setValue(credskey + '/authid', configid)  # link to auth config
    settings.setValue(credskey + '/username',
                      '')  # deprecated; use auth config
    settings.setValue(credskey + '/password',
                      '')  # deprecated; use auth config

    settings.setValue(connkey + '/url', 'https://localhost:8443/geoserver/wcs')

    # Optional settings for WCS (these are the defaults)
    # dpiMode: 0=Off, 1=QGIS, 2=UMN, 4=GeoServer, 7=All (default)
    settings.setValue(connkey + '/dpiMode', 7)
    settings.setValue(connkey + '/ignoreAxisOrientation', False)
    settings.setValue(connkey + '/ignoreGetMapURI', False)
    settings.setValue(connkey + '/invertAxisOrientation', False)
    settings.setValue(connkey + '/referer', '')
    settings.setValue(connkey + '/smoothPixmapTransform', False)

    # WFS
    connkind = 'WFS'
    connname = 'My {0} SSL Server'.format(connkind)
    credskey = '/Qgis/{0}/{1}'.format(connkind, connname)
    connkey = '/Qgis/connections-{0}/{1}'.format(connkind.lower(), connname)

    settings.setValue(credskey + '/authid', configid)  # link to auth config
    settings.setValue(credskey + '/username',
                      '')  # deprecated; use auth config
    settings.setValue(credskey + '/password',
                      '')  # deprecated; use auth config

    settings.setValue(connkey + '/url', 'https://localhost:8443/geoserver/wfs')

    # Optional settings for WFS (these are the defaults)
    settings.setValue(connkey + '/referer', '')
Example #32
0
def get_qgis_app():
    """ Start one QGIS application to test against.

    :returns: Handle to QGIS app, canvas, iface and parent. If there are any
        errors the tuple members will be returned as None.
    :rtype: (QgsApplication, CANVAS, IFACE, PARENT)

    If QGIS is already running the handle to that app will be returned.
    """

    try:
        from PyQt4 import QtGui, QtCore
        from PyQt4.QtCore import QCoreApplication, QSettings
        from qgis.core import QgsApplication
        from qgis.gui import QgsMapCanvas
        from safe.common.qgis_interface import QgisInterface
    except ImportError:
        return None, None, None, None

    global QGIS_APP  # pylint: disable=W0603

    if QGIS_APP is None:
        gui_flag = True  # All test will run qgis in gui mode

        # AG: For testing purposes, we use our own configuration file instead
        # of using the QGIS apps conf of the host
        QCoreApplication.setOrganizationName('QGIS')
        QCoreApplication.setOrganizationDomain('qgis.org')
        QCoreApplication.setApplicationName('QGIS2InaSAFETesting')

        # noinspection PyPep8Naming
        QGIS_APP = QgsApplication(sys.argv, gui_flag)

        # Make sure QGIS_PREFIX_PATH is set in your env if needed!
        QGIS_APP.initQgis()
        s = QGIS_APP.showSettings()
        LOGGER.debug(s)

        # Save some settings
        settings = QSettings()
        settings.setValue('locale/overrideFlag', True)
        settings.setValue('locale/userLocale', 'en_US')

    global PARENT  # pylint: disable=W0603
    if PARENT is None:
        # noinspection PyPep8Naming
        PARENT = QtGui.QWidget()

    global CANVAS  # pylint: disable=W0603
    if CANVAS is None:
        # noinspection PyPep8Naming
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QtCore.QSize(400, 400))

    global IFACE  # pylint: disable=W0603
    if IFACE is None:
        # QgisInterface is a stub implementation of the QGIS plugin interface
        # noinspection PyPep8Naming
        IFACE = QgisInterface(CANVAS)

    return QGIS_APP, CANVAS, IFACE, PARENT
def main(user="", masterpass="", pkidir=""):
    if not user or not pkidir:
        print "Missing parameters for user or pkidir"
        print "  user: {0}".format(user)
        print "  pkidir: {0}".format(pkidir)
        sys.exit(1)

    # Get user's pre-defined QGIS master password.
    # This can be done in a variety of ways, depending upon user auth
    # systems (queried from LDAP, etc.), using a variety of Python packages.
    # As an example, we could hard-code define it as a standard password that
    # must be changed later by user, OR if we know the user's defined password.
    # masterpass = some_user_query_function(user)

    if not masterpass:
        print "Master password must be defined"
        sys.exit(1)

    print "Setting authentication config using:"
    print "  user: {0}".format(user)
    print "  master pass: {0}".format(masterpass)
    print "  pkidir: {0}".format(pkidir)

    # instantiate QGIS
    qgsapp = QgsApplication(sys.argv, True)

    # These are for referencing the correct QSettings for the QGIS app
    QCoreApplication.setOrganizationName("QGIS")
    QCoreApplication.setOrganizationDomain("qgis.org")
    QCoreApplication.setApplicationName("QGIS2")

    # Initialize QGIS
    qgsapp.initQgis()
    print qgsapp.showSettings()

    # Initialize the auth system
    # noinspection PyArgumentList
    authm = QgsAuthManager.instance()
    authm.init()
    # This will use the standard qgis-auth.db location, but the rest of this
    # script will not work if qgis-auth.db already exists and you do NOT know
    # the user's chosen master password already stored in it.

    # If you want to generate individual qgis-auth.db for a list of users, just
    # do:
    #   authdbdir = tempfile.mkdtemp()
    #   authm.init(authdbdir)
    # Note that the saved paths to PKI components in the db will need to be the
    # same absolute paths as when the auth db is copied to the user's machine.
    # This means paths with the current user's name in them will not work when
    # copied to a different user (unless names are the same).

    print authm.authenticationDbPath()

    # Define pool of users and loop through them, or use the current user.
    # users = ["user"]
    # for user in users:

    # Set master password for QGIS and (optionally) store it in qgis-auth.db.
    # This also verifies the set password against by comparing password
    # against its derived hash stored in auth db.
    if not authm.setMasterPassword(masterpass, True):
        print "Failed to verify or store/verify password"
        sys.exit(1)

    # Now that we have a master password set/stored, we can use it to
    # encrypt and store authentication configurations.
    # There are 3 configurations that can be stored (as of Nov 2014), and
    # examples of their initialization are in the unit tests for
    # QGIS-with-PKI source tree (test_qgsauthsystem_api-sample.py).

    # Add authentication configuration.
    # You can add as many auth configs as needed, but only one can be linked
    # to a given custom server config; although, you can create as many custom
    # server configs as needed. In this example, we are defining only one auth
    # config and linking it to multiple custom server configs, representing
    # different OWS services located at the same domain.

    # NOTE: PKI file components need to *already* exist on the filesystem in a
    # location that doesn't change, as their paths are stored in the auth db.

    # # Basic configuration
    # configname = 'My Basic Config'
    # config = QgsAuthConfigBasic()
    # config.setName(kind)
    # config.setUri('https://localhost:8443')
    # config.setUsername('username')
    # config.setPassword('password')  # will need queried or set per user
    # config.setRealm('Realm')

    # ^^  OR  vv

    # # PKI-Paths (PEM-based) configuration
    # configname = 'My PKI Paths Config'
    # config = QgsAuthConfigPkiPaths()
    # config.setName(configname)
    # config.setUri('https://localhost:8443')
    # config.setCertId(os.path.join(pkidir, '{0}_cert.pem'.format(user)))
    # config.setKeyId(os.path.join(pkidir, '{0}_key.pem'.format(user)))
    # config.setKeyPassphrase('')  # will need queried and set per user
    # config.setIssuerId(os.path.join(pkidir, 'ca.pem'))
    # config.setIssuerSelfSigned(True)

    # ^^  OR  vv

    # PKI-PKCS#12 (*.p12-based) configuration
    configname = "My PKI PKCS#12 Config"
    config = QgsAuthConfigPkiPkcs12()
    config.setName(configname)
    config.setUri("https://localhost:8443")
    config.setBundlePath(os.path.join(pkidir, "{0}.p12".format(user)))
    config.setBundlePassphrase("password")  # will need queried and set per user
    config.setIssuerPath(os.path.join(pkidir, "ca.pem"))
    config.setIssuerSelfSigned(True)

    # Securely store the config in database (encrypted with master password)
    res = authm.storeAuthenticationConfig(config)
    if not res[0]:
        print "Failed to store {0} config".format(configname)
        sys.exit(1)

    # The auth config has been given a unique ID from the auth system when it
    # was stored; retrieve it, so it can be linked to a custom server config.
    configid = config.id()

    # If the user does not have the OWS connection(s) that this auth config is
    # meant to connect to, define now.
    # NOTE: this assumes the individual connections do not already exist. If the
    # connection settings do exist, this will OVERWRITE them.

    settings = QSettings()  # get application's settings object

    print "settings.fileName(): {0}".format(settings.fileName())
    print "settings.organizationName(): {0}".format(settings.organizationName())
    print "settings.applicationName(): {0}".format(settings.applicationName())

    # WMS
    connkind = "WMS"
    connname = "My {0} SSL Server".format(connkind)
    credskey = "/Qgis/{0}/{1}".format(connkind, connname)
    connkey = "/Qgis/connections-{0}/{1}".format(connkind.lower(), connname)

    settings.setValue(credskey + "/authid", configid)  # link to auth config
    settings.setValue(credskey + "/username", "")  # deprecated; use auth config
    settings.setValue(credskey + "/password", "")  # deprecated; use auth config

    settings.setValue(connkey + "/url", "https://localhost:8443/geoserver/wms")

    # Optional settings for WMS (these are the defaults)
    # dpiMode: 0=Off, 1=QGIS, 2=UMN, 4=GeoServer, 7=All (default)
    settings.setValue(connkey + "/dpiMode", 7)
    settings.setValue(connkey + "/ignoreAxisOrientation", False)
    settings.setValue(connkey + "/ignoreGetFeatureInfoURI", False)
    settings.setValue(connkey + "/ignoreGetMapURI", False)
    settings.setValue(connkey + "/invertAxisOrientation", False)
    settings.setValue(connkey + "/referer", "")
    settings.setValue(connkey + "/smoothPixmapTransform", False)

    # WCS
    connkind = "WCS"
    connname = "My {0} SSL Server".format(connkind)
    credskey = "/Qgis/{0}/{1}".format(connkind, connname)
    connkey = "/Qgis/connections-{0}/{1}".format(connkind.lower(), connname)

    settings.setValue(credskey + "/authid", configid)  # link to auth config
    settings.setValue(credskey + "/username", "")  # deprecated; use auth config
    settings.setValue(credskey + "/password", "")  # deprecated; use auth config

    settings.setValue(connkey + "/url", "https://localhost:8443/geoserver/wcs")

    # Optional settings for WCS (these are the defaults)
    # dpiMode: 0=Off, 1=QGIS, 2=UMN, 4=GeoServer, 7=All (default)
    settings.setValue(connkey + "/dpiMode", 7)
    settings.setValue(connkey + "/ignoreAxisOrientation", False)
    settings.setValue(connkey + "/ignoreGetMapURI", False)
    settings.setValue(connkey + "/invertAxisOrientation", False)
    settings.setValue(connkey + "/referer", "")
    settings.setValue(connkey + "/smoothPixmapTransform", False)

    # WFS
    connkind = "WFS"
    connname = "My {0} SSL Server".format(connkind)
    credskey = "/Qgis/{0}/{1}".format(connkind, connname)
    connkey = "/Qgis/connections-{0}/{1}".format(connkind.lower(), connname)

    settings.setValue(credskey + "/authid", configid)  # link to auth config
    settings.setValue(credskey + "/username", "")  # deprecated; use auth config
    settings.setValue(credskey + "/password", "")  # deprecated; use auth config

    settings.setValue(connkey + "/url", "https://localhost:8443/geoserver/wfs")

    # Optional settings for WFS (these are the defaults)
    settings.setValue(connkey + "/referer", "")
Example #34
0
def start_qgis_application(
        enable_gui: bool = False,
        enable_processing: bool = False,
        verbose: bool = False,
        cleanup: bool = True,
        logger: logging.Logger = None,
        logprefix: str = 'Qgis:',
        settings: Dict = None) -> 'qgis.core.QgsApplication':
    """ Start qgis application

        :param boolean enable_gui: Enable graphical interface, default to False
        :param boolean enable_processing: Enable processing, default to False
        :param boolean verbose: Output qgis settings, default to False
        :param boolean cleanup: Register atexit hook to close qgisapplication on exit().
            Note that prevents qgis to segfault when exiting. Default to True.
    """

    os.environ['QGIS_NO_OVERRIDE_IMPORT'] = '1'
    os.environ['QGIS_DISABLE_MESSAGE_HOOKS'] = '1'

    logger = logger or logging.getLogger()
    qgisPrefixPath = setup_qgis_paths()

    from qgis.PyQt.QtCore import QCoreApplication
    from qgis.core import Qgis, QgsApplication

    logger.info("Starting Qgis application: %s", Qgis.QGIS_VERSION)

    global version_info
    version_info = tuple(
        int(n) for n in Qgis.QGIS_VERSION.split('-')[0].split('.'))

    if QgsApplication.QGIS_APPLICATION_NAME != "QGIS3":
        raise RuntimeError("You need QGIS3 (found %s)" %
                           QgsApplication.QGIS_APPLICATION_NAME)

    if not enable_gui:
        #  We MUST set the QT_QPA_PLATFORM to prevent
        #  Qt trying to connect to display in containers
        if os.environ.get('DISPLAY') is None:
            logger.info("Setting offscreen mode")
            os.environ['QT_QPA_PLATFORM'] = 'offscreen'

    global qgis_application

    qgis_application = QgsApplication([], enable_gui)
    qgis_application.setPrefixPath(qgisPrefixPath, True)

    # From qgis server
    # Will enable us to read qgis setting file
    QCoreApplication.setOrganizationName(QgsApplication.QGIS_ORGANIZATION_NAME)
    QCoreApplication.setOrganizationDomain(
        QgsApplication.QGIS_ORGANIZATION_DOMAIN)
    QCoreApplication.setApplicationName(QgsApplication.QGIS_APPLICATION_NAME)

    qgis_application.initQgis()

    if cleanup:
        # Closing QgsApplication on exit will
        # prevent our app to segfault on exit()
        import atexit

        logger.info("%s Installing cleanup hook" % logprefix)

        @atexit.register
        def exitQgis():
            global qgis_application
            if qgis_application:
                qgis_application.exitQgis()
                del qgis_application

    optpath = os.getenv('QGIS_OPTIONS_PATH')
    if optpath:
        # Log qgis settings
        load_qgis_settings(optpath, logger, verbose)

    if settings:
        # Initialize settings
        from qgis.core import QgsSettings
        qgsettings = QgsSettings()
        for k, v in settings.items():
            qgsettings.setValue(k, v)

    if verbose:
        print(qgis_application.showSettings())

    # Install logger hook
    install_logger_hook(logger, logprefix, verbose=verbose)

    logger.info("%s Qgis application initialized......" % logprefix)

    if enable_processing:
        init_qgis_processing()
        logger.info("%s QGis processing initialized" % logprefix)

    return qgis_application
class TestProviderBase(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        # to see how to setup a qgis app in pyqgis
        # https://hub.qgis.org/issues/13494#note-19
        os.environ["QGIS_DEBUG"] = str(-1)
        QCoreApplication.setOrganizationName('QGIS')
        QCoreApplication.setApplicationName('QGIS2')
        QgsApplication.setPrefixPath(os.getenv("QGIS_PREFIX_PATH"), True)
        QgsApplication.setAuthDbDirPath('/home/richard/.qgis2/')

        # ARGH... proxy, be sure that you have proxy enabled in QGIS IF you want to test within rivm (behind proxy)
        # else it keeps hanging/running after the tests

    def setUp(self):
        self.ran_errored = False
        self.ran_finished = False
        self.ran_progress = False
        self.qgs = None
        # Duh... there can only be one QApplication at a time
        # http://stackoverflow.com/questions/10888045/simple-ipython-example-raises-exception-on-sys-exit
        # if you do create >1 QgsApplications (QtApplications) then you will have non exit code 0
        self.qgs = QgsApplication.instance()  # checks if QApplication already exists
        if not self.qgs:  # create QApplication if it doesnt exist
            self.qgs = QgsApplication(sys.argv, False)
            self.qgs.initQgis()  # nessecary for opening auth db etc etc
            # out = self.qgs.showSettings()
            # print out

    def test_qgs_OK(self):
        out = self.qgs.showSettings()
        self.assertGreater(len(out), 0)

    def test_config_None(self):
        conf = None
        with self.assertRaises(TypeError):
            ProviderBase(conf)

    def test_config_NOK(self):
        conf = SimpleConfig()
        conf.url = None
        with self.assertRaises(TypeError):
            ProviderBase(conf)

    # # only working if proxy is set (when at RIVM), disable for now
    # @unittest.skip
    # def test_simple_url(self):
    #     conf = SimpleConfig()
    #     conf.url = 'https://duif.net/'
    #     prov = SimpleProvider(conf)
    #     def prov_finished(result):
    #         self.assertFalse(result.error())
    #         self.assertEquals(result.data.strip(), "ok")
    #     prov.finished.connect(prov_finished)
    #     prov.get_data()
    #     while not prov.is_finished():
    #         QCoreApplication.processEvents()
    #
    # # only working if proxy is set (when at RIVM), disable for now
    # @unittest.skip
    # def test_simple_NOK_url(self):
    #     conf = SimpleConfig()
    #     conf.url = 'htps://duif.net/'
    #     with self.assertRaises(TypeError):
    #         ProviderBase(conf)

    def test_simple_file(self):
        conf = SimpleConfig()
        # find dir of this class
        conf.url = 'file://'+os.path.join('file://', os.path.dirname(__file__), 'duif.net')
        prov = SimpleProvider(conf)
        def prov_finished(result):
            self.assertFalse(result.error())
            self.assertEquals(result.data.strip(), "ok")
        prov.finished.connect(prov_finished)
        prov.get_data()
        while not prov.is_finished():
            QCoreApplication.processEvents()
Example #36
0
def get_qgis_app():
    """ Start one QGIS application to test against.

    :returns: Handle to QGIS app, canvas, iface and parent. If there are any
        errors the tuple members will be returned as None.
    :rtype: (QgsApplication, CANVAS, IFACE, PARENT)

    If QGIS is already running the handle to that app will be returned.
    """

    try:
        from qgis.core import QgsApplication
        from qgis.gui import QgsMapCanvas  # pylint: disable=no-name-in-module
        # noinspection PyPackageRequirements
        from PyQt4 import QtGui, QtCore  # pylint: disable=W0621
        # noinspection PyPackageRequirements
        from PyQt4.QtCore import QCoreApplication, QSettings
        from safe.gis.qgis_interface import QgisInterface
    except ImportError:
        return None, None, None, None

    global QGIS_APP  # pylint: disable=W0603

    if QGIS_APP is None:
        gui_flag = True  # All test will run qgis in gui mode

        # AG: For testing purposes, we use our own configuration file instead
        # of using the QGIS apps conf of the host
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setOrganizationName('QGIS')
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setOrganizationDomain('qgis.org')
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setApplicationName('QGIS2InaSAFETesting')

        # noinspection PyPep8Naming
        QGIS_APP = QgsApplication(sys.argv, gui_flag)

        # Make sure QGIS_PREFIX_PATH is set in your env if needed!
        QGIS_APP.initQgis()
        s = QGIS_APP.showSettings()
        LOGGER.debug(s)

        # Save some settings
        settings = QSettings()
        settings.setValue('locale/overrideFlag', True)
        settings.setValue('locale/userLocale', 'en_US')
        # We disabled message bars for now for extent selector as
        # we don't have a main window to show them in TS - version 3.2
        settings.setValue('inasafe/show_extent_confirmations', False)
        settings.setValue('inasafe/show_extent_warnings', False)
        settings.setValue('inasafe/showRubberBands', True)
        settings.setValue('inasafe/analysis_extents_mode', 'HazardExposure')

    global PARENT  # pylint: disable=W0603
    if PARENT is None:
        # noinspection PyPep8Naming
        PARENT = QtGui.QWidget()

    global CANVAS  # pylint: disable=W0603
    if CANVAS is None:
        # noinspection PyPep8Naming
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QtCore.QSize(400, 400))

    global IFACE  # pylint: disable=W0603
    if IFACE is None:
        # QgisInterface is a stub implementation of the QGIS plugin interface
        # noinspection PyPep8Naming
        IFACE = QgisInterface(CANVAS)
        register_impact_functions()

    return QGIS_APP, CANVAS, IFACE, PARENT
Example #37
0
  plugins_dir = os.path.dirname(plugin_dir)

  # python path setting
  sys.path.append(plugins_dir)

  # initialize output directory
  initOutputDir()

  plugin_name = os.path.basename(plugin_dir)
  suite = unittest.TestLoader().discover(plugin_name + ".tests")
  unittest.TextTestRunner(verbosity=2).run(suite)


if __name__ == "__main__":
  gui_mode = True
  QGISAPP = QgsApplication(sys.argv, gui_mode)
  QGISAPP.initQgis()
  print "=" * 70
  print QGISAPP.showSettings()
  print "=" * 70

  # set up network disk cache
  manager = QgsNetworkAccessManager.instance()
  cache = QNetworkDiskCache(manager)
  cache.setCacheDirectory(pluginPath(os.path.join("tests", "cache")))
  cache.setMaximumCacheSize(50 * 1024 * 1024)
  manager.setCache(cache)

  # run test!
  runTest()
Example #38
0
  return result

if __name__ == "__main__":
  def usage():
    print "Usage:"
    print "    run_test.py output_file_path"
    sys.exit(1)
  
  from PyQt4.QtCore import QSize
  from PyQt4.QtGui import QWidget

  from qgis.core import QgsApplication

  if len(sys.argv) < 2:
    print "Output file path is not specified."
    usage()
  outfile = sys.argv[-1]

  myGuiFlag = True  # All test will run qgis in gui mode
  QGISAPP = QgsApplication(sys.argv, myGuiFlag)
  QGISAPP.initQgis()
  s = QGISAPP.showSettings()

  result = runTest()
  with open(outfile, "w") as f:
    f.write(result.html())
  sys.stdout = stdout
  print ""
  print "Result written to", outfile
Example #39
0
def get_qgis_app(requested_locale='en_US', qsetting=''):
    """ Start one QGIS application to test against.
    :param locale: The locale we want the qgis to launch with.
    :type locale: str
    :param qsetting: String to specify the QSettings. By default,
        use empty string.
    :type qsetting: str
    :returns: Handle to QGIS app, canvas, iface and parent. If there are any
        errors the tuple members will be returned as None.
    :rtype: (QgsApplication, CANVAS, IFACE, PARENT)
    If QGIS is already running the handle to that app will be returned.
    """
    global QGIS_APP, PARENT, IFACE, CANVAS  # pylint: disable=W0603

    from qgis.PyQt.QtCore import QSettings
    if qsetting:
        settings = QSettings(qsetting)
    else:
        settings = QSettings()

    try:
        current_locale = settings.value(
            'locale/userLocale',
            'en_US')
    except TypeError as e:
        pass

    locale_match = current_locale == requested_locale

    if iface and locale_match:
        from qgis.core import QgsApplication
        QGIS_APP = QgsApplication
        CANVAS = iface.mapCanvas()
        PARENT = iface.mainWindow()
        IFACE = iface

    try:
        from qgis.core import QgsApplication
        from qgis.gui import QgsMapCanvas  # pylint: disable=no-name-in-module
        # noinspection PyPackageRequirements
        from qgis.PyQt import QtWidgets, QtCore  # pylint: disable=W0621
        # noinspection PyPackageRequirements
        from qgis.PyQt.QtCore import QCoreApplication, QSettings
    except ImportError:
        return None, None, None, None

    if not QGIS_APP:
        gui_flag = True  # All test will run qgis in gui mode

        # AG: For testing purposes, we use our own configuration file
        # instead of using the QGIS apps conf of the host
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setOrganizationName('QGIS')
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setOrganizationDomain('qgis.org')
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setApplicationName('QGIS3Testing')

        # noinspection PyPep8Naming
        if 'argv' in dir(sys):
            QGIS_APP = QgsApplication([p.encode('utf-8')
                                       for p in sys.argv], gui_flag)
        else:
            QGIS_APP = QgsApplication([], gui_flag)

        # Make sure QGIS_PREFIX_PATH is set in your env if needed!
        QGIS_APP.initQgis()

        s = QGIS_APP.showSettings()
        LOGGER.debug(s)

    if not locale_match:
        """Setup internationalisation for the plugin."""

        if not settings:
            settings = QSettings()

        settings.setValue('locale/userLocale',
                           deep_convert_dict(
                               requested_locale))

        locale_name = str(requested_locale).split('_')[0]
        os.environ['LANG'] = str(locale_name)

        i18n_path = os.path.join(
        os.path.dirname(__file__), '../')

        i18n_path = os.path.join(i18n_path, 'i18n')

        translation_path = os.path.join(
            i18n_path, '_' + str(locale_name) + '.qm')

        if os.path.exists(translation_path):
            if isinstance(QGIS_APP, sip.wrappertype):
                translator = QTranslator()
            else:
                translator = QTranslator(QGIS_APP)
            result = translator.load(translation_path)
            if not result:
                message = 'Failed to load translation for %s' % locale_name
                raise Exception(message)
            # noinspection PyTypeChecker,PyCallByClass
            QCoreApplication.installTranslator(translator)

    if PARENT is None:
        # noinspection PyPep8Naming
        PARENT = QtWidgets.QWidget()

    if CANVAS is None:
        # noinspection PyPep8Naming
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QtCore.QSize(400, 400))

    return QGIS_APP, CANVAS, IFACE, PARENT
    QgsApplication,
    QgsVectorLayer,
    QgsProviderRegistry)


if __name__ == "__main__":
    gui_flag = True  # our app has a gui
    app = QgsApplication(sys.argv, gui_flag)

    # Some OSX specific setup
    #path = '/Applications/QGIS.app/contents/MacOS'
    #os.environ['QGIS_PREFIX_PATH'] = path
    #app.setPluginPath('/Applications/QGIS.app/contents/PlugIns/qgis/')

    # Initilise QGIS and show its state
    app.initQgis()
    print app.showSettings()
    for item in QgsProviderRegistry.instance().providerList():
        print str(item)

    base_dir = os.path.dirname(__file__)
    layer_file = 'vector.shp'
    full_path = os.path.join(base_dir, layer_file)

    layer = QgsVectorLayer(full_path, 'some points', 'ogr')
    if layer.isValid():
        feature_count = layer.dataProvider().featureCount()
        print 'Your layer has %i features' % feature_count
    else:
        print 'Sorry layer is not valid!'
Example #41
0
def get_qgis_app():
    """ Start one QGIS application to test against.

    :returns: Handle to QGIS app, canvas, iface and parent. If there are any
        errors the tuple members will be returned as None.
    :rtype: (QgsApplication, CANVAS, IFACE, PARENT)

    If QGIS is already running the handle to that app will be returned.
    """

    try:
        from PyQt4 import QtGui, QtCore
        from PyQt4.QtCore import QCoreApplication, QSettings
        from qgis.core import QgsApplication
        from qgis.gui import QgsMapCanvas
        from safe.common.qgis_interface import QgisInterface
    except ImportError:
        return None, None, None, None

    global QGIS_APP  # pylint: disable=W0603

    if QGIS_APP is None:
        gui_flag = True  # All test will run qgis in gui mode

        # AG: For testing purposes, we use our own configuration file instead
        # of using the QGIS apps conf of the host
        QCoreApplication.setOrganizationName('QGIS')
        QCoreApplication.setOrganizationDomain('qgis.org')
        QCoreApplication.setApplicationName('QGIS2InaSAFETesting')

        # noinspection PyPep8Naming
        QGIS_APP = QgsApplication(sys.argv, gui_flag)

        # Make sure QGIS_PREFIX_PATH is set in your env if needed!
        QGIS_APP.initQgis()
        s = QGIS_APP.showSettings()
        LOGGER.debug(s)

        # Save some settings
        settings = QSettings()
        settings.setValue('locale/overrideFlag', True)
        settings.setValue('locale/userLocale', 'en_US')

    global PARENT  # pylint: disable=W0603
    if PARENT is None:
        # noinspection PyPep8Naming
        PARENT = QtGui.QWidget()

    global CANVAS  # pylint: disable=W0603
    if CANVAS is None:
        # noinspection PyPep8Naming
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QtCore.QSize(400, 400))

    global IFACE  # pylint: disable=W0603
    if IFACE is None:
        # QgisInterface is a stub implementation of the QGIS plugin interface
        # noinspection PyPep8Naming
        IFACE = QgisInterface(CANVAS)

    return QGIS_APP, CANVAS, IFACE, PARENT
Example #42
0
def get_qgis_app():
    """ Start one QGIS application to test against.

    :returns: Handle to QGIS app, canvas, iface and parent. If there are any
        errors the tuple members will be returned as None.
    :rtype: (QgsApplication, CANVAS, IFACE, PARENT)

    If QGIS is already running the handle to that app will be returned.
    """

    global QGIS_APP, PARENT, IFACE, CANVAS  # pylint: disable=W0603

    if iface:
        from qgis.core import QgsApplication
        QGIS_APP = QgsApplication
        CANVAS = iface.mapCanvas()
        PARENT = iface.mainWindow()
        IFACE = iface
        return QGIS_APP, CANVAS, IFACE, PARENT

    try:
        from qgis.core import QgsApplication
        from qgis.gui import QgsMapCanvas  # pylint: disable=no-name-in-module
        # noinspection PyPackageRequirements
        from PyQt4 import QtGui, QtCore  # pylint: disable=W0621
        # noinspection PyPackageRequirements
        from PyQt4.QtCore import QCoreApplication, QSettings
        from safe.test.qgis_interface import QgisInterface
    except ImportError:
        return None, None, None, None

    if QGIS_APP is None:
        gui_flag = True  # All test will run qgis in gui mode

        # AG: For testing purposes, we use our own configuration file instead
        # of using the QGIS apps conf of the host
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setOrganizationName('QGIS')
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setOrganizationDomain('qgis.org')
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setApplicationName('QGIS2InaSAFETesting')

        # noinspection PyPep8Naming
        if 'argv' in dir(sys):
            QGIS_APP = QgsApplication(sys.argv, gui_flag)
        else:
            QGIS_APP = QgsApplication([], gui_flag)

        # Make sure QGIS_PREFIX_PATH is set in your env if needed!
        QGIS_APP.initQgis()
        s = QGIS_APP.showSettings()
        LOGGER.debug(s)

        # Save some settings
        settings = QSettings()
        settings.setValue('locale/overrideFlag', True)
        settings.setValue('locale/userLocale', 'en_US')
        # We disabled message bars for now for extent selector as
        # we don't have a main window to show them in TS - version 3.2
        settings.setValue('inasafe/show_extent_confirmations', False)
        settings.setValue('inasafe/show_extent_warnings', False)
        settings.setValue('inasafe/showRubberBands', True)
        settings.setValue('inasafe/analysis_extents_mode', HAZARD_EXPOSURE)

    if PARENT is None:
        # noinspection PyPep8Naming
        PARENT = QtGui.QWidget()

    if CANVAS is None:
        # noinspection PyPep8Naming
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QtCore.QSize(400, 400))

    if IFACE is None:
        # QgisInterface is a stub implementation of the QGIS plugin interface
        # noinspection PyPep8Naming
        IFACE = QgisInterface(CANVAS)

    return QGIS_APP, CANVAS, IFACE, PARENT
def start_qgis_application(enable_gui: bool = False,
                           enable_processing: bool = True,
                           verbose: bool = False,
                           cleanup: bool = True) -> 'QgsApplication':
    """ Start qgis application

        :param boolean enable_gui: Enable graphical interface, default to False
        :param boolean enable_processing: Enable processing, default to False
        :param boolean verbose: Output qgis settings, default to False
        :param boolean cleanup: Register atexit hook to close qgisapplication on exit().
            Note that prevents qgis to segfault when exiting. Default to True.
    """

    os.environ['QGIS_NO_OVERRIDE_IMPORT'] = '1'
    os.environ['QGIS_DISABLE_MESSAGE_HOOKS'] = '1'

    setup_qgis_paths()

    from qgis.core import QgsApplication, Qgis

    if QgsApplication.QGIS_APPLICATION_NAME != "QGIS3":
        raise RuntimeError("You need QGIS3 (found %s)" %
                           QgsApplication.QGIS_APPLICATION_NAME)

    if not enable_gui:
        #  We MUST set the QT_QPA_PLATFORM to prevent
        #  Qt trying to connect to display in containers
        if os.environ.get('DISPLAY') is None:
            print("Warning: Setting Qt offscreen mode")
            os.environ['QT_QPA_PLATFORM'] = 'offscreen'

    qgis_prefix = os.environ.get('QGIS_HOME', '/usr')

    global _qgis_application

    if _qgis_application is not None:
        print("Qgis already initialized", file=sys.stderr, flush=True)
        return _qgis_application

    _qgis_application = QgsApplication([], enable_gui)

    # Install logger hook
    install_logger_hook(verbose=verbose)

    _qgis_application.setPrefixPath(qgis_prefix, True)
    _qgis_application.initQgis()

    if cleanup:
        # Closing QgsApplication on exit will
        # prevent our app to segfault on exit()
        import atexit

        @atexit.register
        def exitQgis():
            global _qgis_application
            if _qgis_application:
                _qgis_application.exitQgis()
                del _qgis_application

    if verbose:
        print(_qgis_application.showSettings())

    if enable_processing:
        init_processing(verbose)

    if verbose:
        print("Qgis %s initialized......" % Qgis.QGIS_VERSION)

    return _qgis_application
Example #44
0
def get_qgis_app(cleanup=True):
    """ Start one QGIS application to test against.

    :returns: Handle to QGIS app, canvas, iface and parent. If there are any
        errors the tuple members will be returned as None.
    :rtype: (QgsApplication, CANVAS, IFACE, PARENT)

    If QGIS is already running the handle to that app will be returned.
    """

    global QGIS_APP, PARENT, IFACE, CANVAS  # pylint: disable=W0603

    if iface:
        QGIS_APP = QgsApplication
        CANVAS = iface.mapCanvas()
        PARENT = iface.mainWindow()
        IFACE = iface
        return QGIS_APP, CANVAS, IFACE, PARENT

    global QGISAPP  # pylint: disable=global-variable-undefined

    try:
        QGISAPP  # pylint: disable=used-before-assignment
    except NameError:
        myGuiFlag = True  # All test will run qgis in gui mode

        # In python3 we need to convert to a bytes object (or should
        # QgsApplication accept a QString instead of const char* ?)
        try:
            argvb = list(map(os.fsencode, sys.argv))
        except AttributeError:
            argvb = sys.argv

        # Note: QGIS_PREFIX_PATH is evaluated in QgsApplication -
        # no need to mess with it here.
        QGISAPP = QgsApplication(argvb, myGuiFlag)

        QGISAPP.initQgis()
        s = QGISAPP.showSettings()
        LOGGER.debug(s)

        def debug_log_message(message, tag, level):
            """
            Prints a debug message to a log
            :param message: message to print
            :param tag: log tag
            :param level: log message level (severity)
            :return:
            """
            print('{}({}): {}'.format(tag, level, message))

        QgsApplication.instance().messageLog().messageReceived.connect(
            debug_log_message)

        if cleanup:

            @atexit.register
            def exitQgis():  # pylint: disable=unused-variable
                """
                Gracefully closes the QgsApplication instance
                """
                try:
                    QGISAPP.exitQgis()  # pylint: disable=used-before-assignment
                    QGISAPP = None  # pylint: disable=redefined-outer-name
                except NameError:
                    pass

    if PARENT is None:
        # noinspection PyPep8Naming
        PARENT = QWidget()

    if CANVAS is None:
        # noinspection PyPep8Naming
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QSize(400, 400))

    if IFACE is None:
        # QgisInterface is a stub implementation of the QGIS plugin interface
        # noinspection PyPep8Naming
        IFACE = QgisInterface(CANVAS)

    return QGISAPP, CANVAS, IFACE, PARENT
Example #45
0
def get_qgis_app(requested_locale='en_US', qsetting=''):
    """ Start one QGIS application to test against.

    :param locale: The locale we want the qgis to launch with.
    :type locale: str

    :param qsetting: String to specify the QSettings. By default,
        use empty string.
    :type qsetting: str

    :returns: Handle to QGIS app, canvas, iface and parent. If there are any
        errors the tuple members will be returned as None.
    :rtype: (QgsApplication, CANVAS, IFACE, PARENT)

    If QGIS is already running the handle to that app will be returned.
    """
    global QGIS_APP, PARENT, IFACE, CANVAS  # pylint: disable=W0603

    from qgis.PyQt.QtCore import QSettings
    if qsetting:
        settings = QSettings(qsetting)
    else:
        settings = QSettings()

    default_user_directory = setting('defaultUserDirectory')
    current_locale = general_setting(
        'locale/userLocale', default='en_US', qsettings=settings)
    locale_match = current_locale == requested_locale

    if iface and locale_match:
        from qgis.core import QgsApplication
        QGIS_APP = QgsApplication
        CANVAS = iface.mapCanvas()
        PARENT = iface.mainWindow()
        IFACE = iface

    try:
        from qgis.core import QgsApplication
        from qgis.gui import QgsMapCanvas  # pylint: disable=no-name-in-module
        # noinspection PyPackageRequirements
        from qgis.PyQt import QtWidgets, QtCore  # pylint: disable=W0621
        # noinspection PyPackageRequirements
        from qgis.PyQt.QtCore import QCoreApplication, QSettings
        from safe.test.qgis_interface import QgisInterface
    except ImportError:
        return None, None, None, None

    if qsetting:
        settings = QSettings(qsetting)
    else:
        settings = QSettings()

    if not QGIS_APP:
        gui_flag = True  # All test will run qgis in gui mode

        # AG: For testing purposes, we use our own configuration file
        # instead of using the QGIS apps conf of the host
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setOrganizationName('QGIS')
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setOrganizationDomain('qgis.org')
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setApplicationName('QGIS2InaSAFETesting')

        # We disabled message bars for now for extent selector as
        # we don't have a main window to show them in TS - version 3.2
        set_setting('show_extent_warnings', False, settings)
        set_setting('showRubberBands', True, settings)
        set_setting('show_extent_confirmations', False, settings)
        set_setting('analysis_extents_mode', HAZARD_EXPOSURE, settings)
        if default_user_directory:
            set_setting(
                'defaultUserDirectory', default_user_directory, settings)

        # noinspection PyPep8Naming
        if 'argv' in dir(sys):
            QGIS_APP = QgsApplication([p.encode('utf-8')
                                       for p in sys.argv], gui_flag)
        else:
            QGIS_APP = QgsApplication([], gui_flag)

        # Make sure QGIS_PREFIX_PATH is set in your env if needed!
        QGIS_APP.initQgis()

        # Initialize processing
        processing.Processing.initialize()

        s = QGIS_APP.showSettings()
        LOGGER.debug(s)

    if not locale_match:
        """Setup internationalisation for the plugin."""

        # Save some settings
        set_general_setting('locale/overrideFlag', True, settings)
        set_general_setting('locale/userLocale', requested_locale, settings)

        locale_name = str(requested_locale).split('_')[0]
        # Also set the system locale to the user overridden local
        # so that the inasafe library functions gettext will work
        # .. see:: :py:func:`common.utilities`
        os.environ['LANG'] = str(locale_name)

        inasafe_translation_path = os.path.join(
            safe_dir('i18n'), 'inasafe_' + str(locale_name) + '.qm')

        if os.path.exists(inasafe_translation_path):
            if isinstance(QGIS_APP, sip.wrappertype):
                translator = QTranslator()
            else:
                translator = QTranslator(QGIS_APP)
            result = translator.load(inasafe_translation_path)
            if not result:
                message = 'Failed to load translation for %s' % locale_name
                raise Exception(message)
            # noinspection PyTypeChecker,PyCallByClass
            QCoreApplication.installTranslator(translator)

        # at the end, reload InaSAFE modules so it will get translated too
        reload_inasafe_modules()

    if PARENT is None:
        # noinspection PyPep8Naming
        PARENT = QtWidgets.QWidget()

    if CANVAS is None:
        # noinspection PyPep8Naming
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QtCore.QSize(400, 400))

    if IFACE is None:
        # QgisInterface is a stub implementation of the QGIS plugin interface
        # noinspection PyPep8Naming
        IFACE = QgisInterface(CANVAS)

    return QGIS_APP, CANVAS, IFACE, PARENT
    plugins_dir = os.path.dirname(plugin_dir)

    # python path setting
    sys.path.append(plugins_dir)

    # initialize output directory
    initOutputDir()

    plugin_name = os.path.basename(plugin_dir)
    suite = unittest.TestLoader().discover(plugin_name + ".tests")
    unittest.TextTestRunner(verbosity=2).run(suite)


if __name__ == "__main__":
    gui_mode = True
    QGISAPP = QgsApplication(sys.argv, gui_mode)
    QGISAPP.initQgis()
    print("=" * 70)
    print(QGISAPP.showSettings())
    print("=" * 70)

    # set up network disk cache
    manager = QgsNetworkAccessManager.instance()
    cache = QNetworkDiskCache(manager)
    cache.setCacheDirectory(pluginPath(os.path.join("tests", "cache")))
    cache.setMaximumCacheSize(50 * 1024 * 1024)
    manager.setCache(cache)

    # run test!
    runTest()
Example #47
0
def get_qgis_app():
    """ Start one QGIS application to test against.

    :returns: Handle to QGIS app, canvas, iface and parent. If there are any
        errors the tuple members will be returned as None.
    :rtype: (QgsApplication, CANVAS, IFload_standard_layersACE, PARENT)

    If QGIS is already running the handle to that app will be returned.
    """

    try:
        from qgis.core import QgsApplication
        from qgis.gui import QgsMapCanvas  # pylint: disable=no-name-in-module
        # noinspection PyPackageRequirements
        from qgis.PyQt import QtGui, QtCore  # pylint: disable=W0621
        # noinspection PyPackageRequirements
        from qgis.PyQt.QtCore import QCoreApplication, QSettings
        from qgis.gui import QgisInterface
    except ImportError:
        return None, None, None, None

    global QGIS_APP  # pylint: disable=W0603

    if QGIS_APP is None:
        gui_flag = True  # All test will run qgis in gui mode

        # AG: For testing purposes, we use our own configuration file instead
        # of using the QGIS apps conf of the host
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setOrganizationName('QGIS')
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setOrganizationDomain('qgis.org')
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setApplicationName('IsochronesTesting')

        # noinspection PyPep8Naming
        QGIS_APP = QgsApplication(sys.argv, gui_flag)

        # Make sure QGIS_PREFIX_PATH is set in your env if needed!
        QGIS_APP.initQgis()
        s = QGIS_APP.showSettings()

        # Save some settings
        settings = QSettings()
        settings.setValue('locale/overrideFlag', True)
        settings.setValue('locale/userLocale', 'en_US')
        # We disabled message bars for now for extent selector as
        # we don't have a main window to show them in TS - version 3.2

    global PARENT  # pylint: disable=W0603
    if PARENT is None:
        # noinspection PyPep8Naming
        PARENT = QtGui.QWidget()

    global CANVAS  # pylint: disable=W0603
    if CANVAS is None:
        # noinspection PyPep8Naming
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QtCore.QSize(400, 400))

    global IFACE  # pylint: disable=W0603
    if IFACE is None:
        # QgisInterface is a stub implementation of the QGIS plugin interface
        # noinspection PyPep8Naming
        IFACE = QgisInterface(CANVAS)

    return QGIS_APP, CANVAS, IFACE, PARENT
Example #48
0
def start_qgis_application(
        enable_gui: bool = False,
        enable_processing: bool = False,
        verbose: bool = False,
        cleanup: bool = True,
        logger: logging.Logger = None,
        logprefix: str = 'Qgis:') -> 'QgsApplication':  # noqa: F821
    """ Start qgis application

        :param boolean enable_gui: Enable graphical interface, default to False
        :param boolean enable_processing: Enable processing, default to False
        :param boolean verbose: Output qgis settings, default to False
        :param boolean cleanup: Register atexit hook to close qgisapplication on exit().
            Note that prevents qgis to segfault when exiting. Default to True.
    """
    os.environ['QGIS_NO_OVERRIDE_IMPORT'] = '1'
    os.environ['QGIS_DISABLE_MESSAGE_HOOKS'] = '1'

    logger = logger or logging.getLogger()
    setup_qgis_paths()

    from qgis.core import Qgis, QgsApplication

    logger.info("Starting Qgis application: %s", Qgis.QGIS_VERSION)

    if QgsApplication.QGIS_APPLICATION_NAME != "QGIS3":
        raise RuntimeError("You need QGIS3 (found %s)" %
                           QgsApplication.QGIS_APPLICATION_NAME)

    if not enable_gui:
        #  We MUST set the QT_QPA_PLATFORM to prevent
        #  Qt trying to connect to display in containers
        if os.environ.get('DISPLAY') is None:
            logger.info("Setting offscreen mode")
            os.environ['QT_QPA_PLATFORM'] = 'offscreen'

    qgis_prefix = os.environ.get('QGIS3_HOME', '/usr')

    # XXX Set QGIS_PREFIX_PATH, it seems that setPrefixPath
    # does not do the job correctly
    os.environ['QGIS_PREFIX_PATH'] = qgis_prefix

    global qgis_application

    qgis_application = QgsApplication([], enable_gui)
    qgis_application.setPrefixPath(qgis_prefix, True)
    qgis_application.initQgis()

    if cleanup:
        # Closing QgsApplication on exit will
        # prevent our app to segfault on exit()
        import atexit

        logger.info("%s Installing cleanup hook" % logprefix)

        @atexit.register
        def exitQgis():
            global qgis_application
            if qgis_application:
                qgis_application.exitQgis()
                del qgis_application

    if verbose:
        print(qgis_application.showSettings())

    # Install logger hook
    install_logger_hook(logger, logprefix, verbose=verbose)

    logger.info("%s Qgis application initialized......" % logprefix)

    if enable_processing:
        init_processing()
        logger.info("%s QGis processing initialized" % logprefix)

    return qgis_application
Example #49
0
    for i in range(getSize()[0] * getSize()[1]):
        fileName = str(x[0]) + "_" + str(x[1]) + "_DOM.asc"
        getLayer(ascFolder + fileName, fileName)
        x, n = getNext(x, n)


if __name__ == "__main__":

    outputImageName = "multipatch." + str(
        os.environ['__VJ_INTERMEDIATE_GRAPHICS_FORMAT__'])

    print "initQgis"
    qgishome = "/usr"
    QgsApplication.setPrefixPath(qgishome, True)
    QgsApplication.initQgis()
    print QgsApplication.showSettings()

    print "    ...Done"

    load_layers()

    style = 'templatestyle.qml'
    print "Set style:", style
    for layer in QgsMapLayerRegistry.instance().mapLayers().values():
        layer.loadNamedStyle(style)
    print "    ...Done"

    # Render all loaded layers (works with project files to)
    resolution = os.environ["__VJ_RESOLUTION_HEIGHTMAP__"]

    renderLayers(int(resolution),
Example #50
0
    plugins_dir = os.path.dirname(plugin_dir)

    # python path setting
    sys.path.append(plugins_dir)

    # initialize output directory
    initOutputDir()

    plugin_name = os.path.basename(plugin_dir)
    suite = unittest.TestLoader().discover(plugin_name + ".tests")
    unittest.TextTestRunner(verbosity=2).run(suite)


if __name__ == "__main__":
    gui_mode = True
    QGISAPP = QgsApplication(sys.argv, gui_mode)
    QGISAPP.initQgis()
    print "=" * 70
    print QGISAPP.showSettings()
    print "=" * 70

    # set up network disk cache
    manager = QgsNetworkAccessManager.instance()
    cache = QNetworkDiskCache(manager)
    cache.setCacheDirectory(pluginPath(os.path.join("tests", "cache")))
    cache.setMaximumCacheSize(50 * 1024 * 1024)
    manager.setCache(cache)

    # run test!
    runTest()
Example #51
-1
def getQgisTestApp():
    """ Start one QGis application to test agaist

    Input
        NIL

    Output
        handle to qgis app


    If QGis is already running the handle to that app will be returned
    """

    global QGISAPP  # pylint: disable=W0603

    if QGISAPP is None:
        myGuiFlag = True  # All test will run qgis in gui mode
        QGISAPP = QgsApplication(sys.argv, myGuiFlag)
        if 'QGIS_PREFIX_PATH' in os.environ:
            myPath = os.environ['QGIS_PREFIX_PATH']
            myUseDefaultPathFlag = True
            QGISAPP.setPrefixPath(myPath, myUseDefaultPathFlag)

        if sys.platform.startswith('darwin'):
            # override resource paths, otherwise looks for Resources in app
            if 'QGIS_MAC_PKGDATA_DIR' in os.environ:
                myPkgPath = os.environ['QGIS_MAC_PKGDATA_DIR']
                QGISAPP.setPkgDataPath(myPkgPath)
            if 'QGIS_MAC_SVG_DIR'  in os.environ:
                mySVGPath = os.environ['QGIS_MAC_SVG_DIR']
                mySVGPaths = QGISAPP.svgPaths()
                # doesn't get rid of incorrect path, just adds correct one
                mySVGPaths.prepend(mySVGPath)
                QGISAPP.setDefaultSvgPaths(mySVGPaths)

        QGISAPP.initQgis()
        s = QGISAPP.showSettings()
        print s

    global PARENT  # pylint: disable=W0603
    if PARENT is None:
        PARENT = QtGui.QWidget()

    global CANVAS  # pylint: disable=W0603
    if CANVAS is None:
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QtCore.QSize(400, 400))

    global IFACE  # pylint: disable=W0603
    if IFACE is None:
        # QgisInterface is a stub implementation of the QGIS plugin interface
        IFACE = QgisInterface(CANVAS)

    return QGISAPP, CANVAS, IFACE, PARENT