utils.py 36 KB

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