File: ScriptUtils.py

package info (click to toggle)
qgis 3.40.6%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 1,181,336 kB
  • sloc: cpp: 1,593,302; python: 370,494; xml: 23,474; perl: 3,664; sh: 3,482; ansic: 2,257; sql: 2,133; yacc: 1,068; lex: 577; javascript: 540; lisp: 411; makefile: 157
file content (154 lines) | stat: -rw-r--r-- 5,202 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
"""
***************************************************************************
    ScriptUtils.py
    ---------------------
    Date                 : August 2012
    Copyright            : (C) 2012 by Victor Olaya
    Email                : volayaf at gmail dot com
***************************************************************************
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
*                                                                         *
***************************************************************************
"""

__author__ = "Victor Olaya"
__date__ = "August 2012"
__copyright__ = "(C) 2012, Victor Olaya"

from qgis.processing import alg as algfactory
import os
import inspect
import importlib.util

from qgis.PyQt.QtCore import QCoreApplication, QDir

from qgis.core import (
    Qgis,
    QgsApplication,
    QgsProcessingAlgorithm,
    QgsProcessingFeatureBasedAlgorithm,
    QgsMessageLog,
)

from processing.core.ProcessingConfig import ProcessingConfig
from processing.tools.system import mkdir, userFolder

scriptsRegistry = {}

SCRIPTS_FOLDERS = "SCRIPTS_FOLDERS"


def defaultScriptsFolder():
    folder = str(os.path.join(userFolder(), "scripts"))
    mkdir(folder)
    return os.path.abspath(folder)


def scriptsFolders():
    folder = ProcessingConfig.getSetting(SCRIPTS_FOLDERS)
    if folder is not None:
        return folder.split(";")
    else:
        return [defaultScriptsFolder()]


def loadAlgorithm(moduleName, filePath):
    global scriptsRegistry

    try:
        spec = importlib.util.spec_from_file_location(moduleName, filePath)
        module = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(module)
        try:
            alg = algfactory.instances.pop().createInstance()
            scriptsRegistry[alg.name()] = filePath
            return alg
        except IndexError:
            for x in dir(module):
                obj = getattr(module, x)
                if (
                    inspect.isclass(obj)
                    and issubclass(
                        obj,
                        (QgsProcessingAlgorithm, QgsProcessingFeatureBasedAlgorithm),
                    )
                    and obj.__name__
                    not in (
                        "QgsProcessingAlgorithm",
                        "QgsProcessingFeatureBasedAlgorithm",
                    )
                ):
                    o = obj()
                    scriptsRegistry[o.name()] = filePath
                    return o
    except (ImportError, AttributeError, TypeError) as e:
        QgsMessageLog.logMessage(
            QCoreApplication.translate(
                "ScriptUtils", "Could not import script algorithm '{}' from '{}'\n{}"
            ).format(moduleName, filePath, str(e)),
            QCoreApplication.translate("ScriptUtils", "Processing"),
            Qgis.MessageLevel.Critical,
        )


def findAlgorithmSource(name):
    global scriptsRegistry
    try:
        return scriptsRegistry[name]
    except:
        return None


def resetScriptFolder(folder):
    """Check if script folder exist. If not, notify and try to check if it is absolute to another user setting.
    If so, modify folder to change user setting to the current user setting."""

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

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

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

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

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

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

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

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

    return newFolder