utils.py 33 KB

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