utils.py 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201
  1. """
  2. @package core.utils
  3. @brief Misc utilities for wxGUI
  4. (C) 2007-2015 by the GRASS Development Team
  5. This program is free software under the GNU General Public License
  6. (>=v2). Read the file COPYING that comes with GRASS for details.
  7. @author Martin Landa <landa.martin gmail.com>
  8. @author Jachym Cepicky
  9. """
  10. import os
  11. import sys
  12. import platform
  13. import glob
  14. import shlex
  15. import re
  16. import inspect
  17. import six
  18. from grass.script import core as grass
  19. from grass.script import task as gtask
  20. from core.gcmd import RunCommand
  21. from core.debug import Debug
  22. from core.globalvar import ETCDIR, wxPythonPhoenix
  23. def cmp(a, b):
  24. """cmp function"""
  25. return ((a > b) - (a < b))
  26. def normalize_whitespace(text):
  27. """Remove redundant whitespace from a string"""
  28. return (' ').join(text.split())
  29. def split(s):
  30. """Platform spefic shlex.split"""
  31. try:
  32. if sys.platform == "win32":
  33. return shlex.split(s.replace('\\', r'\\'))
  34. else:
  35. return shlex.split(s)
  36. except ValueError as e:
  37. sys.stderr.write(_("Syntax error: %s") % e)
  38. return []
  39. def GetTempfile(pref=None):
  40. """Creates GRASS temporary file using defined prefix.
  41. .. todo::
  42. Fix path on MS Windows/MSYS
  43. :param pref: prefer the given path
  44. :return: Path to file name (string) or None
  45. """
  46. ret = RunCommand('g.tempfile',
  47. read=True,
  48. pid=os.getpid())
  49. tempfile = ret.splitlines()[0].strip()
  50. # FIXME
  51. # ugly hack for MSYS (MS Windows)
  52. if platform.system() == 'Windows':
  53. tempfile = tempfile.replace("/", "\\")
  54. try:
  55. path, file = os.path.split(tempfile)
  56. if pref:
  57. return os.path.join(pref, file)
  58. else:
  59. return tempfile
  60. except:
  61. return None
  62. def GetLayerNameFromCmd(dcmd, fullyQualified=False, param=None,
  63. layerType=None):
  64. """Get map name from GRASS command
  65. Parameter dcmd can be modified when first parameter is not
  66. defined.
  67. :param dcmd: GRASS command (given as list)
  68. :param fullyQualified: change map name to be fully qualified
  69. :param param: params directory
  70. :param str layerType: check also layer type ('raster', 'vector',
  71. 'raster_3d', ...)
  72. :return: tuple (name, found)
  73. """
  74. mapname = ''
  75. found = True
  76. if len(dcmd) < 1:
  77. return mapname, False
  78. if 'd.grid' == dcmd[0]:
  79. mapname = 'grid'
  80. elif 'd.geodesic' in dcmd[0]:
  81. mapname = 'geodesic'
  82. elif 'd.rhumbline' in dcmd[0]:
  83. mapname = 'rhumb'
  84. elif 'd.graph' in dcmd[0]:
  85. mapname = 'graph'
  86. else:
  87. params = list()
  88. for idx in range(len(dcmd)):
  89. try:
  90. p, v = dcmd[idx].split('=', 1)
  91. except ValueError:
  92. continue
  93. if p == param:
  94. params = [(idx, p, v)]
  95. break
  96. # this does not use types, just some (incomplete subset of?) names
  97. if p in ('map', 'input', 'layer',
  98. 'red', 'blue', 'green',
  99. 'hue', 'saturation', 'intensity',
  100. 'shade', 'labels'):
  101. params.append((idx, p, v))
  102. if len(params) < 1:
  103. if len(dcmd) > 1:
  104. i = 1
  105. while i < len(dcmd):
  106. if '=' not in dcmd[i] and not dcmd[i].startswith('-'):
  107. task = gtask.parse_interface(dcmd[0])
  108. # this expects the first parameter to be the right one
  109. p = task.get_options()['params'][0].get('name', '')
  110. params.append((i, p, dcmd[i]))
  111. break
  112. i += 1
  113. else:
  114. return mapname, False
  115. if len(params) < 1:
  116. return mapname, False
  117. # need to add mapset for all maps
  118. mapsets = {}
  119. for i, p, v in params:
  120. if p == 'layer':
  121. continue
  122. mapname = v
  123. mapset = ''
  124. if fullyQualified and '@' not in mapname:
  125. if layerType in ('raster', 'vector',
  126. 'raster_3d', 'rgb', 'his'):
  127. try:
  128. if layerType in ('raster', 'rgb', 'his'):
  129. findType = 'cell'
  130. elif layerType == 'raster_3d':
  131. findType = 'grid3'
  132. else:
  133. findType = layerType
  134. mapset = grass.find_file(
  135. mapname, element=findType)['mapset']
  136. except AttributeError: # not found
  137. return '', False
  138. if not mapset:
  139. found = False
  140. else:
  141. mapset = '' # grass.gisenv()['MAPSET']
  142. mapsets[i] = mapset
  143. # update dcmd
  144. for i, p, v in params:
  145. if p == 'layer':
  146. continue
  147. dcmd[i] = p + '=' + v
  148. if i in mapsets and mapsets[i]:
  149. dcmd[i] += '@' + mapsets[i]
  150. maps = list()
  151. ogr = False
  152. for i, p, v in params:
  153. if v.lower().rfind('@ogr') > -1:
  154. ogr = True
  155. if p == 'layer' and not ogr:
  156. continue
  157. maps.append(dcmd[i].split('=', 1)[1])
  158. mapname = '\n'.join(maps)
  159. return mapname, found
  160. def GetValidLayerName(name):
  161. """Make layer name SQL compliant, based on G_str_to_sql()
  162. .. todo::
  163. Better use directly Ctypes to reuse venerable libgis C fns...
  164. """
  165. retName = name.strip()
  166. # check if name is fully qualified
  167. if '@' in retName:
  168. retName, mapset = retName.split('@')
  169. else:
  170. mapset = None
  171. cIdx = 0
  172. retNameList = list(retName)
  173. for c in retNameList:
  174. if not (c >= 'A' and c <= 'Z') and \
  175. not (c >= 'a' and c <= 'z') and \
  176. not (c >= '0' and c <= '9'):
  177. retNameList[cIdx] = '_'
  178. cIdx += 1
  179. retName = ''.join(retNameList)
  180. if not (retName[0] >= 'A' and retName[0] <= 'Z') and \
  181. not (retName[0] >= 'a' and retName[0] <= 'z'):
  182. retName = 'x' + retName[1:]
  183. if mapset:
  184. retName = retName + '@' + mapset
  185. return retName
  186. def ListOfCatsToRange(cats):
  187. """Convert list of category number to range(s)
  188. Used for example for d.vect cats=[range]
  189. :param cats: category list
  190. :return: category range string
  191. :return: '' on error
  192. """
  193. catstr = ''
  194. try:
  195. cats = list(map(int, cats))
  196. except:
  197. return catstr
  198. i = 0
  199. while i < len(cats):
  200. next = 0
  201. j = i + 1
  202. while j < len(cats):
  203. if cats[i + next] == cats[j] - 1:
  204. next += 1
  205. else:
  206. break
  207. j += 1
  208. if next > 1:
  209. catstr += '%d-%d,' % (cats[i], cats[i + next])
  210. i += next + 1
  211. else:
  212. catstr += '%d,' % (cats[i])
  213. i += 1
  214. return catstr.strip(',')
  215. def ListOfMapsets(get='ordered'):
  216. """Get list of available/accessible mapsets
  217. :param str get: method ('all', 'accessible', 'ordered')
  218. :return: list of mapsets
  219. :return: None on error
  220. """
  221. mapsets = []
  222. if get == 'all' or get == 'ordered':
  223. ret = RunCommand('g.mapsets',
  224. read=True,
  225. quiet=True,
  226. flags='l',
  227. sep='newline')
  228. if ret:
  229. mapsets = ret.splitlines()
  230. ListSortLower(mapsets)
  231. else:
  232. return None
  233. if get == 'accessible' or get == 'ordered':
  234. ret = RunCommand('g.mapsets',
  235. read=True,
  236. quiet=True,
  237. flags='p',
  238. sep='newline')
  239. if ret:
  240. if get == 'accessible':
  241. mapsets = ret.splitlines()
  242. else:
  243. mapsets_accessible = ret.splitlines()
  244. for mapset in mapsets_accessible:
  245. mapsets.remove(mapset)
  246. mapsets = mapsets_accessible + mapsets
  247. else:
  248. return None
  249. return mapsets
  250. def ListSortLower(list):
  251. """Sort list items (not case-sensitive)"""
  252. list.sort(key=lambda x: x.lower())
  253. def GetVectorNumberOfLayers(vector):
  254. """Get list of all vector layers"""
  255. layers = list()
  256. if not vector:
  257. return layers
  258. fullname = grass.find_file(name=vector, element='vector')['fullname']
  259. if not fullname:
  260. Debug.msg(
  261. 5,
  262. "utils.GetVectorNumberOfLayers(): vector map '%s' not found" %
  263. vector)
  264. return layers
  265. ret, out, msg = RunCommand('v.category',
  266. getErrorMsg=True,
  267. read=True,
  268. input=fullname,
  269. option='layers')
  270. if ret != 0:
  271. sys.stderr.write(
  272. _("Vector map <%(map)s>: %(msg)s\n") %
  273. {'map': fullname, 'msg': msg})
  274. return layers
  275. else:
  276. Debug.msg(1, "GetVectorNumberOfLayers(): ret %s" % ret)
  277. for layer in out.splitlines():
  278. layers.append(layer)
  279. Debug.msg(3, "utils.GetVectorNumberOfLayers(): vector=%s -> %s" %
  280. (fullname, ','.join(layers)))
  281. return layers
  282. def Deg2DMS(lon, lat, string=True, hemisphere=True, precision=3):
  283. """Convert deg value to dms string
  284. :param lon: longitude (x)
  285. :param lat: latitude (y)
  286. :param string: True to return string otherwise tuple
  287. :param hemisphere: print hemisphere
  288. :param precision: seconds precision
  289. :return: DMS string or tuple of values
  290. :return: empty string on error
  291. """
  292. try:
  293. flat = float(lat)
  294. flon = float(lon)
  295. except ValueError:
  296. if string:
  297. return ''
  298. else:
  299. return None
  300. # fix longitude
  301. while flon > 180.0:
  302. flon -= 360.0
  303. while flon < -180.0:
  304. flon += 360.0
  305. # hemisphere
  306. if hemisphere:
  307. if flat < 0.0:
  308. flat = abs(flat)
  309. hlat = 'S'
  310. else:
  311. hlat = 'N'
  312. if flon < 0.0:
  313. hlon = 'W'
  314. flon = abs(flon)
  315. else:
  316. hlon = 'E'
  317. else:
  318. flat = abs(flat)
  319. flon = abs(flon)
  320. hlon = ''
  321. hlat = ''
  322. slat = __ll_parts(flat, precision=precision)
  323. slon = __ll_parts(flon, precision=precision)
  324. if string:
  325. return slon + hlon + '; ' + slat + hlat
  326. return (slon + hlon, slat + hlat)
  327. def DMS2Deg(lon, lat):
  328. """Convert dms value to deg
  329. :param lon: longitude (x)
  330. :param lat: latitude (y)
  331. :return: tuple of converted values
  332. :return: ValueError on error
  333. """
  334. x = __ll_parts(lon, reverse=True)
  335. y = __ll_parts(lat, reverse=True)
  336. return (x, y)
  337. def __ll_parts(value, reverse=False, precision=3):
  338. """Converts deg to d:m:s string
  339. :param value: value to be converted
  340. :param reverse: True to convert from d:m:s to deg
  341. :param precision: seconds precision (ignored if reverse is True)
  342. :return: converted value (string/float)
  343. :return: ValueError on error (reverse == True)
  344. """
  345. if not reverse:
  346. if value == 0.0:
  347. return '%s%.*f' % ('00:00:0', precision, 0.0)
  348. d = int(int(value))
  349. m = int((value - d) * 60)
  350. s = ((value - d) * 60 - m) * 60
  351. if m < 0:
  352. m = '00'
  353. elif m < 10:
  354. m = '0' + str(m)
  355. else:
  356. m = str(m)
  357. if s < 0:
  358. s = '00.0000'
  359. elif s < 10.0:
  360. s = '0%.*f' % (precision, s)
  361. else:
  362. s = '%.*f' % (precision, s)
  363. return str(d) + ':' + m + ':' + s
  364. else: # -> reverse
  365. try:
  366. d, m, s = value.split(':')
  367. hs = s[-1]
  368. s = s[:-1]
  369. except ValueError:
  370. try:
  371. d, m = value.split(':')
  372. hs = m[-1]
  373. m = m[:-1]
  374. s = '0.0'
  375. except ValueError:
  376. try:
  377. d = value
  378. hs = d[-1]
  379. d = d[:-1]
  380. m = '0'
  381. s = '0.0'
  382. except ValueError:
  383. raise ValueError
  384. if hs not in ('N', 'S', 'E', 'W'):
  385. raise ValueError
  386. coef = 1.0
  387. if hs in ('S', 'W'):
  388. coef = -1.0
  389. fm = int(m) / 60.0
  390. fs = float(s) / (60 * 60)
  391. return coef * (float(d) + fm + fs)
  392. def GetCmdString(cmd):
  393. """Get GRASS command as string.
  394. :param cmd: GRASS command given as tuple
  395. :return: command string
  396. """
  397. return ' '.join(gtask.cmdtuple_to_list(cmd))
  398. def PathJoin(*args):
  399. """Check path created by os.path.join"""
  400. path = os.path.join(*args)
  401. if platform.system() == 'Windows' and \
  402. '/' in path:
  403. return path[1].upper() + ':\\' + path[3:].replace('/', '\\')
  404. return path
  405. def ReadEpsgCodes():
  406. """Read EPSG codes with g.proj
  407. :return: dictionary of EPSG code
  408. """
  409. epsgCodeDict = dict()
  410. ret = RunCommand('g.proj',
  411. read=True,
  412. list_codes="EPSG")
  413. for line in ret.splitlines():
  414. code, descr, params = line.split("|")
  415. epsgCodeDict[int(code)] = (descr, params)
  416. return epsgCodeDict
  417. def ReprojectCoordinates(coord, projOut, projIn=None, flags=''):
  418. """Reproject coordinates
  419. :param coord: coordinates given as tuple
  420. :param projOut: output projection
  421. :param projIn: input projection (use location projection settings)
  422. :return: reprojected coordinates (returned as tuple)
  423. """
  424. coors = RunCommand('m.proj',
  425. flags=flags,
  426. input='-',
  427. proj_in=projIn,
  428. proj_out=projOut,
  429. sep=';',
  430. stdin='%f;%f' % (coord[0], coord[1]),
  431. read=True)
  432. if coors:
  433. coors = coors.split(';')
  434. e = coors[0]
  435. n = coors[1]
  436. try:
  437. proj = projOut.split(' ')[0].split('=')[1]
  438. except IndexError:
  439. proj = ''
  440. if proj in ('ll', 'latlong', 'longlat') and 'd' not in flags:
  441. return (proj, (e, n))
  442. else:
  443. try:
  444. return (proj, (float(e), float(n)))
  445. except ValueError:
  446. return (None, None)
  447. return (None, None)
  448. def GetListOfLocations(dbase):
  449. """Get list of GRASS locations in given dbase
  450. :param dbase: GRASS database path
  451. :return: list of locations (sorted)
  452. """
  453. listOfLocations = list()
  454. try:
  455. for location in glob.glob(os.path.join(dbase, "*")):
  456. try:
  457. if os.path.join(
  458. location, "PERMANENT") in glob.glob(
  459. os.path.join(location, "*")):
  460. listOfLocations.append(os.path.basename(location))
  461. except:
  462. pass
  463. except (UnicodeEncodeError, UnicodeDecodeError) as e:
  464. raise e
  465. ListSortLower(listOfLocations)
  466. return listOfLocations
  467. def GetListOfMapsets(dbase, location, selectable=False):
  468. """Get list of mapsets in given GRASS location
  469. :param dbase: GRASS database path
  470. :param location: GRASS location
  471. :param selectable: True to get list of selectable mapsets, otherwise all
  472. :return: list of mapsets - sorted (PERMANENT first)
  473. """
  474. listOfMapsets = list()
  475. if selectable:
  476. ret = RunCommand('g.mapset',
  477. read=True,
  478. flags='l',
  479. location=location,
  480. dbase=dbase)
  481. if not ret:
  482. return listOfMapsets
  483. for line in ret.rstrip().splitlines():
  484. listOfMapsets += line.split(' ')
  485. else:
  486. for mapset in glob.glob(os.path.join(dbase, location, "*")):
  487. if os.path.isdir(mapset) and os.path.isfile(
  488. os.path.join(dbase, location, mapset, "WIND")):
  489. listOfMapsets.append(os.path.basename(mapset))
  490. ListSortLower(listOfMapsets)
  491. return listOfMapsets
  492. def GetColorTables():
  493. """Get list of color tables"""
  494. ret = RunCommand('r.colors',
  495. read=True,
  496. flags='l')
  497. if not ret:
  498. return list()
  499. return ret.splitlines()
  500. def _getGDALFormats():
  501. """Get dictionary of available GDAL drivers"""
  502. try:
  503. ret = grass.read_command('r.in.gdal',
  504. quiet=True,
  505. flags='f')
  506. except:
  507. ret = None
  508. return _parseFormats(ret), _parseFormats(ret, writableOnly=True)
  509. def _getOGRFormats():
  510. """Get dictionary of available OGR drivers"""
  511. try:
  512. ret = grass.read_command('v.in.ogr',
  513. quiet=True,
  514. flags='f')
  515. except:
  516. ret = None
  517. return _parseFormats(ret), _parseFormats(ret, writableOnly=True)
  518. def _parseFormats(output, writableOnly=False):
  519. """Parse r.in.gdal/v.in.ogr -f output"""
  520. formats = {'file': list(),
  521. 'database': list(),
  522. 'protocol': list()
  523. }
  524. if not output:
  525. return formats
  526. patt = None
  527. if writableOnly:
  528. patt = re.compile('\(rw\+?\)$', re.IGNORECASE)
  529. for line in output.splitlines():
  530. key, name = map(lambda x: x.strip(), line.strip().split(':', 1))
  531. if writableOnly and not patt.search(key):
  532. continue
  533. if name in ('Memory', 'Virtual Raster', 'In Memory Raster'):
  534. continue
  535. if name in ('PostgreSQL', 'SQLite',
  536. 'ODBC', 'ESRI Personal GeoDatabase',
  537. 'Rasterlite',
  538. 'PostGIS WKT Raster driver',
  539. 'PostGIS Raster driver',
  540. 'CouchDB',
  541. 'MSSQLSpatial',
  542. 'FileGDB'):
  543. formats['database'].append(name)
  544. elif name in ('GeoJSON',
  545. 'OGC Web Coverage Service',
  546. 'OGC Web Map Service',
  547. 'WFS',
  548. 'GeoRSS',
  549. 'HTTP Fetching Wrapper'):
  550. formats['protocol'].append(name)
  551. else:
  552. formats['file'].append(name)
  553. for items in six.itervalues(formats):
  554. items.sort()
  555. return formats
  556. formats = None
  557. def GetFormats(writableOnly=False):
  558. """Get GDAL/OGR formats"""
  559. global formats
  560. if not formats:
  561. gdalAll, gdalWritable = _getGDALFormats()
  562. ogrAll, ogrWritable = _getOGRFormats()
  563. formats = {
  564. 'all': {
  565. 'gdal': gdalAll,
  566. 'ogr': ogrAll,
  567. },
  568. 'writable': {
  569. 'gdal': gdalWritable,
  570. 'ogr': ogrWritable,
  571. },
  572. }
  573. if writableOnly:
  574. return formats['writable']
  575. return formats['all']
  576. rasterFormatExtension = {
  577. 'GeoTIFF': 'tif',
  578. 'Erdas Imagine Images (.img)': 'img',
  579. 'Ground-based SAR Applications Testbed File Format (.gff)': 'gff',
  580. 'Arc/Info Binary Grid': 'adf',
  581. 'Portable Network Graphics': 'png',
  582. 'JPEG JFIF': 'jpg',
  583. 'Japanese DEM (.mem)': 'mem',
  584. 'Graphics Interchange Format (.gif)': 'gif',
  585. 'X11 PixMap Format': 'xpm',
  586. 'MS Windows Device Independent Bitmap': 'bmp',
  587. 'SPOT DIMAP': 'dim',
  588. 'RadarSat 2 XML Product': 'xml',
  589. 'EarthWatch .TIL': 'til',
  590. 'ERMapper .ers Labelled': 'ers',
  591. 'ERMapper Compressed Wavelets': 'ecw',
  592. 'GRIdded Binary (.grb)': 'grb',
  593. 'EUMETSAT Archive native (.nat)': 'nat',
  594. 'Idrisi Raster A.1': 'rst',
  595. 'Golden Software ASCII Grid (.grd)': 'grd',
  596. 'Golden Software Binary Grid (.grd)': 'grd',
  597. 'Golden Software 7 Binary Grid (.grd)': 'grd',
  598. 'R Object Data Store': 'r',
  599. 'USGS DOQ (Old Style)': 'doq',
  600. 'USGS DOQ (New Style)': 'doq',
  601. 'ENVI .hdr Labelled': 'hdr',
  602. 'ESRI .hdr Labelled': 'hdr',
  603. 'Generic Binary (.hdr Labelled)': 'hdr',
  604. 'PCI .aux Labelled': 'aux',
  605. 'EOSAT FAST Format': 'fst',
  606. 'VTP .bt (Binary Terrain) 1.3 Format': 'bt',
  607. 'FARSITE v.4 Landscape File (.lcp)': 'lcp',
  608. 'Swedish Grid RIK (.rik)': 'rik',
  609. 'USGS Optional ASCII DEM (and CDED)': 'dem',
  610. 'Northwood Numeric Grid Format .grd/.tab': '',
  611. 'Northwood Classified Grid Format .grc/.tab': '',
  612. 'ARC Digitized Raster Graphics': 'arc',
  613. 'Magellan topo (.blx)': 'blx',
  614. 'SAGA GIS Binary Grid (.sdat)': 'sdat',
  615. 'GeoPackage (.gpkg)': 'gpkg'
  616. }
  617. vectorFormatExtension = {
  618. 'ESRI Shapefile': 'shp',
  619. 'GeoPackage': 'gpkg',
  620. 'UK .NTF': 'ntf',
  621. 'SDTS': 'ddf',
  622. 'DGN': 'dgn',
  623. 'VRT': 'vrt',
  624. 'REC': 'rec',
  625. 'BNA': 'bna',
  626. 'CSV': 'csv',
  627. 'GML': 'gml',
  628. 'GPX': 'gpx',
  629. 'KML': 'kml',
  630. 'GMT': 'gmt',
  631. 'PGeo': 'mdb',
  632. 'XPlane': 'dat',
  633. 'AVCBin': 'adf',
  634. 'AVCE00': 'e00',
  635. 'DXF': 'dxf',
  636. 'Geoconcept': 'gxt',
  637. 'GeoRSS': 'xml',
  638. 'GPSTrackMaker': 'gtm',
  639. 'VFK': 'vfk',
  640. 'SVG': 'svg'
  641. }
  642. def GetSettingsPath():
  643. """Get full path to the settings directory
  644. """
  645. try:
  646. verFd = open(os.path.join(ETCDIR, "VERSIONNUMBER"))
  647. version = int(verFd.readlines()[0].split(' ')[0].split('.')[0])
  648. except (IOError, ValueError, TypeError, IndexError) as e:
  649. sys.exit(
  650. _("ERROR: Unable to determine GRASS version. Details: %s") %
  651. e)
  652. verFd.close()
  653. # keep location of settings files rc and wx in sync with lib/init/grass.py
  654. if sys.platform == 'win32':
  655. return os.path.join(os.getenv('APPDATA'), 'GRASS%d' % version)
  656. return os.path.join(os.getenv('HOME'), '.grass%d' % version)
  657. def StoreEnvVariable(key, value=None, envFile=None):
  658. """Store environmental variable
  659. If value is not given (is None) then environmental variable is
  660. unset.
  661. :param key: env key
  662. :param value: env value
  663. :param envFile: path to the environmental file (None for default location)
  664. """
  665. windows = sys.platform == 'win32'
  666. if not envFile:
  667. gVersion = grass.version()['version'].split('.', 1)[0]
  668. if not windows:
  669. envFile = os.path.join(
  670. os.getenv('HOME'), '.grass%s' %
  671. gVersion, 'bashrc')
  672. else:
  673. envFile = os.path.join(
  674. os.getenv('APPDATA'), 'GRASS%s' %
  675. gVersion, 'env.bat')
  676. # read env file
  677. environ = dict()
  678. lineSkipped = list()
  679. if os.path.exists(envFile):
  680. try:
  681. fd = open(envFile)
  682. except IOError as e:
  683. sys.stderr.write(_("Unable to open file '%s'\n") % envFile)
  684. return
  685. for line in fd.readlines():
  686. line = line.rstrip(os.linesep)
  687. try:
  688. k, v = map(
  689. lambda x: x.strip(), line.split(
  690. ' ', 1)[1].split(
  691. '=', 1))
  692. except Exception as e:
  693. sys.stderr.write(_("%s: line skipped - unable to parse '%s'\n"
  694. "Reason: %s\n") % (envFile, line, e))
  695. lineSkipped.append(line)
  696. continue
  697. if k in environ:
  698. sys.stderr.write(_("Duplicated key: %s\n") % k)
  699. environ[k] = v
  700. fd.close()
  701. # update environmental variables
  702. if value is None:
  703. if key in environ:
  704. del environ[key]
  705. else:
  706. environ[key] = value
  707. # write update env file
  708. try:
  709. fd = open(envFile, 'w')
  710. except IOError as e:
  711. sys.stderr.write(_("Unable to create file '%s'\n") % envFile)
  712. return
  713. if windows:
  714. expCmd = 'set'
  715. else:
  716. expCmd = 'export'
  717. for key, value in six.iteritems(environ):
  718. fd.write('%s %s=%s\n' % (expCmd, key, value))
  719. # write also skipped lines
  720. for line in lineSkipped:
  721. fd.write(line + os.linesep)
  722. fd.close()
  723. def SetAddOnPath(addonPath=None, key='PATH'):
  724. """Set default AddOn path
  725. :param addonPath: path to addons (None for default)
  726. :param key: env key - 'PATH' or 'BASE'
  727. """
  728. gVersion = grass.version()['version'].split('.', 1)[0]
  729. # update env file
  730. if not addonPath:
  731. if sys.platform != 'win32':
  732. addonPath = os.path.join(os.path.join(os.getenv('HOME'),
  733. '.grass%s' % gVersion,
  734. 'addons'))
  735. else:
  736. addonPath = os.path.join(os.path.join(os.getenv('APPDATA'),
  737. 'GRASS%s' % gVersion,
  738. 'addons'))
  739. StoreEnvVariable(key='GRASS_ADDON_' + key, value=addonPath)
  740. os.environ['GRASS_ADDON_' + key] = addonPath
  741. # update path
  742. if addonPath not in os.environ['PATH']:
  743. os.environ['PATH'] = addonPath + os.pathsep + os.environ['PATH']
  744. # predefined colors and their names
  745. # must be in sync with lib/gis/color_str.c
  746. str2rgb = {'aqua': (100, 128, 255),
  747. 'black': (0, 0, 0),
  748. 'blue': (0, 0, 255),
  749. 'brown': (180, 77, 25),
  750. 'cyan': (0, 255, 255),
  751. 'gray': (128, 128, 128),
  752. 'grey': (128, 128, 128),
  753. 'green': (0, 255, 0),
  754. 'indigo': (0, 128, 255),
  755. 'magenta': (255, 0, 255),
  756. 'orange': (255, 128, 0),
  757. 'red': (255, 0, 0),
  758. 'violet': (128, 0, 255),
  759. 'purple': (128, 0, 255),
  760. 'white': (255, 255, 255),
  761. 'yellow': (255, 255, 0)}
  762. rgb2str = {}
  763. for (s, r) in str2rgb.items():
  764. rgb2str[r] = s
  765. # ensure that gray value has 'gray' string and not 'grey'
  766. rgb2str[str2rgb['gray']] = 'gray'
  767. # purple is defined as nickname for violet in lib/gis
  768. # (although Wikipedia says that purple is (128, 0, 128))
  769. # we will prefer the defined color, not nickname
  770. rgb2str[str2rgb['violet']] = 'violet'
  771. def color_resolve(color):
  772. if len(color) > 0 and color[0] in "0123456789":
  773. rgb = tuple(map(int, color.split(':')))
  774. label = color
  775. else:
  776. # Convert color names to RGB
  777. try:
  778. rgb = str2rgb[color]
  779. label = color
  780. except KeyError:
  781. rgb = (200, 200, 200)
  782. label = _('Select Color')
  783. return (rgb, label)
  784. command2ltype = {'d.rast': 'raster',
  785. 'd.rast3d': 'raster_3d',
  786. 'd.rgb': 'rgb',
  787. 'd.his': 'his',
  788. 'd.shade': 'shaded',
  789. 'd.legend': 'rastleg',
  790. 'd.rast.arrow': 'rastarrow',
  791. 'd.rast.num': 'rastnum',
  792. 'd.rast.leg': 'maplegend',
  793. 'd.vect': 'vector',
  794. 'd.vect.thematic': 'thememap',
  795. 'd.vect.chart': 'themechart',
  796. 'd.grid': 'grid',
  797. 'd.geodesic': 'geodesic',
  798. 'd.rhumbline': 'rhumb',
  799. 'd.labels': 'labels',
  800. 'd.barscale': 'barscale',
  801. 'd.redraw': 'redraw',
  802. 'd.wms': 'wms',
  803. 'd.histogram': 'histogram',
  804. 'd.colortable': 'colortable',
  805. 'd.graph': 'graph',
  806. 'd.out.file': 'export',
  807. 'd.to.rast': 'torast',
  808. 'd.text': 'text',
  809. 'd.northarrow': 'northarrow',
  810. 'd.polar': 'polar',
  811. 'd.legend.vect': 'vectleg'
  812. }
  813. ltype2command = {}
  814. for (cmd, ltype) in command2ltype.items():
  815. ltype2command[ltype] = cmd
  816. def GetGEventAttribsForHandler(method, event):
  817. """Get attributes from event, which can be used by handler method.
  818. Be aware of event class attributes.
  819. :param method: handler method (including self arg)
  820. :param event: event
  821. :return: (valid kwargs for method,
  822. list of method's args without default value
  823. which were not found among event attributes)
  824. """
  825. args_spec = inspect.getargspec(method)
  826. args = args_spec[0]
  827. defaults = []
  828. if args_spec[3]:
  829. defaults = args_spec[3]
  830. # number of arguments without def value
  831. req_args = len(args) - 1 - len(defaults)
  832. kwargs = {}
  833. missing_args = []
  834. for i, a in enumerate(args):
  835. if hasattr(event, a):
  836. kwargs[a] = getattr(event, a)
  837. elif i < req_args:
  838. missing_args.append(a)
  839. return kwargs, missing_args
  840. def PilImageToWxImage(pilImage, copyAlpha=True):
  841. """Convert PIL image to wx.Image
  842. Based on http://wiki.wxpython.org/WorkingWithImages
  843. """
  844. from gui_core.wrap import EmptyImage
  845. hasAlpha = pilImage.mode[-1] == 'A'
  846. if copyAlpha and hasAlpha: # Make sure there is an alpha layer copy.
  847. wxImage = EmptyImage(*pilImage.size)
  848. pilImageCopyRGBA = pilImage.copy()
  849. pilImageCopyRGB = pilImageCopyRGBA.convert('RGB') # RGBA --> RGB
  850. wxImage.SetData(pilImageCopyRGB.tobytes())
  851. # Create layer and insert alpha values.
  852. if wxPythonPhoenix:
  853. wxImage.SetAlpha(pilImageCopyRGBA.tobytes()[3::4])
  854. else:
  855. wxImage.SetAlphaData(pilImageCopyRGBA.tobytes()[3::4])
  856. else: # The resulting image will not have alpha.
  857. wxImage = EmptyImage(*pilImage.size)
  858. pilImageCopy = pilImage.copy()
  859. # Discard any alpha from the PIL image.
  860. pilImageCopyRGB = pilImageCopy.convert('RGB')
  861. wxImage.SetData(pilImageCopyRGB.tobytes())
  862. return wxImage
  863. def autoCropImageFromFile(filename):
  864. """Loads image from file and crops it automatically.
  865. If PIL is not installed, it does not crop it.
  866. :param filename: path to file
  867. :return: wx.Image instance
  868. """
  869. try:
  870. from PIL import Image
  871. pilImage = Image.open(filename)
  872. imageBox = pilImage.getbbox()
  873. cropped = pilImage.crop(imageBox)
  874. return PilImageToWxImage(cropped, copyAlpha=True)
  875. except ImportError:
  876. import wx
  877. return wx.Image(filename)
  878. def isInRegion(regionA, regionB):
  879. """Tests if 'regionA' is inside of 'regionB'.
  880. For example, region A is a display region and region B is some reference
  881. region, e.g., a computational region.
  882. >>> displayRegion = {'n': 223900, 's': 217190, 'w': 630780, 'e': 640690}
  883. >>> compRegion = {'n': 228500, 's': 215000, 'w': 630000, 'e': 645000}
  884. >>> isInRegion(displayRegion, compRegion)
  885. True
  886. >>> displayRegion = {'n':226020, 's': 212610, 'w': 626510, 'e': 646330}
  887. >>> isInRegion(displayRegion, compRegion)
  888. False
  889. :param regionA: input region A as dictionary
  890. :param regionB: input region B as dictionary
  891. :return: True if region A is inside of region B
  892. :return: False othewise
  893. """
  894. if regionA['s'] >= regionB['s'] and \
  895. regionA['n'] <= regionB['n'] and \
  896. regionA['w'] >= regionB['w'] and \
  897. regionA['e'] <= regionB['e']:
  898. return True
  899. return False
  900. def do_doctest_gettext_workaround():
  901. """Setups environment for doing a doctest with gettext usage.
  902. When using gettext with dynamically defined underscore function
  903. (`_("For translation")`), doctest does not work properly. One option is to
  904. use `import as` instead of dynamically defined underscore function but this
  905. would require change all modules which are used by tested module. This
  906. should be considered for the future. The second option is to define dummy
  907. underscore function and one other function which creates the right
  908. environment to satisfy all. This is done by this function.
  909. """
  910. def new_displayhook(string):
  911. """A replacement for default `sys.displayhook`"""
  912. if string is not None:
  913. sys.stdout.write("%r\n" % (string,))
  914. def new_translator(string):
  915. """A fake gettext underscore function."""
  916. return string
  917. sys.displayhook = new_displayhook
  918. import __builtin__
  919. __builtin__._ = new_translator
  920. def doc_test():
  921. """Tests the module using doctest
  922. :return: a number of failed tests
  923. """
  924. import doctest
  925. do_doctest_gettext_workaround()
  926. return doctest.testmod().failed
  927. def registerPid(pid):
  928. """Register process id as GUI_PID GRASS variable
  929. :param: pid process id
  930. """
  931. env = grass.gisenv()
  932. guiPid = []
  933. if 'GUI_PID' in env:
  934. guiPid = env['GUI_PID'].split(',')
  935. guiPid.append(str(pid))
  936. grass.run_command('g.gisenv', set='GUI_PID={0}'.format(','.join(guiPid)))
  937. def unregisterPid(pid):
  938. """Unregister process id from GUI_PID GRASS variable
  939. :param: pid process id
  940. """
  941. env = grass.gisenv()
  942. if 'GUI_PID' not in env:
  943. return
  944. guiPid = env['GUI_PID'].split(',')
  945. pid = str(os.getpid())
  946. if pid in guiPid:
  947. guiPid.remove(pid)
  948. grass.run_command(
  949. 'g.gisenv',
  950. set='GUI_PID={0}'.format(
  951. ','.join(guiPid)))
  952. def get_shell_pid(env=None):
  953. """Get shell PID from the GIS environment or None"""
  954. try:
  955. shell_pid = int(grass.gisenv(env=env)['PID'])
  956. return shell_pid
  957. except (KeyError, ValueError) as error:
  958. Debug.msg(
  959. 1,
  960. "No PID for GRASS shell (assuming no shell running): {}".format(error)
  961. )
  962. return None
  963. def is_shell_running():
  964. """Return True if a separate shell is registered in the GIS environment"""
  965. if get_shell_pid() is None:
  966. return False
  967. return True
  968. if __name__ == '__main__':
  969. sys.exit(doc_test())