main.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. """!
  2. @package mapdisp.main
  3. @brief Start Map Display as standalone application
  4. Classes:
  5. - mapdisp::MapApp
  6. Usage:
  7. python mapdisp/main.py monitor-identifier /path/to/map/file /path/to/command/file /path/to/env/file
  8. (C) 2006-2011 by the GRASS Development Team
  9. This program is free software under the GNU General Public License
  10. (>=v2). Read the file COPYING that comes with GRASS for details.
  11. @author Michael Barton
  12. @author Jachym Cepicky
  13. @author Martin Landa <landa.martin gmail.com>
  14. @author Vaclav Petras <wenzeslaus gmail.com> (MapFrameBase)
  15. @author Anna Kratochvilova <kratochanna gmail.com> (MapFrameBase)
  16. """
  17. import os
  18. import sys
  19. if __name__ == "__main__":
  20. sys.path.append(os.path.join(os.getenv('GISBASE'), 'etc', 'gui', 'wxpython'))
  21. from core import globalvar
  22. import wx
  23. from core import utils
  24. from core.giface import StandaloneGrassInterface
  25. from core.gcmd import RunCommand
  26. from core.render import Map
  27. from mapdisp.frame import MapFrame
  28. from grass.script import core as grass
  29. from core.debug import Debug
  30. from core.settings import UserSettings
  31. # for standalone app
  32. monFile = { 'cmd' : None,
  33. 'map' : None,
  34. 'env' : None,
  35. }
  36. monName = None
  37. monSize = list(globalvar.MAP_WINDOW_SIZE)
  38. class DMonMap(Map):
  39. def __init__(self, gisrc = None, cmdfile = None, mapfile = None, envfile = None, monitor = None):
  40. """!Map composition (stack of map layers and overlays)
  41. @param cmdline full path to the cmd file (defined by d.mon)
  42. @param mapfile full path to the map file (defined by d.mon)
  43. @param envfile full path to the env file (defined by d.mon)
  44. @param monitor name of monitor (defined by d.mon)
  45. """
  46. Map.__init__(self)
  47. # environment settings
  48. self.env = dict()
  49. self.cmdfile = cmdfile
  50. self.envfile = envfile
  51. self.monitor = monitor
  52. if mapfile:
  53. self.mapfileCmd = mapfile
  54. self.maskfileCmd = os.path.splitext(mapfile)[0] + '.pgm'
  55. # generated file for g.pnmcomp output for rendering the map
  56. self.mapfile = grass.tempfile(create = False) + '.ppm'
  57. self._writeEnvFile(self.env) # self.env is expected to be defined in parent class
  58. self._writeEnvFile({"GRASS_PNG_READ" : "TRUE"})
  59. def GetLayersFromCmdFile(self):
  60. """!Get list of map layers from cmdfile
  61. """
  62. if not self.cmdfile:
  63. return
  64. nlayers = 0
  65. try:
  66. fd = open(self.cmdfile, 'r')
  67. for line in fd.readlines():
  68. cmd = utils.split(line.strip())
  69. ltype = None
  70. if cmd[0] == 'd.rast':
  71. ltype = 'raster'
  72. elif cmd[0] == 'd.vect':
  73. ltype = 'vector'
  74. name = utils.GetLayerNameFromCmd(cmd, fullyQualified = True,
  75. layerType = ltype)[0]
  76. self.AddLayer(type = ltype, command = cmd, l_active = False, name = name)
  77. nlayers += 1
  78. except IOError, e:
  79. grass.warning(_("Unable to read cmdfile '%(cmd)s'. Details: %(det)s") % \
  80. { 'cmd' : self.cmdfile, 'det' : e })
  81. return
  82. fd.close()
  83. Debug.msg(1, "Map.GetLayersFromCmdFile(): cmdfile=%s" % self.cmdfile)
  84. Debug.msg(1, " nlayers=%d" % nlayers)
  85. def _parseCmdFile(self):
  86. """!Parse cmd file for standalone application
  87. """
  88. nlayers = 0
  89. try:
  90. fd = open(self.cmdfile, 'r')
  91. grass.try_remove(self.mapfile)
  92. cmdLines = fd.readlines()
  93. RunCommand('g.gisenv',
  94. set = 'MONITOR_%s_CMDFILE=' % self.monitor)
  95. for cmd in cmdLines:
  96. cmdStr = utils.split(cmd.strip())
  97. cmd = utils.CmdToTuple(cmdStr)
  98. RunCommand(cmd[0], **cmd[1])
  99. nlayers += 1
  100. RunCommand('g.gisenv',
  101. set = 'MONITOR_%s_CMDFILE=%s' % (self.monitor, self.cmdfile))
  102. except IOError, e:
  103. grass.warning(_("Unable to read cmdfile '%(cmd)s'. Details: %(det)s") % \
  104. { 'cmd' : self.cmdfile, 'det' : e })
  105. return
  106. fd.close()
  107. Debug.msg(1, "Map.__parseCmdFile(): cmdfile=%s" % self.cmdfile)
  108. Debug.msg(1, " nlayers=%d" % nlayers)
  109. return nlayers
  110. def _renderCmdFile(self, force, windres):
  111. if not force:
  112. return ([self.mapfileCmd],
  113. [self.maskfileCmd],
  114. ['1.0'])
  115. region = os.environ["GRASS_REGION"] = self.SetRegion(windres)
  116. self._writeEnvFile({'GRASS_REGION' : region})
  117. currMon = grass.gisenv()['MONITOR']
  118. if currMon != self.monitor:
  119. RunCommand('g.gisenv',
  120. set = 'MONITOR=%s' % self.monitor)
  121. grass.try_remove(self.mapfileCmd) # GRASS_PNG_READ is TRUE
  122. nlayers = self._parseCmdFile()
  123. if self.overlays:
  124. RunCommand('g.gisenv',
  125. unset = 'MONITOR') # GRASS_RENDER_IMMEDIATE doesn't like monitors
  126. driver = UserSettings.Get(group = 'display', key = 'driver', subkey = 'type')
  127. if driver == 'png':
  128. os.environ["GRASS_RENDER_IMMEDIATE"] = "png"
  129. else:
  130. os.environ["GRASS_RENDER_IMMEDIATE"] = "cairo"
  131. self._renderLayers(overlaysOnly = True)
  132. del os.environ["GRASS_RENDER_IMMEDIATE"]
  133. RunCommand('g.gisenv',
  134. set = 'MONITOR=%s' % currMon)
  135. if currMon != self.monitor:
  136. RunCommand('g.gisenv',
  137. set = 'MONITOR=%s' % currMon)
  138. if nlayers > 0:
  139. return ([self.mapfileCmd],
  140. [self.maskfileCmd],
  141. ['1.0'])
  142. else:
  143. return ([], [], [])
  144. def _writeEnvFile(self, data):
  145. """!Write display-related variable to the file (used for
  146. standalone app)
  147. """
  148. if not self.envfile:
  149. return
  150. try:
  151. fd = open(self.envfile, "r")
  152. for line in fd.readlines():
  153. key, value = line.split('=')
  154. if key not in data.keys():
  155. data[key] = value
  156. fd.close()
  157. fd = open(self.envfile, "w")
  158. for k, v in data.iteritems():
  159. fd.write('%s=%s\n' % (k.strip(), str(v).strip()))
  160. except IOError, e:
  161. grass.warning(_("Unable to open file '%(file)s' for writting. Details: %(det)s") % \
  162. { 'cmd' : self.envfile, 'det' : e })
  163. return
  164. fd.close()
  165. def ChangeMapSize(self, (width, height)):
  166. """!Change size of rendered map.
  167. @param width,height map size
  168. """
  169. Map.ChangeMapSize(self, (width, height))
  170. self._writeEnvFile({'GRASS_WIDTH' : self.width,
  171. 'GRASS_HEIGHT' : self.height})
  172. def GetMapsMasksAndOpacities(self, force, guiFrame, windres):
  173. """!
  174. Used by Render function.
  175. @return maps, masks, opacities
  176. """
  177. return self._renderCmdFile(force, windres)
  178. class DMonFrame(MapFrame):
  179. def OnZoomToMap(self, event):
  180. layers = self.MapWindow.GetMap().GetListOfLayers()
  181. self.MapWindow.ZoomToMap(layers = layers)
  182. class MapApp(wx.App):
  183. def OnInit(self):
  184. wx.InitAllImageHandlers()
  185. if __name__ == "__main__":
  186. self.cmdTimeStamp = os.path.getmtime(monFile['cmd'])
  187. self.Map = DMonMap(cmdfile = monFile['cmd'], mapfile = monFile['map'],
  188. envfile = monFile['env'], monitor = monName)
  189. else:
  190. self.Map = None
  191. # actual use of StandaloneGrassInterface not yet tested
  192. # needed for adding functionality in future
  193. self.mapFrm = DMonFrame(parent = None, id = wx.ID_ANY, Map = self.Map,
  194. giface = StandaloneGrassInterface(),
  195. size = monSize)
  196. # self.SetTopWindow(Map)
  197. self.mapFrm.GetMapWindow().SetAlwaysRenderEnabled(True)
  198. self.mapFrm.Show()
  199. if __name__ == "__main__":
  200. self.timer = wx.PyTimer(self.watcher)
  201. #check each 0.5s
  202. global mtime
  203. mtime = 500
  204. self.timer.Start(mtime)
  205. return True
  206. def OnExit(self):
  207. if __name__ == "__main__":
  208. # stop the timer
  209. # self.timer.Stop()
  210. # terminate thread
  211. for f in monFile.itervalues():
  212. grass.try_remove(f)
  213. def watcher(self):
  214. """!Redraw, if new layer appears (check's timestamp of
  215. cmdfile)
  216. """
  217. try:
  218. # GISBASE and other sytem enviromental variables can not be used
  219. # since the process inherited them from GRASS
  220. # raises exception when vaiable does not exists
  221. grass.gisenv()['GISDBASE']
  222. except KeyError:
  223. self.timer.Stop()
  224. return
  225. # todo: events
  226. try:
  227. currentCmdFileTime = os.path.getmtime(monFile['cmd'])
  228. if currentCmdFileTime > self.cmdTimeStamp:
  229. self.timer.Stop()
  230. self.cmdTimeStamp = currentCmdFileTime
  231. self.mapFrm.OnDraw(None)
  232. self.mapFrm.GetMap().GetLayersFromCmdFile()
  233. self.timer.Start(mtime)
  234. except OSError, e:
  235. grass.warning("%s" % e)
  236. self.timer.Stop()
  237. if __name__ == "__main__":
  238. # set command variable
  239. if len(sys.argv) < 5:
  240. print __doc__
  241. sys.exit(1)
  242. monName = sys.argv[1]
  243. monFile = { 'map' : sys.argv[2],
  244. 'cmd' : sys.argv[3],
  245. 'env' : sys.argv[4],
  246. }
  247. if len(sys.argv) >= 6:
  248. try:
  249. monSize[0] = int(sys.argv[5])
  250. except ValueError:
  251. pass
  252. if len(sys.argv) == 7:
  253. try:
  254. monSize[1] = int(sys.argv[6])
  255. except ValueError:
  256. pass
  257. import gettext
  258. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  259. grass.verbose(_("Starting map display <%s>...") % (monName))
  260. RunCommand('g.gisenv',
  261. set = 'MONITOR_%s_PID=%d' % (monName, os.getpid()))
  262. gmMap = MapApp(0)
  263. # set title
  264. gmMap.mapFrm.SetTitle(_("GRASS GIS Map Display: " +
  265. monName +
  266. " - Location: " + grass.gisenv()["LOCATION_NAME"]))
  267. gmMap.MainLoop()
  268. grass.verbose(_("Stopping map display <%s>...") % (monName))
  269. # clean up GRASS env variables
  270. env = grass.gisenv()
  271. env_name = 'MONITOR_%s' % monName
  272. for key in env.keys():
  273. if key.find(env_name) == 0:
  274. RunCommand('g.gisenv',
  275. unset = '%s' % key)
  276. if key == 'MONITOR' and env[key] == monName:
  277. RunCommand('g.gisenv',
  278. unset = '%s' % key)
  279. sys.exit(0)