main.py 11 KB

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