utils.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  1. """!
  2. @package core.utils
  3. @brief Misc utilities for wxGUI
  4. (C) 2007-2009, 2011-2012 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 core.globalvar import ETCDIR
  19. if os.path.join(ETCDIR, "python") not in sys.path:
  20. sys.path.append(os.path.join(ETCDIR, "python"))
  21. from grass.script import core as grass
  22. from grass.script import task as gtask
  23. from core.gcmd import RunCommand
  24. from core.debug import Debug
  25. # from core.settings import UserSettings
  26. def normalize_whitespace(text):
  27. """!Remove redundant whitespace from a string"""
  28. return string.join(string.split(text), ' ')
  29. def split(s):
  30. """!Platform spefic shlex.split"""
  31. if sys.platform == "win32":
  32. return shlex.split(s.replace('\\', r'\\'))
  33. else:
  34. return shlex.split(s)
  35. def GetTempfile(pref=None):
  36. """!Creates GRASS temporary file using defined prefix.
  37. @todo Fix path on MS Windows/MSYS
  38. @param pref prefer the given path
  39. @return Path to file name (string) or None
  40. """
  41. ret = RunCommand('g.tempfile',
  42. read = True,
  43. pid = os.getpid())
  44. tempfile = ret.splitlines()[0].strip()
  45. # FIXME
  46. # ugly hack for MSYS (MS Windows)
  47. if platform.system() == 'Windows':
  48. tempfile = tempfile.replace("/", "\\")
  49. try:
  50. path, file = os.path.split(tempfile)
  51. if pref:
  52. return os.path.join(pref, file)
  53. else:
  54. return tempfile
  55. except:
  56. return None
  57. def GetLayerNameFromCmd(dcmd, fullyQualified = False, param = None,
  58. layerType = None):
  59. """!Get map name from GRASS command
  60. Parameter dcmd can be modified when first parameter is not
  61. defined.
  62. @param dcmd GRASS command (given as list)
  63. @param fullyQualified change map name to be fully qualified
  64. @param param params directory
  65. @param layerType check also layer type ('raster', 'vector', '3d-raster', ...)
  66. @return tuple (name, found)
  67. """
  68. mapname = ''
  69. found = True
  70. if len(dcmd) < 1:
  71. return mapname, False
  72. if 'd.grid' == dcmd[0]:
  73. mapname = 'grid'
  74. elif 'd.geodesic' in dcmd[0]:
  75. mapname = 'geodesic'
  76. elif 'd.rhumbline' in dcmd[0]:
  77. mapname = 'rhumb'
  78. elif 'd.graph' in dcmd[0]:
  79. mapname = 'graph'
  80. else:
  81. params = list()
  82. for idx in range(len(dcmd)):
  83. try:
  84. p, v = dcmd[idx].split('=', 1)
  85. except ValueError:
  86. continue
  87. if p == param:
  88. params = [(idx, p, v)]
  89. break
  90. if p in ('map', 'input', 'layer',
  91. 'red', 'blue', 'green',
  92. 'h_map', 's_map', 'i_map',
  93. 'reliefmap', 'labels'):
  94. params.append((idx, p, v))
  95. if len(params) < 1:
  96. if len(dcmd) > 1:
  97. i = 1
  98. while i < len(dcmd):
  99. if '=' not in dcmd[i] and not dcmd[i].startswith('-'):
  100. task = gtask.parse_interface(dcmd[0])
  101. # this expects the first parameter to be the right one
  102. p = task.get_options()['params'][0].get('name', '')
  103. params.append((i, p, dcmd[i]))
  104. break
  105. i += 1
  106. else:
  107. return mapname, False
  108. if len(params) < 1:
  109. return mapname, False
  110. # need to add mapset for all maps
  111. mapsets = {}
  112. for i, p, v in params:
  113. if p == 'layer':
  114. continue
  115. mapname = v
  116. mapset = ''
  117. if fullyQualified and '@' not in mapname:
  118. if layerType in ('raster', 'vector', '3d-raster', 'rgb', 'his'):
  119. try:
  120. if layerType in ('raster', 'rgb', 'his'):
  121. findType = 'cell'
  122. else:
  123. findType = layerType
  124. mapset = grass.find_file(mapname, element = findType)['mapset']
  125. except AttributeError: # not found
  126. return '', False
  127. if not mapset:
  128. found = False
  129. else:
  130. mapset = grass.gisenv()['MAPSET']
  131. mapsets[i] = mapset
  132. # update dcmd
  133. for i, p, v in params:
  134. if p == 'layer':
  135. continue
  136. dcmd[i] = p + '=' + v
  137. if i in mapsets and mapsets[i]:
  138. dcmd[i] += '@' + mapsets[i]
  139. maps = list()
  140. ogr = False
  141. for i, p, v in params:
  142. if v.lower().rfind('@ogr') > -1:
  143. ogr = True
  144. if p == 'layer' and not ogr:
  145. continue
  146. maps.append(dcmd[i].split('=', 1)[1])
  147. mapname = '\n'.join(maps)
  148. return mapname, found
  149. def GetValidLayerName(name):
  150. """!Make layer name SQL compliant, based on G_str_to_sql()
  151. @todo: Better use directly Ctypes to reuse venerable libgis C fns...
  152. """
  153. retName = str(name).strip()
  154. # check if name is fully qualified
  155. if '@' in retName:
  156. retName, mapset = retName.split('@')
  157. else:
  158. mapset = None
  159. cIdx = 0
  160. retNameList = list(retName)
  161. for c in retNameList:
  162. if not (c >= 'A' and c <= 'Z') and \
  163. not (c >= 'a' and c <= 'z') and \
  164. not (c >= '0' and c <= '9'):
  165. retNameList[cIdx] = '_'
  166. cIdx += 1
  167. retName = ''.join(retNameList)
  168. if not (retName[0] >= 'A' and retName[0] <= 'Z') and \
  169. not (retName[0] >= 'a' and retName[0] <= 'z'):
  170. retName = 'x' + retName[1:]
  171. if mapset:
  172. retName = retName + '@' + mapset
  173. return retName
  174. def ListOfCatsToRange(cats):
  175. """!Convert list of category number to range(s)
  176. Used for example for d.vect cats=[range]
  177. @param cats category list
  178. @return category range string
  179. @return '' on error
  180. """
  181. catstr = ''
  182. try:
  183. cats = map(int, cats)
  184. except:
  185. return catstr
  186. i = 0
  187. while i < len(cats):
  188. next = 0
  189. j = i + 1
  190. while j < len(cats):
  191. if cats[i + next] == cats[j] - 1:
  192. next += 1
  193. else:
  194. break
  195. j += 1
  196. if next > 1:
  197. catstr += '%d-%d,' % (cats[i], cats[i + next])
  198. i += next + 1
  199. else:
  200. catstr += '%d,' % (cats[i])
  201. i += 1
  202. return catstr.strip(',')
  203. def ListOfMapsets(get = 'ordered'):
  204. """!Get list of available/accessible mapsets
  205. @param get method ('all', 'accessible', 'ordered')
  206. @return list of mapsets
  207. @return None on error
  208. """
  209. mapsets = []
  210. if get == 'all' or get == 'ordered':
  211. ret = RunCommand('g.mapsets',
  212. read = True,
  213. quiet = True,
  214. flags = 'l',
  215. sep = 'newline')
  216. if ret:
  217. mapsets = ret.splitlines()
  218. ListSortLower(mapsets)
  219. else:
  220. return None
  221. if get == 'accessible' or get == 'ordered':
  222. ret = RunCommand('g.mapsets',
  223. read = True,
  224. quiet = True,
  225. flags = 'p',
  226. sep = 'newline')
  227. if ret:
  228. if get == 'accessible':
  229. mapsets = ret.splitlines()
  230. else:
  231. mapsets_accessible = ret.splitlines()
  232. for mapset in mapsets_accessible:
  233. mapsets.remove(mapset)
  234. mapsets = mapsets_accessible + mapsets
  235. else:
  236. return None
  237. return mapsets
  238. def ListSortLower(list):
  239. """!Sort list items (not case-sensitive)"""
  240. list.sort(cmp=lambda x, y: cmp(x.lower(), y.lower()))
  241. def GetVectorNumberOfLayers(vector):
  242. """!Get list of vector layers connected to database"""
  243. layers = list()
  244. if not vector:
  245. return layers
  246. fullname = grass.find_file(name = vector, element = 'vector')['fullname']
  247. if not fullname:
  248. Debug.msg(5, "utils.GetVectorNumberOfLayers(): vector map '%s' not found" % vector)
  249. return layers
  250. ret, out, msg = RunCommand('v.category',
  251. getErrorMsg = True,
  252. read = True,
  253. input = fullname,
  254. option = 'layers')
  255. if ret != 0:
  256. sys.stderr.write(_("Vector map <%(map)s>: %(msg)s\n") % { 'map' : fullname, 'msg' : msg })
  257. return layers
  258. else:
  259. Debug.msg(1, "GetVectorNumberOfLayers(): ret %s" % ret)
  260. for layer in out.splitlines():
  261. layers.append(layer)
  262. Debug.msg(3, "utils.GetVectorNumberOfLayers(): vector=%s -> %s" % \
  263. (fullname, ','.join(layers)))
  264. return layers
  265. def Deg2DMS(lon, lat, string = True, hemisphere = True, precision = 3):
  266. """!Convert deg value to dms string
  267. @param lon longitude (x)
  268. @param lat latitude (y)
  269. @param string True to return string otherwise tuple
  270. @param hemisphere print hemisphere
  271. @param precision seconds precision
  272. @return DMS string or tuple of values
  273. @return empty string on error
  274. """
  275. try:
  276. flat = float(lat)
  277. flon = float(lon)
  278. except ValueError:
  279. if string:
  280. return ''
  281. else:
  282. return None
  283. # fix longitude
  284. while flon > 180.0:
  285. flon -= 360.0
  286. while flon < -180.0:
  287. flon += 360.0
  288. # hemisphere
  289. if hemisphere:
  290. if flat < 0.0:
  291. flat = abs(flat)
  292. hlat = 'S'
  293. else:
  294. hlat = 'N'
  295. if flon < 0.0:
  296. hlon = 'W'
  297. flon = abs(flon)
  298. else:
  299. hlon = 'E'
  300. else:
  301. flat = abs(flat)
  302. flon = abs(flon)
  303. hlon = ''
  304. hlat = ''
  305. slat = __ll_parts(flat, precision = precision)
  306. slon = __ll_parts(flon, precision = precision)
  307. if string:
  308. return slon + hlon + '; ' + slat + hlat
  309. return (slon + hlon, slat + hlat)
  310. def DMS2Deg(lon, lat):
  311. """!Convert dms value to deg
  312. @param lon longitude (x)
  313. @param lat latitude (y)
  314. @return tuple of converted values
  315. @return ValueError on error
  316. """
  317. x = __ll_parts(lon, reverse = True)
  318. y = __ll_parts(lat, reverse = True)
  319. return (x, y)
  320. def __ll_parts(value, reverse = False, precision = 3):
  321. """!Converts deg to d:m:s string
  322. @param value value to be converted
  323. @param reverse True to convert from d:m:s to deg
  324. @param precision seconds precision (ignored if reverse is True)
  325. @return converted value (string/float)
  326. @return ValueError on error (reverse == True)
  327. """
  328. if not reverse:
  329. if value == 0.0:
  330. return '%s%.*f' % ('00:00:0', precision, 0.0)
  331. d = int(int(value))
  332. m = int((value - d) * 60)
  333. s = ((value - d) * 60 - m) * 60
  334. if m < 0:
  335. m = '00'
  336. elif m < 10:
  337. m = '0' + str(m)
  338. else:
  339. m = str(m)
  340. if s < 0:
  341. s = '00.0000'
  342. elif s < 10.0:
  343. s = '0%.*f' % (precision, s)
  344. else:
  345. s = '%.*f' % (precision, s)
  346. return str(d) + ':' + m + ':' + s
  347. else: # -> reverse
  348. try:
  349. d, m, s = value.split(':')
  350. hs = s[-1]
  351. s = s[:-1]
  352. except ValueError:
  353. try:
  354. d, m = value.split(':')
  355. hs = m[-1]
  356. m = m[:-1]
  357. s = '0.0'
  358. except ValueError:
  359. try:
  360. d = value
  361. hs = d[-1]
  362. d = d[:-1]
  363. m = '0'
  364. s = '0.0'
  365. except ValueError:
  366. raise ValueError
  367. if hs not in ('N', 'S', 'E', 'W'):
  368. raise ValueError
  369. coef = 1.0
  370. if hs in ('S', 'W'):
  371. coef = -1.0
  372. fm = int(m) / 60.0
  373. fs = float(s) / (60 * 60)
  374. return coef * (float(d) + fm + fs)
  375. def GetCmdString(cmd):
  376. """!Get GRASS command as string.
  377. @param cmd GRASS command given as tuple
  378. @return command string
  379. """
  380. return ' '.join(CmdTupleToList(cmd))
  381. def CmdTupleToList(cmd):
  382. """!Convert command tuple to list.
  383. @param cmd GRASS command given as tuple
  384. @return command in list
  385. """
  386. cmdList = []
  387. if not cmd:
  388. return cmdList
  389. cmdList.append(cmd[0])
  390. if 'flags' in cmd[1]:
  391. for flag in cmd[1]['flags']:
  392. cmdList.append('-' + flag)
  393. for flag in ('verbose', 'quiet', 'overwrite'):
  394. if flag in cmd[1] and cmd[1][flag] is True:
  395. cmdList.append('--' + flag)
  396. for k, v in cmd[1].iteritems():
  397. if k in ('flags', 'verbose', 'quiet', 'overwrite'):
  398. continue
  399. cmdList.append('%s=%s' % (k, v))
  400. return cmdList
  401. def CmdToTuple(cmd):
  402. """!Convert command list to tuple for gcmd.RunCommand()"""
  403. if len(cmd) < 1:
  404. return None
  405. dcmd = {}
  406. for item in cmd[1:]:
  407. if '=' in item: # params
  408. key, value = item.split('=', 1)
  409. dcmd[str(key)] = str(value).replace('"', '')
  410. elif item[:2] == '--': # long flags
  411. flag = item[2:]
  412. if flag in ('verbose', 'quiet', 'overwrite'):
  413. dcmd[str(flag)] = True
  414. elif len(item) == 2 and item[0] == '-': # -> flags
  415. if 'flags' not in dcmd:
  416. dcmd['flags'] = ''
  417. dcmd['flags'] += item[1]
  418. else: # unnamed parameter
  419. module = gtask.parse_interface(cmd[0])
  420. dcmd[module.define_first()] = item
  421. return (cmd[0], dcmd)
  422. def PathJoin(*args):
  423. """!Check path created by os.path.join"""
  424. path = os.path.join(*args)
  425. if platform.system() == 'Windows' and \
  426. '/' in path:
  427. return path[1].upper() + ':\\' + path[3:].replace('/', '\\')
  428. return path
  429. def ReadEpsgCodes(path):
  430. """!Read EPSG code from the file
  431. @param path full path to the file with EPSG codes
  432. @return dictionary of EPSG code
  433. @return string on error
  434. """
  435. epsgCodeDict = dict()
  436. try:
  437. try:
  438. f = open(path, "r")
  439. except IOError:
  440. return _("failed to open '%s'" % path)
  441. code = None
  442. for line in f.readlines():
  443. line = line.strip()
  444. if len(line) < 1:
  445. continue
  446. if line[0] == '#':
  447. descr = line[1:].strip()
  448. elif line[0] == '<':
  449. code, params = line.split(" ", 1)
  450. try:
  451. code = int(code.replace('<', '').replace('>', ''))
  452. except ValueError, e:
  453. return e
  454. if code is not None:
  455. epsgCodeDict[code] = (descr, params)
  456. code = None
  457. f.close()
  458. except StandardError, e:
  459. return e
  460. return epsgCodeDict
  461. def ReprojectCoordinates(coord, projOut, projIn = None, flags = ''):
  462. """!Reproject coordinates
  463. @param coord coordinates given as tuple
  464. @param projOut output projection
  465. @param projIn input projection (use location projection settings)
  466. @return reprojected coordinates (returned as tuple)
  467. """
  468. coors = RunCommand('m.proj',
  469. flags = flags,
  470. input = '-',
  471. proj_input = projIn,
  472. proj_output = projOut,
  473. sep = ';',
  474. stdin = '%f;%f' % (coord[0], coord[1]),
  475. read = True)
  476. if coors:
  477. coors = coors.split(';')
  478. e = coors[0]
  479. n = coors[1]
  480. try:
  481. proj = projOut.split(' ')[0].split('=')[1]
  482. except IndexError:
  483. proj = ''
  484. if proj in ('ll', 'latlong', 'longlat') and 'd' not in flags:
  485. return (proj, (e, n))
  486. else:
  487. try:
  488. return (proj, (float(e), float(n)))
  489. except ValueError:
  490. return (None, None)
  491. return (None, None)
  492. def GetListOfLocations(dbase):
  493. """!Get list of GRASS locations in given dbase
  494. @param dbase GRASS database path
  495. @return list of locations (sorted)
  496. """
  497. listOfLocations = list()
  498. try:
  499. for location in glob.glob(os.path.join(dbase, "*")):
  500. try:
  501. if os.path.join(location, "PERMANENT") in glob.glob(os.path.join(location, "*")):
  502. listOfLocations.append(os.path.basename(location))
  503. except:
  504. pass
  505. except UnicodeEncodeError, e:
  506. raise e
  507. ListSortLower(listOfLocations)
  508. return listOfLocations
  509. def GetListOfMapsets(dbase, location, selectable = False):
  510. """!Get list of mapsets in given GRASS location
  511. @param dbase GRASS database path
  512. @param location GRASS location
  513. @param selectable True to get list of selectable mapsets, otherwise all
  514. @return list of mapsets - sorted (PERMANENT first)
  515. """
  516. listOfMapsets = list()
  517. if selectable:
  518. ret = RunCommand('g.mapset',
  519. read = True,
  520. flags = 'l',
  521. location = location,
  522. gisdbase = dbase)
  523. if not ret:
  524. return listOfMapsets
  525. for line in ret.rstrip().splitlines():
  526. listOfMapsets += line.split(' ')
  527. else:
  528. for mapset in glob.glob(os.path.join(dbase, location, "*")):
  529. if os.path.isdir(mapset) and \
  530. os.path.isfile(os.path.join(dbase, location, mapset, "WIND")):
  531. listOfMapsets.append(os.path.basename(mapset))
  532. ListSortLower(listOfMapsets)
  533. return listOfMapsets
  534. def GetColorTables():
  535. """!Get list of color tables"""
  536. ret = RunCommand('r.colors',
  537. read = True,
  538. flags = 'l')
  539. if not ret:
  540. return list()
  541. return ret.splitlines()
  542. def _getGDALFormats():
  543. """!Get dictionary of avaialble GDAL drivers"""
  544. try:
  545. ret = grass.read_command('r.in.gdal',
  546. quiet = True,
  547. flags = 'f')
  548. except:
  549. ret = None
  550. return _parseFormats(ret), _parseFormats(ret, writableOnly = True)
  551. def _getOGRFormats():
  552. """!Get dictionary of avaialble OGR drivers"""
  553. try:
  554. ret = grass.read_command('v.in.ogr',
  555. quiet = True,
  556. flags = 'f')
  557. except:
  558. ret = None
  559. return _parseFormats(ret), _parseFormats(ret, writableOnly = True)
  560. def _parseFormats(output, writableOnly = False):
  561. """!Parse r.in.gdal/v.in.ogr -f output"""
  562. formats = { 'file' : list(),
  563. 'database' : list(),
  564. 'protocol' : list()
  565. }
  566. if not output:
  567. return formats
  568. patt = None
  569. if writableOnly:
  570. patt = re.compile('\(rw\+?\)$', re.IGNORECASE)
  571. for line in output.splitlines():
  572. key, name = map(lambda x: x.strip(), line.strip().rsplit(':', -1))
  573. if writableOnly and not patt.search(key):
  574. continue
  575. if name in ('Memory', 'Virtual Raster', 'In Memory Raster'):
  576. continue
  577. if name in ('PostgreSQL', 'SQLite',
  578. 'ODBC', 'ESRI Personal GeoDatabase',
  579. 'Rasterlite',
  580. 'PostGIS WKT Raster driver',
  581. 'PostGIS Raster driver',
  582. 'CouchDB',
  583. 'MSSQLSpatial',
  584. 'FileGDB'):
  585. formats['database'].append(name)
  586. elif name in ('GeoJSON',
  587. 'OGC Web Coverage Service',
  588. 'OGC Web Map Service',
  589. 'WFS',
  590. 'GeoRSS',
  591. 'HTTP Fetching Wrapper'):
  592. formats['protocol'].append(name)
  593. else:
  594. formats['file'].append(name)
  595. for items in formats.itervalues():
  596. items.sort()
  597. return formats
  598. formats = None
  599. def GetFormats(writableOnly = False):
  600. """!Get GDAL/OGR formats"""
  601. global formats
  602. if not formats:
  603. gdalAll, gdalWritable = _getGDALFormats()
  604. ogrAll, ogrWritable = _getOGRFormats()
  605. formats = {
  606. 'all' : {
  607. 'gdal' : gdalAll,
  608. 'ogr' : ogrAll,
  609. },
  610. 'writable' : {
  611. 'gdal' : gdalWritable,
  612. 'ogr' : ogrWritable,
  613. },
  614. }
  615. if writableOnly:
  616. return formats['writable']
  617. return formats['all']
  618. def GetSettingsPath():
  619. """!Get full path to the settings directory
  620. """
  621. try:
  622. verFd = open(os.path.join(ETCDIR, "VERSIONNUMBER"))
  623. version = int(verFd.readlines()[0].split(' ')[0].split('.')[0])
  624. except (IOError, ValueError, TypeError, IndexError), e:
  625. sys.exit(_("ERROR: Unable to determine GRASS version. Details: %s") % e)
  626. verFd.close()
  627. # keep location of settings files rc and wx in sync with lib/init/grass.py
  628. if sys.platform == 'win32':
  629. return os.path.join(os.getenv('APPDATA'), 'GRASS%d' % version)
  630. return os.path.join(os.getenv('HOME'), '.grass%d' % version)
  631. def StoreEnvVariable(key, value = None, envFile = None):
  632. """!Store environmental variable
  633. If value is not given (is None) then environmental variable is
  634. unset.
  635. @param key env key
  636. @param value env value
  637. @param envFile path to the environmental file (None for default location)
  638. """
  639. windows = sys.platform == 'win32'
  640. if not envFile:
  641. gVersion = grass.version()['version'].split('.', 1)[0]
  642. if not windows:
  643. envFile = os.path.join(os.getenv('HOME'), '.grass%s' % gVersion, 'bashrc')
  644. else:
  645. envFile = os.path.join(os.getenv('APPDATA'), 'GRASS%s' % gVersion, 'env.bat')
  646. # read env file
  647. environ = dict()
  648. lineSkipped = list()
  649. if os.path.exists(envFile):
  650. try:
  651. fd = open(envFile)
  652. except IOError, e:
  653. sys.stderr.write(_("Unable to open file '%s'\n") % envFile)
  654. return
  655. for line in fd.readlines():
  656. line = line.rstrip(os.linesep)
  657. try:
  658. k, v = map(lambda x: x.strip(), line.split(' ', 1)[1].split('=', 1))
  659. except StandardError, e:
  660. sys.stderr.write(_("%s: line skipped - unable to parse '%s'\n"
  661. "Reason: %s\n") % (envFile, line, e))
  662. lineSkipped.append(line)
  663. continue
  664. if k in environ:
  665. sys.stderr.write(_("Duplicated key: %s\n") % k)
  666. environ[k] = v
  667. fd.close()
  668. # update environmental variables
  669. if value is None:
  670. if key in environ:
  671. del environ[key]
  672. else:
  673. environ[key] = value
  674. # write update env file
  675. try:
  676. fd = open(envFile, 'w')
  677. except IOError, e:
  678. sys.stderr.write(_("Unable to create file '%s'\n") % envFile)
  679. return
  680. if windows:
  681. expCmd = 'set'
  682. else:
  683. expCmd = 'export'
  684. for key, value in environ.iteritems():
  685. fd.write('%s %s=%s\n' % (expCmd, key, value))
  686. # write also skipped lines
  687. for line in lineSkipped:
  688. fd.write(line + os.linesep)
  689. fd.close()
  690. def SetAddOnPath(addonPath = None, key = 'PATH'):
  691. """!Set default AddOn path
  692. @param addonPath path to addons (None for default)
  693. @param key env key - 'PATH' or 'BASE'
  694. """
  695. gVersion = grass.version()['version'].split('.', 1)[0]
  696. # update env file
  697. if not addonPath:
  698. if sys.platform != 'win32':
  699. addonPath = os.path.join(os.path.join(os.getenv('HOME'),
  700. '.grass%s' % gVersion,
  701. 'addons'))
  702. else:
  703. addonPath = os.path.join(os.path.join(os.getenv('APPDATA'),
  704. 'GRASS%s' % gVersion,
  705. 'addons'))
  706. StoreEnvVariable(key = 'GRASS_ADDON_' + key, value = addonPath)
  707. os.environ['GRASS_ADDON_' + key] = addonPath
  708. # update path
  709. if addonPath not in os.environ['PATH']:
  710. os.environ['PATH'] = addonPath + os.pathsep + os.environ['PATH']
  711. # From lib/gis/col_str.c, except purple which is mentioned
  712. # there but not given RGB values
  713. str2rgb = {'aqua': (100, 128, 255),
  714. 'black': (0, 0, 0),
  715. 'blue': (0, 0, 255),
  716. 'brown': (180, 77, 25),
  717. 'cyan': (0, 255, 255),
  718. 'gray': (128, 128, 128),
  719. 'green': (0, 255, 0),
  720. 'grey': (128, 128, 128),
  721. 'indigo': (0, 128, 255),
  722. 'magenta': (255, 0, 255),
  723. 'orange': (255, 128, 0),
  724. 'purple': (128, 0, 128),
  725. 'red': (255, 0, 0),
  726. 'violet': (128, 0, 255),
  727. 'white': (255, 255, 255),
  728. 'yellow': (255, 255, 0)}
  729. rgb2str = {}
  730. for (s,r) in str2rgb.items():
  731. rgb2str[ r ] = s
  732. def color_resolve(color):
  733. if len(color) > 0 and color[0] in "0123456789":
  734. rgb = tuple(map(int, color.split(':')))
  735. label = color
  736. else:
  737. # Convert color names to RGB
  738. try:
  739. rgb = str2rgb[color]
  740. label = color
  741. except KeyError:
  742. rgb = (200, 200, 200)
  743. label = _('Select Color')
  744. return (rgb, label)
  745. command2ltype = {'d.rast' : 'raster',
  746. 'd.rast3d' : '3d-raster',
  747. 'd.rgb' : 'rgb',
  748. 'd.his' : 'his',
  749. 'd.shadedmap' : 'shaded',
  750. 'd.legend' : 'rastleg',
  751. 'd.rast.arrow' : 'rastarrow',
  752. 'd.rast.num' : 'rastnum',
  753. 'd.rast.leg' : 'maplegend',
  754. 'd.vect' : 'vector',
  755. 'd.thematic.area': 'thememap',
  756. 'd.vect.chart' : 'themechart',
  757. 'd.grid' : 'grid',
  758. 'd.geodesic' : 'geodesic',
  759. 'd.rhumbline' : 'rhumb',
  760. 'd.labels' : 'labels',
  761. 'd.barscale' : 'barscale',
  762. 'd.redraw' : 'redraw',
  763. 'd.wms' : 'wms',
  764. 'd.histogram' : 'histogram',
  765. 'd.colortable' : 'colortable',
  766. 'd.graph' : 'graph'
  767. }
  768. ltype2command = {}
  769. for (cmd, ltype) in command2ltype.items():
  770. ltype2command[ltype] = cmd
  771. def GetGEventAttribsForHandler(method, event):
  772. """!Get attributes from event, which can be used by handler method.
  773. Be aware of event class attributes.
  774. @param method - handler method (including self arg)
  775. @param event - event
  776. @return (valid kwargs for method,
  777. list of method's args without default value
  778. which were not found among event attributes)
  779. """
  780. args_spec = inspect.getargspec(method)
  781. args = args_spec[0]
  782. defaults =[]
  783. if args_spec[3]:
  784. defaults = args_spec[3]
  785. # number of arguments without def value
  786. req_args = len(args) - 1 - len(defaults)
  787. kwargs = {}
  788. missing_args = []
  789. for i, a in enumerate(args):
  790. if hasattr(event, a):
  791. kwargs[a] = getattr(event, a)
  792. elif i < req_args:
  793. missing_args.append(a)
  794. return kwargs, missing_args