utils.py 28 KB

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