utils.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  1. """!
  2. @package core.utils
  3. @brief Misc utilities for wxGUI
  4. (C) 2007-2009, 2011 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. from core.globalvar import ETCDIR
  18. sys.path.append(os.path.join(ETCDIR, "python"))
  19. from grass.script import core as grass
  20. from grass.script import task as gtask
  21. from core.gcmd import RunCommand
  22. from core.debug import Debug
  23. # from core.settings import UserSettings
  24. def normalize_whitespace(text):
  25. """!Remove redundant whitespace from a string"""
  26. return string.join(string.split(text), ' ')
  27. def split(s):
  28. """!Platform spefic shlex.split"""
  29. if sys.version_info >= (2, 6):
  30. return shlex.split(s, posix = (sys.platform != "win32"))
  31. elif 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. else:
  79. params = list()
  80. for idx in range(len(dcmd)):
  81. try:
  82. p, v = dcmd[idx].split('=', 1)
  83. except ValueError:
  84. continue
  85. if p == param:
  86. params = [(idx, p, v)]
  87. break
  88. if p in ('map', 'input', 'layer',
  89. 'red', 'blue', 'green',
  90. 'h_map', 's_map', 'i_map',
  91. 'reliefmap', 'labels'):
  92. params.append((idx, p, v))
  93. if len(params) < 1:
  94. if len(dcmd) > 1:
  95. i = 1
  96. while i < len(dcmd):
  97. if '=' not in dcmd[i] and not dcmd[i].startswith('-'):
  98. task = gtask.parse_interface(dcmd[0])
  99. # this expects the first parameter to be the right one
  100. p = task.get_options()['params'][0].get('name', '')
  101. params.append((i, p, dcmd[i]))
  102. break
  103. i += 1
  104. else:
  105. return mapname, False
  106. if len(params) < 1:
  107. return mapname, False
  108. # need to add mapset for all maps
  109. mapsets = {}
  110. for i, p, v in params:
  111. if p == 'layer':
  112. continue
  113. mapname = v
  114. mapset = ''
  115. if fullyQualified and '@' not in mapname:
  116. if layerType in ('raster', 'vector', '3d-raster', 'rgb', 'his'):
  117. try:
  118. if layerType in ('raster', 'rgb', 'his'):
  119. findType = 'cell'
  120. else:
  121. findType = layerType
  122. mapset = grass.find_file(mapname, element = findType)['mapset']
  123. except AttributeError: # not found
  124. return '', False
  125. if not mapset:
  126. found = False
  127. else:
  128. mapset = grass.gisenv()['MAPSET']
  129. mapsets[i] = mapset
  130. # update dcmd
  131. for i, p, v in params:
  132. if p == 'layer':
  133. continue
  134. dcmd[i] = p + '=' + v
  135. if i in mapsets and mapsets[i]:
  136. dcmd[i] += '@' + mapsets[i]
  137. maps = list()
  138. ogr = False
  139. for i, p, v in params:
  140. if v.lower().rfind('@ogr') > -1:
  141. ogr = True
  142. if p == 'layer' and not ogr:
  143. continue
  144. maps.append(dcmd[i].split('=', 1)[1])
  145. mapname = '\n'.join(maps)
  146. return mapname, found
  147. def GetValidLayerName(name):
  148. """!Make layer name SQL compliant, based on G_str_to_sql()
  149. @todo: Better use directly GRASS Python SWIG...
  150. """
  151. retName = str(name).strip()
  152. # check if name is fully qualified
  153. if '@' in retName:
  154. retName, mapset = retName.split('@')
  155. else:
  156. mapset = None
  157. cIdx = 0
  158. retNameList = list(retName)
  159. for c in retNameList:
  160. if not (c >= 'A' and c <= 'Z') and \
  161. not (c >= 'a' and c <= 'z') and \
  162. not (c >= '0' and c <= '9'):
  163. retNameList[cIdx] = '_'
  164. cIdx += 1
  165. retName = ''.join(retNameList)
  166. if not (retName[0] >= 'A' and retName[0] <= 'Z') and \
  167. not (retName[0] >= 'a' and retName[0] <= 'z'):
  168. retName = 'x' + retName[1:]
  169. if mapset:
  170. retName = retName + '@' + mapset
  171. return retName
  172. def ListOfCatsToRange(cats):
  173. """!Convert list of category number to range(s)
  174. Used for example for d.vect cats=[range]
  175. @param cats category list
  176. @return category range string
  177. @return '' on error
  178. """
  179. catstr = ''
  180. try:
  181. cats = map(int, cats)
  182. except:
  183. return catstr
  184. i = 0
  185. while i < len(cats):
  186. next = 0
  187. j = i + 1
  188. while j < len(cats):
  189. if cats[i + next] == cats[j] - 1:
  190. next += 1
  191. else:
  192. break
  193. j += 1
  194. if next > 1:
  195. catstr += '%d-%d,' % (cats[i], cats[i + next])
  196. i += next + 1
  197. else:
  198. catstr += '%d,' % (cats[i])
  199. i += 1
  200. return catstr.strip(',')
  201. def ListOfMapsets(get = 'ordered'):
  202. """!Get list of available/accessible mapsets
  203. @param get method ('all', 'accessible', 'ordered')
  204. @return list of mapsets
  205. @return None on error
  206. """
  207. mapsets = []
  208. if get == 'all' or get == 'ordered':
  209. ret = RunCommand('g.mapsets',
  210. read = True,
  211. quiet = True,
  212. flags = 'l',
  213. sep = 'newline')
  214. if ret:
  215. mapsets = ret.splitlines()
  216. ListSortLower(mapsets)
  217. else:
  218. return None
  219. if get == 'accessible' or get == 'ordered':
  220. ret = RunCommand('g.mapsets',
  221. read = True,
  222. quiet = True,
  223. flags = 'p',
  224. sep = 'newline')
  225. if ret:
  226. if get == 'accessible':
  227. mapsets = ret.splitlines()
  228. else:
  229. mapsets_accessible = ret.splitlines()
  230. for mapset in mapsets_accessible:
  231. mapsets.remove(mapset)
  232. mapsets = mapsets_accessible + mapsets
  233. else:
  234. return None
  235. return mapsets
  236. def ListSortLower(list):
  237. """!Sort list items (not case-sensitive)"""
  238. list.sort(cmp=lambda x, y: cmp(x.lower(), y.lower()))
  239. def GetVectorNumberOfLayers(vector):
  240. """!Get list of vector layers"""
  241. layers = list()
  242. if not vector:
  243. return layers
  244. fullname = grass.find_file(name = vector, element = 'vector')['fullname']
  245. if not fullname:
  246. Debug.msg(5, "utils.GetVectorNumberOfLayers(): vector map '%s' not found" % vector)
  247. return layers
  248. ret, out, msg = RunCommand('v.db.connect',
  249. getErrorMsg = True,
  250. read = True,
  251. flags = 'g',
  252. map = fullname,
  253. sep = ';')
  254. if ret != 0:
  255. sys.stderr.write(_("Vector map <%(map)s>: %(msg)s\n") % { 'map' : fullname, 'msg' : msg })
  256. return layers
  257. else:
  258. Debug.msg(1, "GetVectorNumberOfLayers(): ret %s" % ret)
  259. for line in ret.splitlines():
  260. try:
  261. layer = line.split(';')[0]
  262. if '/' in layer:
  263. layer = layer.split('/')[0]
  264. layers.append(layer)
  265. except IndexError:
  266. pass
  267. Debug.msg(3, "utils.GetVectorNumberOfLayers(): vector=%s -> %s" % \
  268. (fullname, ','.join(layers)))
  269. return layers
  270. def Deg2DMS(lon, lat, string = True, hemisphere = True, precision = 3):
  271. """!Convert deg value to dms string
  272. @param lon longitude (x)
  273. @param lat latitude (y)
  274. @param string True to return string otherwise tuple
  275. @param hemisphere print hemisphere
  276. @param precision seconds precision
  277. @return DMS string or tuple of values
  278. @return empty string on error
  279. """
  280. try:
  281. flat = float(lat)
  282. flon = float(lon)
  283. except ValueError:
  284. if string:
  285. return ''
  286. else:
  287. return None
  288. # fix longitude
  289. while flon > 180.0:
  290. flon -= 360.0
  291. while flon < -180.0:
  292. flon += 360.0
  293. # hemisphere
  294. if hemisphere:
  295. if flat < 0.0:
  296. flat = abs(flat)
  297. hlat = 'S'
  298. else:
  299. hlat = 'N'
  300. if flon < 0.0:
  301. hlon = 'W'
  302. flon = abs(flon)
  303. else:
  304. hlon = 'E'
  305. else:
  306. flat = abs(flat)
  307. flon = abs(flon)
  308. hlon = ''
  309. hlat = ''
  310. slat = __ll_parts(flat, precision = precision)
  311. slon = __ll_parts(flon, precision = precision)
  312. if string:
  313. return slon + hlon + '; ' + slat + hlat
  314. return (slon + hlon, slat + hlat)
  315. def DMS2Deg(lon, lat):
  316. """!Convert dms value to deg
  317. @param lon longitude (x)
  318. @param lat latitude (y)
  319. @return tuple of converted values
  320. @return ValueError on error
  321. """
  322. x = __ll_parts(lon, reverse = True)
  323. y = __ll_parts(lat, reverse = True)
  324. return (x, y)
  325. def __ll_parts(value, reverse = False, precision = 3):
  326. """!Converts deg to d:m:s string
  327. @param value value to be converted
  328. @param reverse True to convert from d:m:s to deg
  329. @param precision seconds precision (ignored if reverse is True)
  330. @return converted value (string/float)
  331. @return ValueError on error (reverse == True)
  332. """
  333. if not reverse:
  334. if value == 0.0:
  335. return '%s%.*f' % ('00:00:0', precision, 0.0)
  336. d = int(int(value))
  337. m = int((value - d) * 60)
  338. s = ((value - d) * 60 - m) * 60
  339. if m < 0:
  340. m = '00'
  341. elif m < 10:
  342. m = '0' + str(m)
  343. else:
  344. m = str(m)
  345. if s < 0:
  346. s = '00.0000'
  347. elif s < 10.0:
  348. s = '0%.*f' % (precision, s)
  349. else:
  350. s = '%.*f' % (precision, s)
  351. return str(d) + ':' + m + ':' + s
  352. else: # -> reverse
  353. try:
  354. d, m, s = value.split(':')
  355. hs = s[-1]
  356. s = s[:-1]
  357. except ValueError:
  358. try:
  359. d, m = value.split(':')
  360. hs = m[-1]
  361. m = m[:-1]
  362. s = '0.0'
  363. except ValueError:
  364. try:
  365. d = value
  366. hs = d[-1]
  367. d = d[:-1]
  368. m = '0'
  369. s = '0.0'
  370. except ValueError:
  371. raise ValueError
  372. if hs not in ('N', 'S', 'E', 'W'):
  373. raise ValueError
  374. coef = 1.0
  375. if hs in ('S', 'W'):
  376. coef = -1.0
  377. fm = int(m) / 60.0
  378. fs = float(s) / (60 * 60)
  379. return coef * (float(d) + fm + fs)
  380. def GetCmdString(cmd):
  381. """
  382. Get GRASS command as string.
  383. @param cmd GRASS command given as dictionary
  384. @return command string
  385. """
  386. scmd = ''
  387. if not cmd:
  388. return scmd
  389. scmd = cmd[0]
  390. if 'flags' in cmd[1]:
  391. for flag in cmd[1]['flags']:
  392. scmd += ' -' + flag
  393. for flag in ('verbose', 'quiet', 'overwrite'):
  394. if flag in cmd[1] and cmd[1][flag] is True:
  395. scmd += ' --' + flag
  396. for k, v in cmd[1].iteritems():
  397. if k in ('flags', 'verbose', 'quiet', 'overwrite'):
  398. continue
  399. scmd += ' %s=%s' % (k, v)
  400. return scmd
  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. formats['database'].append(name)
  584. elif name in ('GeoJSON',
  585. 'OGC Web Coverage Service',
  586. 'OGC Web Map Service',
  587. 'WFS',
  588. 'GeoRSS',
  589. 'HTTP Fetching Wrapper'):
  590. formats['protocol'].append(name)
  591. else:
  592. formats['file'].append(name)
  593. for items in formats.itervalues():
  594. items.sort()
  595. return formats
  596. formats = None
  597. def GetFormats(writableOnly = False):
  598. """!Get GDAL/OGR formats"""
  599. global formats
  600. if not formats:
  601. gdalAll, gdalWritable = _getGDALFormats()
  602. ogrAll, ogrWritable = _getOGRFormats()
  603. formats = {
  604. 'all' : {
  605. 'gdal' : gdalAll,
  606. 'ogr' : ogrAll,
  607. },
  608. 'writable' : {
  609. 'gdal' : gdalWritable,
  610. 'ogr' : ogrWritable,
  611. },
  612. }
  613. if writableOnly:
  614. return formats['writable']
  615. return formats['all']
  616. def GetSettingsPath():
  617. """!Get full path to the settings directory
  618. """
  619. try:
  620. verFd = open(os.path.join(ETCDIR, "VERSIONNUMBER"))
  621. version = int(verFd.readlines()[0].split(' ')[0].split('.')[0])
  622. except (IOError, ValueError, TypeError, IndexError), e:
  623. sys.exit(_("ERROR: Unable to determine GRASS version. Details: %s") % e)
  624. verFd.close()
  625. # keep location of settings files rc and wx in sync with lib/init/grass.py
  626. if sys.platform == 'win32':
  627. return os.path.join(os.getenv('APPDATA'), 'GRASS%d' % version)
  628. return os.path.join(os.getenv('HOME'), '.grass%d' % version)
  629. def StoreEnvVariable(key, value = None, envFile = None):
  630. """!Store environmental variable
  631. If value is not given (is None) then environmental variable is
  632. unset.
  633. @param key env key
  634. @param value env value
  635. @param envFile path to the environmental file (None for default location)
  636. """
  637. windows = sys.platform == 'win32'
  638. if not envFile:
  639. gVersion = grass.version()['version'].split('.', 1)[0]
  640. if not windows:
  641. envFile = os.path.join(os.getenv('HOME'), '.grass%s' % gVersion, 'bashrc')
  642. else:
  643. envFile = os.path.join(os.getenv('APPDATA'), 'GRASS%s' % gVersion, 'env.bat')
  644. # read env file
  645. environ = dict()
  646. lineSkipped = list()
  647. if os.path.exists(envFile):
  648. try:
  649. fd = open(envFile)
  650. except IOError, e:
  651. sys.stderr.write(_("Unable to open file '%s'\n") % envFile)
  652. return
  653. for line in fd.readlines():
  654. line = line.rstrip(os.linesep)
  655. try:
  656. k, v = map(lambda x: x.strip(), line.split(' ', 1)[1].split('=', 1))
  657. except StandardError, e:
  658. sys.stderr.write(_("%s: line skipped - unable to parse '%s'\n"
  659. "Reason: %s\n") % (envFile, line, e))
  660. lineSkipped.append(line)
  661. continue
  662. if k in environ:
  663. sys.stderr.write(_("Duplicated key: %s\n") % k)
  664. environ[k] = v
  665. fd.close()
  666. # update environmental variables
  667. if value is None and key in environ:
  668. del environ[key]
  669. else:
  670. environ[key] = value
  671. # write update env file
  672. try:
  673. fd = open(envFile, 'w')
  674. except IOError, e:
  675. sys.stderr.write(_("Unable to create file '%s'\n") % envFile)
  676. return
  677. if windows:
  678. expCmd = 'set'
  679. else:
  680. expCmd = 'export'
  681. for key, value in environ.iteritems():
  682. fd.write('%s %s=%s\n' % (expCmd, key, value))
  683. # write also skipped lines
  684. for line in lineSkipped:
  685. fd.write(line + os.linesep)
  686. fd.close()
  687. def SetAddOnPath(addonPath = None, key = 'PATH'):
  688. """!Set default AddOn path
  689. @addonPath path to addons (None for default)
  690. @key env key - 'PATH' or 'BASE'
  691. """
  692. gVersion = grass.version()['version'].split('.', 1)[0]
  693. # update env file
  694. if not addonPath:
  695. if sys.platform != 'win32':
  696. addonPath = os.path.join(os.path.join(os.getenv('HOME'),
  697. '.grass%s' % gVersion,
  698. 'addons'))
  699. else:
  700. addonPath = os.path.join(os.path.join(os.getenv('APPDATA'),
  701. 'GRASS%s' % gVersion,
  702. 'addons'))
  703. StoreEnvVariable(key = 'GRASS_ADDON_' + key, value = addonPath)
  704. os.environ['GRASS_ADDON_' + key] = addonPath
  705. # From lib/gis/col_str.c, except purple which is mentioned
  706. # there but not given RGB values
  707. str2rgb = {'aqua': (100, 128, 255),
  708. 'black': (0, 0, 0),
  709. 'blue': (0, 0, 255),
  710. 'brown': (180, 77, 25),
  711. 'cyan': (0, 255, 255),
  712. 'gray': (128, 128, 128),
  713. 'green': (0, 255, 0),
  714. 'grey': (128, 128, 128),
  715. 'indigo': (0, 128, 255),
  716. 'magenta': (255, 0, 255),
  717. 'orange': (255, 128, 0),
  718. 'purple': (128, 0, 128),
  719. 'red': (255, 0, 0),
  720. 'violet': (128, 0, 255),
  721. 'white': (255, 255, 255),
  722. 'yellow': (255, 255, 0)}
  723. rgb2str = {}
  724. for (s,r) in str2rgb.items():
  725. rgb2str[ r ] = s
  726. def color_resolve(color):
  727. if len(color) > 0 and color[0] in "0123456789":
  728. rgb = tuple(map(int, color.split(':')))
  729. label = color
  730. else:
  731. # Convert color names to RGB
  732. try:
  733. rgb = str2rgb[color]
  734. label = color
  735. except KeyError:
  736. rgb = (200, 200, 200)
  737. label = _('Select Color')
  738. return (rgb, label)