ScriptUtils.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. """
  2. ***************************************************************************
  3. ScriptUtils.py
  4. ---------------------
  5. Date : August 2012
  6. Copyright : (C) 2012 by Victor Olaya
  7. Email : volayaf at gmail dot com
  8. ***************************************************************************
  9. * *
  10. * This program is free software; you can redistribute it and/or modify *
  11. * it under the terms of the GNU General Public License as published by *
  12. * the Free Software Foundation; either version 2 of the License, or *
  13. * (at your option) any later version. *
  14. * *
  15. ***************************************************************************
  16. """
  17. __author__ = 'Victor Olaya'
  18. __date__ = 'August 2012'
  19. __copyright__ = '(C) 2012, Victor Olaya'
  20. from qgis.processing import alg as algfactory
  21. import os
  22. import inspect
  23. import importlib.util
  24. from qgis.PyQt.QtCore import QCoreApplication, QDir
  25. from qgis.core import (Qgis,
  26. QgsApplication,
  27. QgsProcessingAlgorithm,
  28. QgsProcessingFeatureBasedAlgorithm,
  29. QgsMessageLog
  30. )
  31. from processing.core.ProcessingConfig import ProcessingConfig
  32. from processing.tools.system import mkdir, userFolder
  33. scriptsRegistry = {}
  34. SCRIPTS_FOLDERS = "SCRIPTS_FOLDERS"
  35. def defaultScriptsFolder():
  36. folder = str(os.path.join(userFolder(), "scripts"))
  37. mkdir(folder)
  38. return os.path.abspath(folder)
  39. def scriptsFolders():
  40. folder = ProcessingConfig.getSetting(SCRIPTS_FOLDERS)
  41. if folder is not None:
  42. return folder.split(";")
  43. else:
  44. return [defaultScriptsFolder()]
  45. def loadAlgorithm(moduleName, filePath):
  46. global scriptsRegistry
  47. try:
  48. spec = importlib.util.spec_from_file_location(moduleName, filePath)
  49. module = importlib.util.module_from_spec(spec)
  50. spec.loader.exec_module(module)
  51. try:
  52. alg = algfactory.instances.pop().createInstance()
  53. scriptsRegistry[alg.name()] = filePath
  54. return alg
  55. except IndexError:
  56. for x in dir(module):
  57. obj = getattr(module, x)
  58. if inspect.isclass(obj) and issubclass(obj, (QgsProcessingAlgorithm, QgsProcessingFeatureBasedAlgorithm)) and obj.__name__ not in ("QgsProcessingAlgorithm", "QgsProcessingFeatureBasedAlgorithm"):
  59. o = obj()
  60. scriptsRegistry[o.name()] = filePath
  61. return o
  62. except (ImportError, AttributeError, TypeError) as e:
  63. QgsMessageLog.logMessage(QCoreApplication.translate("ScriptUtils", "Could not import script algorithm '{}' from '{}'\n{}").format(moduleName, filePath, str(e)),
  64. QCoreApplication.translate("ScriptUtils", "Processing"),
  65. Qgis.Critical)
  66. def findAlgorithmSource(name):
  67. global scriptsRegistry
  68. try:
  69. return scriptsRegistry[name]
  70. except:
  71. return None
  72. def resetScriptFolder(folder):
  73. """Check if script folder exist. If not, notify and try to check if it is absolute to another user setting.
  74. If so, modify folder to change user setting to the current user setting."""
  75. newFolder = folder
  76. if os.path.exists(newFolder):
  77. return newFolder
  78. QgsMessageLog.logMessage(QgsApplication .translate("loadAlgorithms", "Script folder {} does not exist").format(newFolder),
  79. QgsApplication.translate("loadAlgorithms", "Processing"),
  80. Qgis.Warning)
  81. if not os.path.isabs(newFolder):
  82. return None
  83. # try to check if folder is absolute to other QgsApplication.qgisSettingsDirPath()
  84. # isolate "QGIS3/profiles/"
  85. appIndex = -4
  86. profileIndex = -3
  87. currentSettingPath = QDir.toNativeSeparators(QgsApplication.qgisSettingsDirPath())
  88. paths = currentSettingPath.split(os.sep)
  89. commonSettingPath = os.path.join(paths[appIndex], paths[profileIndex])
  90. if commonSettingPath in newFolder:
  91. # strip not common folder part. e.g. preserve the profile path
  92. # stripping the heading part that come from another location
  93. tail = newFolder[newFolder.find(commonSettingPath):]
  94. # tail folder with the actual userSetting path
  95. header = os.path.join(os.sep, os.path.join(*paths[:appIndex]))
  96. newFolder = os.path.join(header, tail)
  97. # skip if it does not exist
  98. if not os.path.exists(newFolder):
  99. return None
  100. QgsMessageLog.logMessage(QgsApplication .translate("loadAlgorithms", "Script folder changed into {}").format(newFolder),
  101. QgsApplication.translate("loadAlgorithms", "Processing"),
  102. Qgis.Warning)
  103. return newFolder