main.py 11 KB

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