utils.py 32 KB

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