guiutils.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. """
  2. @package startup.guiutils
  3. @brief General GUI-dependent utilities for GUI startup of GRASS GIS
  4. (C) 2018 by Vaclav Petras the GRASS Development Team
  5. This program is free software under the GNU General Public License
  6. (>=v2). Read the file COPYING that comes with GRASS for details.
  7. @author Vaclav Petras <wenzeslaus gmail com>
  8. This is for code which depend on something from GUI (wx or wxGUI).
  9. """
  10. import os
  11. import grass.script as gs
  12. from core import globalvar
  13. from core.gcmd import GError, DecodeString, RunCommand
  14. from gui_core.dialogs import TextEntryDialog
  15. from gui_core.widgets import GenericMultiValidator
  16. def SetSessionMapset(database, location, mapset):
  17. """Sets database, location and mapset for the current session"""
  18. RunCommand("g.gisenv", set="GISDBASE=%s" % database)
  19. RunCommand("g.gisenv", set="LOCATION_NAME=%s" % location)
  20. RunCommand("g.gisenv", set="MAPSET=%s" % mapset)
  21. class NewMapsetDialog(TextEntryDialog):
  22. def __init__(self, parent=None, default=None,
  23. database=None, location=None):
  24. self.database = database
  25. self.location = location
  26. # list of tuples consisting of conditions and callbacks
  27. checks = [(gs.legal_name, self._nameValidationFailed),
  28. (self._checkMapsetNotExists, self._mapsetAlreadyExists),
  29. (self._checkOGR, self._reservedMapsetName)]
  30. validator = GenericMultiValidator(checks)
  31. TextEntryDialog.__init__(
  32. self, parent=parent,
  33. message=_("Name for the new mapset:"),
  34. caption=_("Create new mapset"),
  35. defaultValue=default,
  36. validator=validator,
  37. )
  38. def _nameValidationFailed(self, ctrl):
  39. message = _(
  40. "Name '{}' is not a valid name for location or mapset. "
  41. "Please use only ASCII characters excluding characters {} "
  42. "and space.").format(ctrl.GetValue(), '/"\'@,=*~')
  43. GError(parent=self, message=message, caption=_("Invalid name"))
  44. def _checkOGR(self, text):
  45. """Check user's input for reserved mapset name."""
  46. if text.lower() == 'ogr':
  47. return False
  48. return True
  49. def _reservedMapsetName(self, ctrl):
  50. message = _(
  51. "Name '{}' is reserved for direct "
  52. "read access to OGR layers. Please use "
  53. "another name for your mapset.").format(ctrl.GetValue())
  54. GError(parent=self, message=message,
  55. caption=_("Reserved mapset name"))
  56. def _checkMapsetNotExists(self, text):
  57. """Check whether user's input mapset exists or not."""
  58. if mapset_exists(self.database, self.location, text):
  59. return False
  60. return True
  61. def _mapsetAlreadyExists(self, ctrl):
  62. message = _(
  63. "Mapset '{}' already exists. Please consider to use "
  64. "another name for your location.").format(ctrl.GetValue())
  65. GError(parent=self, message=message, caption=_("Existing mapset path"))
  66. # TODO: similar to (but not the same as) read_gisrc function in grass.py
  67. def read_gisrc():
  68. """Read variables from a current GISRC file
  69. Returns a dictionary representation of the file content.
  70. """
  71. grassrc = {}
  72. gisrc = os.getenv("GISRC")
  73. if gisrc and os.path.isfile(gisrc):
  74. try:
  75. rc = open(gisrc, "r")
  76. for line in rc.readlines():
  77. try:
  78. key, val = line.split(":", 1)
  79. except ValueError as e:
  80. sys.stderr.write(
  81. _('Invalid line in GISRC file (%s):%s\n' % (e, line)))
  82. grassrc[key.strip()] = DecodeString(val.strip())
  83. finally:
  84. rc.close()
  85. return grassrc
  86. def GetVersion():
  87. """Gets version and revision
  88. Returns tuple `(version, revision)`. For standard releases revision
  89. is an empty string.
  90. Revision string is currently wrapped in parentheses with added
  91. leading space. This is an implementation detail and legacy and may
  92. change anytime.
  93. """
  94. versionFile = open(os.path.join(globalvar.ETCDIR, "VERSIONNUMBER"))
  95. versionLine = versionFile.readline().rstrip('\n')
  96. versionFile.close()
  97. try:
  98. grassVersion, grassRevision = versionLine.split(' ', 1)
  99. if grassVersion.endswith('dev'):
  100. grassRevisionStr = ' (%s)' % grassRevision
  101. else:
  102. grassRevisionStr = ''
  103. except ValueError:
  104. grassVersion = versionLine
  105. grassRevisionStr = ''
  106. return (grassVersion, grassRevisionStr)
  107. def mapset_exists(database, location, mapset):
  108. """Returns True whether mapset path exists."""
  109. location_path = os.path.join(database, location)
  110. mapset_path = os.path.join(location_path, mapset)
  111. if os.path.exists(mapset_path):
  112. return True
  113. return False