main.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. try:
  71. ltype = utils.command2ltype[cmd[0]]
  72. except KeyError:
  73. grass.warning(_("Unsupported command %s.") % cmd[0])
  74. continue
  75. name = utils.GetLayerNameFromCmd(cmd, fullyQualified = True,
  76. layerType = ltype)[0]
  77. self.AddLayer(ltype = ltype, command = cmd, active = False, name = name)
  78. nlayers += 1
  79. except IOError, e:
  80. grass.warning(_("Unable to read cmdfile '%(cmd)s'. Details: %(det)s") % \
  81. { 'cmd' : self.cmdfile, 'det' : e })
  82. return
  83. fd.close()
  84. Debug.msg(1, "Map.GetLayersFromCmdFile(): cmdfile=%s" % self.cmdfile)
  85. Debug.msg(1, " nlayers=%d" % nlayers)
  86. def _parseCmdFile(self):
  87. """!Parse cmd file for standalone application
  88. """
  89. nlayers = 0
  90. try:
  91. fd = open(self.cmdfile, 'r')
  92. grass.try_remove(self.mapfile)
  93. cmdLines = fd.readlines()
  94. RunCommand('g.gisenv',
  95. set = 'MONITOR_%s_CMDFILE=' % self.monitor)
  96. for cmd in cmdLines:
  97. cmdStr = utils.split(cmd.strip())
  98. cmd = utils.CmdToTuple(cmdStr)
  99. RunCommand(cmd[0], **cmd[1])
  100. nlayers += 1
  101. RunCommand('g.gisenv',
  102. set = 'MONITOR_%s_CMDFILE=%s' % (self.monitor, self.cmdfile))
  103. except IOError, e:
  104. grass.warning(_("Unable to read cmdfile '%(cmd)s'. Details: %(det)s") % \
  105. { 'cmd' : self.cmdfile, 'det' : e })
  106. return
  107. fd.close()
  108. Debug.msg(1, "Map.__parseCmdFile(): cmdfile=%s" % self.cmdfile)
  109. Debug.msg(1, " nlayers=%d" % nlayers)
  110. return nlayers
  111. def _renderCmdFile(self, force, windres):
  112. if not force:
  113. return ([self.mapfileCmd],
  114. [self.maskfileCmd],
  115. ['1.0'])
  116. region = os.environ["GRASS_REGION"] = self.SetRegion(windres)
  117. self._writeEnvFile({'GRASS_REGION' : region})
  118. currMon = grass.gisenv()['MONITOR']
  119. if currMon != self.monitor:
  120. RunCommand('g.gisenv',
  121. set = 'MONITOR=%s' % self.monitor)
  122. grass.try_remove(self.mapfileCmd) # GRASS_PNG_READ is TRUE
  123. nlayers = self._parseCmdFile()
  124. if self.overlays:
  125. RunCommand('g.gisenv',
  126. unset = 'MONITOR') # GRASS_RENDER_IMMEDIATE doesn't like monitors
  127. driver = UserSettings.Get(group = 'display', key = 'driver', subkey = 'type')
  128. if driver == 'png':
  129. os.environ["GRASS_RENDER_IMMEDIATE"] = "png"
  130. else:
  131. os.environ["GRASS_RENDER_IMMEDIATE"] = "cairo"
  132. self._renderLayers(overlaysOnly = True)
  133. del os.environ["GRASS_RENDER_IMMEDIATE"]
  134. RunCommand('g.gisenv',
  135. set = 'MONITOR=%s' % currMon)
  136. if currMon != self.monitor:
  137. RunCommand('g.gisenv',
  138. set = 'MONITOR=%s' % currMon)
  139. if nlayers > 0:
  140. return ([self.mapfileCmd],
  141. [self.maskfileCmd],
  142. ['1.0'])
  143. else:
  144. return ([], [], [])
  145. def _writeEnvFile(self, data):
  146. """!Write display-related variable to the file (used for
  147. standalone app)
  148. """
  149. if not self.envfile:
  150. return
  151. try:
  152. fd = open(self.envfile, "r")
  153. for line in fd.readlines():
  154. key, value = line.split('=')
  155. if key not in data.keys():
  156. data[key] = value
  157. fd.close()
  158. fd = open(self.envfile, "w")
  159. for k, v in data.iteritems():
  160. fd.write('%s=%s\n' % (k.strip(), str(v).strip()))
  161. except IOError, e:
  162. grass.warning(_("Unable to open file '%(file)s' for writting. Details: %(det)s") % \
  163. { 'cmd' : self.envfile, 'det' : e })
  164. return
  165. fd.close()
  166. def ChangeMapSize(self, (width, height)):
  167. """!Change size of rendered map.
  168. @param width,height map size
  169. """
  170. Map.ChangeMapSize(self, (width, height))
  171. self._writeEnvFile({'GRASS_WIDTH' : self.width,
  172. 'GRASS_HEIGHT' : self.height})
  173. def GetMapsMasksAndOpacities(self, force, windres):
  174. """!
  175. Used by Render function.
  176. @return maps, masks, opacities
  177. """
  178. return self._renderCmdFile(force, windres)
  179. class DMonFrame(MapFrame):
  180. def OnZoomToMap(self, event):
  181. layers = self.MapWindow.GetMap().GetListOfLayers()
  182. self.MapWindow.ZoomToMap(layers = layers)
  183. class MapApp(wx.App):
  184. def OnInit(self):
  185. wx.InitAllImageHandlers()
  186. if __name__ == "__main__":
  187. self.cmdTimeStamp = os.path.getmtime(monFile['cmd'])
  188. self.Map = DMonMap(cmdfile = monFile['cmd'], mapfile = monFile['map'],
  189. envfile = monFile['env'], monitor = monName)
  190. else:
  191. self.Map = None
  192. # actual use of StandaloneGrassInterface not yet tested
  193. # needed for adding functionality in future
  194. self.mapFrm = DMonFrame(parent = None, id = wx.ID_ANY, Map = self.Map,
  195. giface = StandaloneGrassInterface(),
  196. size = monSize)
  197. # self.SetTopWindow(Map)
  198. self.mapFrm.GetMapWindow().SetAlwaysRenderEnabled(True)
  199. self.mapFrm.Show()
  200. if __name__ == "__main__":
  201. self.timer = wx.PyTimer(self.watcher)
  202. #check each 0.5s
  203. global mtime
  204. mtime = 500
  205. self.timer.Start(mtime)
  206. return True
  207. def OnExit(self):
  208. if __name__ == "__main__":
  209. # stop the timer
  210. # self.timer.Stop()
  211. # terminate thread
  212. for f in monFile.itervalues():
  213. grass.try_remove(f)
  214. def watcher(self):
  215. """!Redraw, if new layer appears (check's timestamp of
  216. cmdfile)
  217. """
  218. try:
  219. # GISBASE and other sytem enviromental variables can not be used
  220. # since the process inherited them from GRASS
  221. # raises exception when vaiable does not exists
  222. grass.gisenv()['GISDBASE']
  223. except KeyError:
  224. self.timer.Stop()
  225. return
  226. # todo: events
  227. try:
  228. currentCmdFileTime = os.path.getmtime(monFile['cmd'])
  229. if currentCmdFileTime > self.cmdTimeStamp:
  230. self.timer.Stop()
  231. self.cmdTimeStamp = currentCmdFileTime
  232. self.mapFrm.OnDraw(None)
  233. self.mapFrm.GetMap().GetLayersFromCmdFile()
  234. self.timer.Start(mtime)
  235. except OSError, e:
  236. grass.warning("%s" % e)
  237. self.timer.Stop()
  238. def GetMapFrame(self):
  239. """!Get Map Frame instance"""
  240. return self.mapFrm
  241. if __name__ == "__main__":
  242. # set command variable
  243. if len(sys.argv) < 5:
  244. print __doc__
  245. sys.exit(1)
  246. monName = sys.argv[1]
  247. monFile = { 'map' : sys.argv[2],
  248. 'cmd' : sys.argv[3],
  249. 'env' : sys.argv[4],
  250. }
  251. if len(sys.argv) >= 6:
  252. try:
  253. monSize[0] = int(sys.argv[5])
  254. except ValueError:
  255. pass
  256. if len(sys.argv) == 7:
  257. try:
  258. monSize[1] = int(sys.argv[6])
  259. except ValueError:
  260. pass
  261. import gettext
  262. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  263. grass.verbose(_("Starting map display <%s>...") % (monName))
  264. RunCommand('g.gisenv',
  265. set = 'MONITOR_%s_PID=%d' % (monName, os.getpid()))
  266. gmMap = MapApp(0)
  267. # set title
  268. gmMap.mapFrm.SetTitle(_("GRASS GIS Map Display: " +
  269. monName +
  270. " - Location: " + grass.gisenv()["LOCATION_NAME"]))
  271. gmMap.MainLoop()
  272. grass.verbose(_("Stopping map display <%s>...") % (monName))
  273. # clean up GRASS env variables
  274. env = grass.gisenv()
  275. env_name = 'MONITOR_%s' % monName
  276. for key in env.keys():
  277. if key.find(env_name) == 0:
  278. RunCommand('g.gisenv',
  279. unset = '%s' % key)
  280. if key == 'MONITOR' and env[key] == monName:
  281. RunCommand('g.gisenv',
  282. unset = '%s' % key)
  283. sys.exit(0)