ee_plugin.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. # -*- coding: utf-8 -*-
  2. """
  3. Main plugin file.
  4. """
  5. from __future__ import absolute_import
  6. import configparser
  7. import requests
  8. import webbrowser
  9. from builtins import object
  10. import os.path
  11. import json
  12. from qgis.PyQt.QtCore import QSettings, QTranslator, qVersion, QCoreApplication
  13. from qgis.PyQt.QtWidgets import QAction
  14. from qgis.PyQt.QtGui import QIcon
  15. from qgis.core import QgsProject
  16. from ee_plugin import provider
  17. from ee_plugin.icons import resources
  18. # read the plugin version from metadata
  19. cfg = configparser.ConfigParser()
  20. cfg.read(os.path.join(os.path.dirname(__file__), 'metadata.txt'))
  21. VERSION = cfg.get('general', 'version')
  22. version_checked = False
  23. class GoogleEarthEnginePlugin(object):
  24. """QGIS Plugin Implementation."""
  25. def __init__(self, iface):
  26. """Constructor.
  27. :param iface: An interface instance that will be passed to this class
  28. which provides the hook by which you can manipulate the QGIS
  29. application at run time.
  30. :type iface: QgsInterface
  31. """
  32. # Save reference to the QGIS interface
  33. self.iface = iface
  34. # initialize plugin directory
  35. self.plugin_dir = os.path.dirname(__file__)
  36. # initialize locale
  37. locale = QSettings().value('locale/userLocale')[0:2]
  38. locale_path = os.path.join(
  39. self.plugin_dir,
  40. 'i18n',
  41. 'GoogleEarthEnginePlugin_{}.qm'.format(locale))
  42. if os.path.exists(locale_path):
  43. self.translator = QTranslator()
  44. self.translator.load(locale_path)
  45. if qVersion() > '4.3.3':
  46. QCoreApplication.installTranslator(self.translator)
  47. self.menu_name_plugin = self.tr("Google Earth Engine Plugin")
  48. # Create and register the EE data providers
  49. provider.register_data_provider()
  50. # noinspection PyMethodMayBeStatic
  51. def tr(self, message):
  52. """Get the translation for a string using Qt translation API.
  53. We implement this ourselves since we do not inherit QObject.
  54. :param message: String for translation.
  55. :type message: str, QString
  56. :returns: Translated version of message.
  57. :rtype: QString
  58. """
  59. # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
  60. return QCoreApplication.translate('GoogleEarthEngine', message)
  61. def initGui(self):
  62. ### Main dockwidget menu
  63. # Create action that will start plugin configuration
  64. icon_path = ':/plugins/ee_plugin/icons/earth_engine.svg'
  65. self.dockable_action = QAction(
  66. QIcon(icon_path), "User Guide", self.iface.mainWindow())
  67. # connect the action to the run method
  68. self.dockable_action.triggered.connect(self.run)
  69. # Add menu item
  70. self.iface.addPluginToMenu(self.menu_name_plugin, self.dockable_action)
  71. # Register signal to initialize EE layers on project load
  72. self.iface.projectRead.connect(self.updateLayers)
  73. def run(self):
  74. # open user guide in external web browser
  75. webbrowser.open_new(
  76. "http://qgis-ee-plugin.appspot.com/user-guide")
  77. def check_version(self):
  78. global version_checked
  79. if version_checked:
  80. return
  81. try:
  82. latest_version = requests.get('https://qgis-ee-plugin.appspot.com/get_latest_version').text
  83. if VERSION < latest_version:
  84. self.iface.messageBar().pushMessage('Earth Engine plugin:',
  85. 'There is a more recent version of the ee_plugin available {0} and you have {1}, please upgrade!'.format(latest_version, VERSION), duration=15)
  86. except:
  87. print('Error occurred when checking for recent plugin version, skipping ...')
  88. finally:
  89. version_checked = True
  90. def unload(self):
  91. # Remove the plugin menu item and icon
  92. self.iface.removePluginMenu(
  93. self.menu_name_plugin, self.dockable_action)
  94. def updateLayers(self):
  95. import ee
  96. from ee_plugin.utils import add_or_update_ee_layer
  97. layers = QgsProject.instance().mapLayers().values()
  98. for l in filter(lambda layer: layer.customProperty('ee-layer'), layers):
  99. ee_object = l.customProperty('ee-object')
  100. ee_object_vis = l.customProperty('ee-object-vis')
  101. # check for backward-compatibility, older file formats (before 0.0.3) store ee-objects in ee-script property an no ee-object-vis is stored
  102. # also, it seems that JSON representation of persistent object has been changed, making it difficult to read older EE JSON
  103. if ee_object is None:
  104. print('\nWARNING:\n Map layer saved with older version of EE plugin is detected, backward-compatibility for versions before 0.0.3 is not supported due to changes in EE library, please re-create EE layer by re-running the Python script\n')
  105. return
  106. ee_object = ee.deserializer.fromJSON(ee_object)
  107. if ee_object_vis is not None:
  108. ee_object_vis = json.loads(ee_object_vis)
  109. # update loaded EE layer
  110. # get existing values for name, visibility, and opacity
  111. # TODO: this should not be needed, refactor add_or_update_ee_layer to update_ee_layer
  112. name = l.name()
  113. shown = QgsProject.instance().layerTreeRoot().findLayer(l.id()).itemVisibilityChecked()
  114. opacity = l.renderer().opacity()
  115. add_or_update_ee_layer(ee_object, ee_object_vis, name, shown, opacity)