guiutils.py 4.8 KB

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