render_cmd.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. #!/usr/bin/env python3
  2. import os
  3. import sys
  4. import tempfile
  5. from grass.script import core as grass
  6. from grass.script import task as gtask
  7. # read environment variables from file
  8. def read_env_file(env_file):
  9. width = height = legfile = None
  10. fd = open(env_file, 'r')
  11. if fd is None:
  12. grass.fatal("Unable to open file '{0}'".format(env_file))
  13. lines = fd.readlines()
  14. for l in lines:
  15. if l.startswith('#'):
  16. continue
  17. k, v = l.rstrip('\n').split('#', 1)[0].strip().split('=', 1)
  18. os.environ[k] = v
  19. if width is None and k == 'GRASS_RENDER_WIDTH':
  20. width = int(v)
  21. if height is None and k == 'GRASS_RENDER_HEIGHT':
  22. height = int(v)
  23. if legfile is None and k == 'GRASS_LEGEND_FILE':
  24. legfile = v
  25. fd.close()
  26. if width is None or height is None:
  27. grass.fatal("Unknown monitor size")
  28. return width, height, legfile
  29. # run display command
  30. def render(cmd, mapfile):
  31. env = os.environ.copy()
  32. if mapfile:
  33. env['GRASS_RENDER_FILE'] = mapfile
  34. try:
  35. grass.run_command(cmd[0], env=env, **cmd[1])
  36. except Exception as e:
  37. grass.debug(1, "Unable to render: {0}".format(e))
  38. # update cmd file
  39. def update_cmd_file(cmd_file, cmd, mapfile):
  40. if cmd[0] in ('d.colorlist', 'd.font', 'd.fontlist',
  41. 'd.frame', 'd.info', 'd.mon', 'd.out.file',
  42. 'd.redraw', 'd.to.rast', 'd.what.rast',
  43. 'd.what.vect', 'd.where'):
  44. return
  45. mode = 'w' if cmd[0] == 'd.erase' else 'a'
  46. # update cmd file
  47. fd = open(cmd_file, mode)
  48. if fd is None:
  49. grass.fatal("Unable to open file '{0}'".format(cmd_file))
  50. if mode == 'a':
  51. frame = os.getenv('GRASS_RENDER_FRAME', None)
  52. if frame:
  53. fd.write('# GRASS_RENDER_FRAME={0}\n'.format(frame))
  54. if mapfile:
  55. fd.write('# GRASS_RENDER_FILE={0}\n'.format(mapfile))
  56. fd.write(' '.join(gtask.cmdtuple_to_list(cmd)))
  57. fd.write('\n')
  58. else:
  59. fd.write('')
  60. fd.close()
  61. # adjust region
  62. def adjust_region(width, height):
  63. region = grass.region()
  64. mapwidth = abs(region["e"] - region["w"])
  65. mapheight = abs(region['n'] - region['s'])
  66. region["nsres"] = mapheight / height
  67. region["ewres"] = mapwidth / width
  68. region['rows'] = int(round(mapheight / region["nsres"]))
  69. region['cols'] = int(round(mapwidth / region["ewres"]))
  70. region['cells'] = region['rows'] * region['cols']
  71. kwdata = [('proj', 'projection'),
  72. ('zone', 'zone'),
  73. ('north', 'n'),
  74. ('south', 's'),
  75. ('east', 'e'),
  76. ('west', 'w'),
  77. ('cols', 'cols'),
  78. ('rows', 'rows'),
  79. ('e-w resol', 'ewres'),
  80. ('n-s resol', 'nsres')]
  81. grass_region = ''
  82. for wkey, rkey in kwdata:
  83. grass_region += '%s: %s;' % (wkey, region[rkey])
  84. os.environ['GRASS_REGION'] = grass_region
  85. # read any input from stdin and create a temporary file
  86. def read_stdin(cmd):
  87. opt = None
  88. if (cmd[0] == 'd.text' and not 'text' in cmd[1] and
  89. (not 'input' in cmd[1] or cmd[1]['input'] == '-')):
  90. if sys.stdin.isatty():
  91. sys.stderr.write("\nPlease enter text instructions. Enter EOF (ctrl-d) on last line to quit\n")
  92. opt = 'input'
  93. if opt:
  94. tmpfile = tempfile.NamedTemporaryFile(dir=path).name + '.txt'
  95. fd = open(tmpfile, 'w')
  96. while 1:
  97. line = sys.stdin.readline()
  98. if not line:
  99. break
  100. fd.write(line)
  101. fd.close()
  102. cmd[1][opt] = tmpfile
  103. if __name__ == "__main__":
  104. cmd = gtask.cmdstring_to_tuple(sys.argv[1])
  105. if not cmd[0] or cmd[0] == 'd.mon':
  106. sys.exit(0)
  107. path = os.path.dirname(os.path.abspath(__file__))
  108. mon = os.path.split(path)[-1]
  109. width, height, legfile = read_env_file(os.path.join(path, 'env'))
  110. if mon.startswith('wx'):
  111. mapfile = tempfile.NamedTemporaryFile(dir=path).name
  112. if cmd[0] in ('d.barscale', 'd.legend', 'd.northarrow', 'd.legend.vect'):
  113. mapfile += '.png'
  114. else:
  115. mapfile += '.ppm'
  116. else:
  117. mapfile = None
  118. adjust_region(width, height)
  119. read_stdin(cmd)
  120. render(cmd, mapfile)
  121. update_cmd_file(os.path.join(path, 'cmd'), cmd, mapfile)
  122. if cmd[0] == 'd.erase' and os.path.exists(legfile):
  123. os.remove(legfile)
  124. sys.exit(0)