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