grass.py 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236
  1. #!/usr/bin/env python
  2. #############################################################################
  3. #
  4. # MODULE: GRASS initialization script
  5. # AUTHOR(S): Original author unknown - probably CERL
  6. # Andreas Lange <andreas.lange rhein-main.de>
  7. # Huidae Cho <grass4u gmail.com>
  8. # Justin Hickey <jhickey hpcc.nectec.or.th>
  9. # Markus Neteler <neteler osgeo.org>
  10. # Hamish Bowman <hamish_b yahoo.com>
  11. #
  12. # GRASS 7: converted to Python (based on init.sh shell
  13. # script from GRASS 6) by Glynn Clements
  14. # Martin Landa <landa.martin gmail.com>
  15. # Luca Delucchi <lucadeluge gmail.com>
  16. # Vaclav Petras <wenzeslaus gmail.com> (refactoring and exec)
  17. # PURPOSE: Sets up environment variables, parses any remaining
  18. # command line options for setting the GISDBASE, LOCATION,
  19. # and/or MAPSET. Finally it starts GRASS with the appropriate
  20. # user interface and cleans up after it is finished.
  21. # COPYRIGHT: (C) 2000-2018 by the GRASS Development Team
  22. #
  23. # This program is free software under the GNU General
  24. # Public License (>=v2). Read the file COPYING that
  25. # comes with GRASS for details.
  26. #
  27. #############################################################################
  28. """
  29. Script to run GRASS session.
  30. Some of the functions could be used separately but import from this module
  31. is not safe, i.e. it has side effects (this should be changed in the future).
  32. """
  33. # we allow for long file because we want to avoid imports if possible
  34. # (this makes it more stable since we have to set up paths first)
  35. # pylint: disable=too-many-lines
  36. from __future__ import print_function
  37. import sys
  38. import os
  39. import atexit
  40. import string
  41. import subprocess
  42. import re
  43. import platform
  44. import tempfile
  45. import locale
  46. # ----+- Python 3 compatibility start -+----
  47. PY2 = sys.version[0] == '2'
  48. ENCODING = locale.getdefaultlocale()[1]
  49. if ENCODING is None:
  50. ENCODING = 'UTF-8'
  51. print("Default locale not found, using UTF-8") # intentionally not translatable
  52. def decode(bytes_, encoding=None):
  53. """Decode bytes with default locale and return (unicode) string
  54. Adapted from lib/python/core/utils.py
  55. No-op if parameter is not bytes (assumed unicode string).
  56. :param bytes bytes_: the bytes to decode
  57. :param encoding: encoding to be used, default value is None
  58. """
  59. if sys.version_info.major >= 3:
  60. unicode = str
  61. if isinstance(bytes_, unicode):
  62. return bytes_
  63. elif isinstance(bytes_, bytes):
  64. if encoding is None:
  65. enc = ENCODING
  66. else:
  67. enc = encoding
  68. return bytes_.decode(enc)
  69. else:
  70. # if something else than text
  71. raise TypeError("can only accept types str and bytes")
  72. def encode(string, encoding=None):
  73. """Encode string with default locale and return bytes with that encoding
  74. Adapted from lib/python/core/utils.py
  75. No-op if parameter is bytes (assumed already encoded).
  76. This ensures garbage in, garbage out.
  77. :param str string: the string to encode
  78. :param encoding: encoding to be used, default value is None
  79. """
  80. if sys.version_info.major >= 3:
  81. unicode = str
  82. if isinstance(string, bytes):
  83. return string
  84. # this also tests str in Py3:
  85. elif isinstance(string, unicode):
  86. if encoding is None:
  87. enc = ENCODING
  88. else:
  89. enc = encoding
  90. return string.encode(enc)
  91. else:
  92. # if something else than text
  93. raise TypeError("can only accept types str and bytes")
  94. # currently not used, see https://trac.osgeo.org/grass/ticket/3508
  95. def to_text_string(obj, encoding=ENCODING):
  96. """Convert `obj` to (unicode) text string"""
  97. if PY2:
  98. # Python 2
  99. return encode(obj, encoding=encoding)
  100. else:
  101. # Python 3
  102. return decode(obj, encoding=encoding)
  103. if PY2:
  104. import types
  105. string_types = basestring,
  106. integer_types = (int, long)
  107. class_types = (type, types.ClassType)
  108. text_type = unicode
  109. binary_type = str
  110. else:
  111. string_types = str,
  112. integer_types = int,
  113. class_types = type,
  114. text_type = str
  115. binary_type = bytes
  116. MAXSIZE = sys.maxsize
  117. # ----+- Python 3 compatibility end -+----
  118. # Variables substituted during build process
  119. if 'GISBASE' in os.environ:
  120. # TODO: should this be something like GRASS_PATH?
  121. # GISBASE marks complete runtime, so no need to get it here when
  122. # setting it up, possible scenario: existing runtime and starting
  123. # GRASS in that, we want to overwrite the settings, not to take it
  124. # possibly same for GRASS_PROJSHARE and others but maybe not
  125. gisbase = os.environ['GISBASE']
  126. else:
  127. gisbase = "@GISBASE@"
  128. cmd_name = "@START_UP@"
  129. grass_version = "@GRASS_VERSION_NUMBER@"
  130. ld_library_path_var = '@LD_LIBRARY_PATH_VAR@'
  131. if 'GRASS_PROJSHARE' in os.environ:
  132. config_projshare = os.environ['GRASS_PROJSHARE']
  133. else:
  134. config_projshare = "@CONFIG_PROJSHARE@"
  135. gisbase = os.path.normpath(gisbase)
  136. # i18N
  137. import gettext
  138. # TODO: is this needed or even desirable when we have set_language()?
  139. gettext.install('grasslibs', os.path.join(gisbase, 'locale'))
  140. def warning(text):
  141. sys.stderr.write(_("WARNING") + ': ' + text + os.linesep)
  142. def try_remove(path):
  143. try:
  144. os.remove(path)
  145. except:
  146. pass
  147. def try_rmdir(path):
  148. try:
  149. os.rmdir(path)
  150. except:
  151. pass
  152. def clean_env(gisrc):
  153. env_curr = read_gisrc(gisrc)
  154. env_new = {}
  155. for k, v in env_curr.items():
  156. if k.endswith('PID') or k.startswith('MONITOR'):
  157. continue
  158. env_new[k] = v
  159. write_gisrc(env_new, gisrc)
  160. def cleanup_dir(path):
  161. if not path:
  162. return
  163. for root, dirs, files in os.walk(path, topdown=False):
  164. for name in files:
  165. try_remove(os.path.join(root, name))
  166. for name in dirs:
  167. try_rmdir(os.path.join(root, name))
  168. class Cleaner(object): # pylint: disable=R0903
  169. """Holds directories and files which needs to be cleaned or deleted"""
  170. def __init__(self):
  171. self.tmpdir = None
  172. def cleanup(self):
  173. """This can be registered with atexit
  174. Object can then still change and add or remove directories to clean"""
  175. # all exits after setting up tmp dirs (system/location) should
  176. # also tidy it up
  177. cleanup_dir(self.tmpdir)
  178. try_rmdir(self.tmpdir)
  179. def fatal(msg):
  180. sys.stderr.write("%s: " % _('ERROR') + msg + os.linesep)
  181. sys.exit(_("Exiting..."))
  182. def message(msg):
  183. sys.stderr.write(msg + "\n")
  184. sys.stderr.flush()
  185. # mechanism meant for debugging this script (only)
  186. # private global to store if we are debugging
  187. _DEBUG = None
  188. def is_debug():
  189. """Returns True if we are in debug mode
  190. For debug messages use ``debug()``.
  191. """
  192. global _DEBUG
  193. if _DEBUG is not None:
  194. return _DEBUG
  195. _DEBUG = os.getenv('GRASS_DEBUG')
  196. # translate to bool (no or empty variable means false)
  197. if _DEBUG:
  198. _DEBUG = True
  199. else:
  200. _DEBUG = False
  201. return _DEBUG
  202. def debug(msg):
  203. """Print a debug message if in debug mode
  204. Do not use translatable strings for debug messages.
  205. """
  206. if is_debug():
  207. sys.stderr.write("DEBUG: %s\n" % msg)
  208. sys.stderr.flush()
  209. def readfile(path):
  210. debug("Reading %s" % path)
  211. f = open(path, 'r')
  212. s = f.read()
  213. f.close()
  214. return s
  215. def writefile(path, s):
  216. debug("Writing %s" % path)
  217. f = open(path, 'w')
  218. f.write(s)
  219. f.close()
  220. def call(cmd, **kwargs):
  221. """Wrapper for subprocess.call to deal with platform-specific issues"""
  222. if windows:
  223. kwargs['shell'] = True
  224. return subprocess.call(cmd, **kwargs)
  225. def Popen(cmd, **kwargs): # pylint: disable=C0103
  226. """Wrapper for subprocess.Popen to deal with platform-specific issues"""
  227. if windows:
  228. kwargs['shell'] = True
  229. return subprocess.Popen(cmd, **kwargs)
  230. def gpath(*args):
  231. """Costruct path to file or directory in GRASS GIS installation
  232. Can be called only after gisbase was set.
  233. """
  234. return os.path.join(gisbase, *args)
  235. # for wxpath
  236. _WXPYTHON_BASE = None
  237. def wxpath(*args):
  238. """Costruct path to file or directory in GRASS wxGUI
  239. Can be called only after gisbase was set.
  240. This function does not check if the directories exist or if GUI works
  241. this must be done by the caller if needed.
  242. """
  243. global _WXPYTHON_BASE
  244. if not _WXPYTHON_BASE:
  245. # this can be called only after gisbase was set
  246. _WXPYTHON_BASE = gpath("gui", "wxpython")
  247. return os.path.join(_WXPYTHON_BASE, *args)
  248. # using format for most but leaving usage of template for the dynamic ones
  249. # two different methods are easy way to implement two phase construction
  250. help_text = r"""GRASS GIS $VERSION_NUMBER
  251. Geographic Resources Analysis Support System (GRASS GIS).
  252. {usage}:
  253. $CMD_NAME [-h | --help] [-v | --version]
  254. [-c | -c geofile | -c EPSG:code[:datum_trans] | -c XY]
  255. [-e] [-f] [--text | --gtext | --gui] [--config param]
  256. [[[GISDBASE/]LOCATION/]MAPSET]
  257. $CMD_NAME [FLAG]... GISDBASE/LOCATION/MAPSET --exec EXECUTABLE [EPARAM]...
  258. $CMD_NAME --tmp-location [geofile | EPSG | XY] --exec EXECUTABLE [EPARAM]...
  259. {flags}:
  260. -h or --help {help_flag}
  261. -v or --version {version_flag}
  262. -c {create}
  263. -e {exit_after}
  264. -f {force_removal}
  265. --text {text}
  266. {text_detail}
  267. --gtext {gtext}
  268. {gtext_detail}
  269. --gui {gui}
  270. {gui_detail}
  271. --config {config}
  272. {config_detail}
  273. --exec EXECUTABLE {exec_}
  274. {exec_detail}
  275. --tmp-location {tmp_location}
  276. {params}:
  277. GISDBASE {gisdbase}
  278. {gisdbase_detail}
  279. LOCATION {location}
  280. {location_detail}
  281. MAPSET {mapset}
  282. GISDBASE/LOCATION/MAPSET {full_mapset}
  283. EXECUTABLE {executable}
  284. EPARAM {executable_params}
  285. FLAG {standard_flags}
  286. {env_vars}:
  287. GRASS_GUI {gui_var}
  288. GRASS_HTML_BROWSER {html_var}
  289. GRASS_ADDON_PATH {addon_path_var}
  290. GRASS_ADDON_BASE {addon_base_var}
  291. GRASS_BATCH_JOB {batch_var}
  292. GRASS_PYTHON {python_var}
  293. """.format(
  294. usage=_("Usage"),
  295. flags=_("Flags"),
  296. help_flag=_("print this help message"),
  297. version_flag=_("show version information and exit"),
  298. create=_("create given database, location or mapset if it doesn't exist"),
  299. exit_after=_("exit after creation of location or mapset. Only with -c flag"),
  300. force_removal=_("force removal of .gislock if exists (use with care!). Only with --text flag"),
  301. text=_("use text based interface (skip welcome screen)"),
  302. text_detail=_("and set as default"),
  303. gtext=_("use text based interface (show welcome screen)"),
  304. gtext_detail=_("and set as default"),
  305. gui=_("use $DEFAULT_GUI graphical user interface"),
  306. gui_detail=_("and set as default"),
  307. config=_("print GRASS configuration parameters"),
  308. config_detail=_("options: arch,build,compiler,path,revision,version"),
  309. params=_("Parameters"),
  310. gisdbase=_("initial GRASS GIS database directory"),
  311. gisdbase_detail=_("directory containing Locations"),
  312. location=_("initial GRASS Location"),
  313. location_detail=_("directory containing Mapsets with one common coordinate system (projection)"),
  314. mapset=_("initial GRASS Mapset"),
  315. full_mapset=_("fully qualified initial Mapset directory"),
  316. env_vars=_("Environment variables relevant for startup"),
  317. gui_var=_("select GUI (text, gui, gtext)"),
  318. html_var=_("set html web browser for help pages"),
  319. addon_path_var=_("set additional path(s) to local GRASS modules or user scripts"),
  320. addon_base_var=_("set additional GISBASE for locally installed GRASS Addons"),
  321. batch_var=_("shell script to be processed as batch job"),
  322. python_var=_("set Python interpreter name to override 'python'"),
  323. exec_=_("execute GRASS module or script"),
  324. exec_detail=_("provided executable will be executed in GRASS session"),
  325. executable=_("GRASS module, script or any other executable"),
  326. executable_params=_("parameters of the executable"),
  327. standard_flags=_("standard flags"),
  328. tmp_location=_("create temporary location (use with the --exec flag)"),
  329. )
  330. def help_message(default_gui):
  331. t = string.Template(help_text)
  332. s = t.substitute(CMD_NAME=cmd_name, DEFAULT_GUI=default_gui,
  333. VERSION_NUMBER=grass_version)
  334. sys.stderr.write(s)
  335. def get_grass_config_dir():
  336. """Get configuration directory
  337. Determines path of GRASS GIS user configuration directory and creates
  338. it if it does not exist.
  339. Configuration directory is for example used for grass env file
  340. (the one which caries mapset settings from session to session).
  341. """
  342. if sys.platform == 'win32':
  343. grass_config_dirname = "GRASS7"
  344. win_conf_path = os.getenv('APPDATA')
  345. # this can happen with some strange settings
  346. if not win_conf_path:
  347. fatal(_("The APPDATA variable is not set, ask your operating"
  348. " system support"))
  349. if not os.path.exists(win_conf_path):
  350. fatal(_("The APPDATA variable points to directory which does"
  351. " not exist, ask your operating system support"))
  352. directory = os.path.join(win_conf_path, grass_config_dirname)
  353. else:
  354. grass_config_dirname = ".grass7"
  355. directory = os.path.join(os.getenv('HOME'), grass_config_dirname)
  356. if not os.path.exists(directory):
  357. os.mkdir(directory)
  358. return directory
  359. def create_tmp(user, gis_lock):
  360. """Create temporary directory
  361. :param user: user name to be used in the directory name
  362. :param gis_lock: session lock filename to be used in the directory name
  363. """
  364. # use $TMPDIR if it exists, then $TEMP, otherwise /tmp
  365. tmp = os.getenv('TMPDIR')
  366. if not tmp:
  367. tmp = os.getenv('TEMP')
  368. if not tmp:
  369. tmp = os.getenv('TMP')
  370. if not tmp:
  371. tmp = tempfile.gettempdir()
  372. if tmp:
  373. tmpdir = os.path.join(
  374. tmp, "grass7-%(user)s-%(lock)s" % {'user': user,
  375. 'lock': gis_lock})
  376. try:
  377. os.mkdir(tmpdir, 0o700)
  378. except:
  379. tmp = None
  380. if not tmp:
  381. for ttmp in ("/tmp", "/var/tmp", "/usr/tmp"):
  382. tmp = ttmp
  383. tmpdir = os.path.join(
  384. tmp, "grass7-%(user)s-%(lock)s" % {'user': user,
  385. 'lock': gis_lock})
  386. try:
  387. os.mkdir(tmpdir, 0o700)
  388. except:
  389. tmp = None
  390. if tmp:
  391. break
  392. if not tmp:
  393. fatal(_("Unable to create temporary directory <grass7-%(user)s-"
  394. "%(lock)s>! Exiting.") % {'user': user, 'lock': gis_lock})
  395. # promoting the variable even if it was not defined before
  396. os.environ['TMPDIR'] = tmpdir
  397. debug("Tmp directory '{tmpdir}' created for user '{user}'".format(
  398. tmpdir=tmpdir, user=user))
  399. return tmpdir
  400. def get_gisrc_from_config_dir(grass_config_dir, batch_job):
  401. """Set the global grassrc file (aka grassrcrc)"""
  402. if batch_job:
  403. # use individual GISRCRC files when in batch mode (r33174)
  404. filename = os.path.join(grass_config_dir, "rc.%s" % platform.node())
  405. if os.access(filename, os.R_OK):
  406. return filename
  407. # use standard file if in normal mode or the special file is not available
  408. return os.path.join(grass_config_dir, "rc")
  409. def create_gisrc(tmpdir, gisrcrc):
  410. # Set the session grassrc file
  411. gisrc = os.path.join(tmpdir, "gisrc")
  412. os.environ['GISRC'] = gisrc
  413. # remove invalid GISRC file to avoid disturbing error messages:
  414. try:
  415. s = readfile(gisrcrc)
  416. if "UNKNOWN" in s:
  417. try_remove(gisrcrc)
  418. s = None
  419. except:
  420. s = None
  421. # Copy the global grassrc file to the session grassrc file
  422. if s:
  423. writefile(gisrc, s)
  424. return gisrc
  425. def read_gisrc(filename):
  426. kv = {}
  427. try:
  428. f = open(filename, 'r')
  429. except IOError:
  430. return kv
  431. for line in f:
  432. try:
  433. k, v = line.split(':', 1)
  434. except ValueError as e:
  435. warning(_("Invalid line in RC file ({file}):"
  436. " '{line}' ({error})\n").format(
  437. line=line, error=e, file=filename))
  438. continue
  439. kv[k.strip()] = v.strip()
  440. if not kv:
  441. warning(_("Empty RC file ({file})").format(file=filename))
  442. f.close()
  443. return kv
  444. def read_env_file(path):
  445. kv = {}
  446. f = open(path, 'r')
  447. for line in f:
  448. k, v = line.split(':', 1)
  449. kv[k.strip()] = v.strip()
  450. f.close()
  451. return kv
  452. def write_gisrc(kv, filename):
  453. f = open(filename, 'w')
  454. for k, v in kv.items():
  455. f.write("%s: %s\n" % (k, v))
  456. f.close()
  457. def read_gui(gisrc, default_gui):
  458. grass_gui = None
  459. # At this point the GRASS user interface variable has been set from the
  460. # command line, been set from an external environment variable,
  461. # or is not set. So we check if it is not set
  462. # Check for a reference to the GRASS user interface in the grassrc file
  463. if os.access(gisrc, os.R_OK):
  464. kv = read_gisrc(gisrc)
  465. if 'GRASS_GUI' in os.environ:
  466. grass_gui = os.environ['GRASS_GUI']
  467. elif 'GUI' in kv:
  468. grass_gui = kv['GUI']
  469. elif 'GRASS_GUI' in kv:
  470. # For backward compatibility (GRASS_GUI renamed to GUI)
  471. grass_gui = kv['GRASS_GUI']
  472. else:
  473. # Set the GRASS user interface to the default if needed
  474. grass_gui = default_gui
  475. if not grass_gui:
  476. grass_gui = default_gui
  477. if grass_gui == 'gui':
  478. grass_gui = default_gui
  479. # FIXME oldtcltk, gis.m, d.m no longer exist (remove this around 7.2)
  480. if grass_gui in ['d.m', 'gis.m', 'oldtcltk', 'tcltk']:
  481. warning(_("GUI <%s> not supported in this version") % grass_gui)
  482. grass_gui = default_gui
  483. return grass_gui
  484. def path_prepend(directory, var):
  485. path = os.getenv(var)
  486. if path:
  487. path = directory + os.pathsep + path
  488. else:
  489. path = directory
  490. os.environ[var] = path
  491. def path_append(directory, var):
  492. path = os.getenv(var)
  493. if path:
  494. path = path + os.pathsep + directory
  495. else:
  496. path = directory
  497. os.environ[var] = path
  498. def set_paths(grass_config_dir):
  499. # addons (path)
  500. addon_path = os.getenv('GRASS_ADDON_PATH')
  501. if addon_path:
  502. for path in addon_path.split(os.pathsep):
  503. path_prepend(addon_path, 'PATH')
  504. # addons (base)
  505. addon_base = os.getenv('GRASS_ADDON_BASE')
  506. if not addon_base:
  507. addon_base = os.path.join(grass_config_dir, 'addons')
  508. os.environ['GRASS_ADDON_BASE'] = addon_base
  509. if not windows:
  510. path_prepend(os.path.join(addon_base, 'scripts'), 'PATH')
  511. path_prepend(os.path.join(addon_base, 'bin'), 'PATH')
  512. # standard installation
  513. if not windows:
  514. path_prepend(gpath('scripts'), 'PATH')
  515. path_prepend(gpath('bin'), 'PATH')
  516. # Set PYTHONPATH to find GRASS Python modules
  517. if os.path.exists(gpath('etc', 'python')):
  518. path_prepend(gpath('etc', 'python'), 'PYTHONPATH')
  519. # set path for the GRASS man pages
  520. grass_man_path = gpath('docs', 'man')
  521. addons_man_path = os.path.join(addon_base, 'docs', 'man')
  522. man_path = os.getenv('MANPATH')
  523. sys_man_path = None
  524. if man_path:
  525. path_prepend(addons_man_path, 'MANPATH')
  526. path_prepend(grass_man_path, 'MANPATH')
  527. else:
  528. try:
  529. nul = open(os.devnull, 'w')
  530. p = Popen(['manpath'], stdout=subprocess.PIPE, stderr=nul)
  531. nul.close()
  532. s = p.stdout.read()
  533. p.wait()
  534. sys_man_path = s.strip()
  535. except:
  536. pass
  537. if sys_man_path:
  538. os.environ['MANPATH'] = to_text_string(sys_man_path)
  539. path_prepend(addons_man_path, 'MANPATH')
  540. path_prepend(grass_man_path, 'MANPATH')
  541. else:
  542. os.environ['MANPATH'] = to_text_string(addons_man_path)
  543. path_prepend(grass_man_path, 'MANPATH')
  544. # Set LD_LIBRARY_PATH (etc) to find GRASS shared libraries
  545. # this works for subprocesses but won't affect the current process
  546. path_prepend(gpath("lib"), ld_library_path_var)
  547. def find_exe(pgm):
  548. for directory in os.getenv('PATH').split(os.pathsep):
  549. path = os.path.join(directory, pgm)
  550. if os.access(path, os.X_OK):
  551. return path
  552. return None
  553. def set_defaults():
  554. # GRASS_PAGER
  555. if not os.getenv('GRASS_PAGER'):
  556. if find_exe("more"):
  557. pager = "more"
  558. elif find_exe("less"):
  559. pager = "less"
  560. elif windows:
  561. pager = "more"
  562. else:
  563. pager = "cat"
  564. os.environ['GRASS_PAGER'] = pager
  565. # GRASS_PYTHON
  566. if not os.getenv('GRASS_PYTHON'):
  567. if windows:
  568. os.environ['GRASS_PYTHON'] = "python.exe"
  569. else:
  570. os.environ['GRASS_PYTHON'] = "python"
  571. # GRASS_GNUPLOT
  572. if not os.getenv('GRASS_GNUPLOT'):
  573. os.environ['GRASS_GNUPLOT'] = "gnuplot -persist"
  574. # GRASS_PROJSHARE
  575. if not os.getenv('GRASS_PROJSHARE'):
  576. os.environ['GRASS_PROJSHARE'] = config_projshare
  577. def set_display_defaults():
  578. """ Predefine monitor size for certain architectures"""
  579. if os.getenv('HOSTTYPE') == 'arm':
  580. # small monitor on ARM (iPAQ, zaurus... etc)
  581. os.environ['GRASS_RENDER_HEIGHT'] = "320"
  582. os.environ['GRASS_RENDER_WIDTH'] = "240"
  583. def set_browser():
  584. # GRASS_HTML_BROWSER
  585. browser = os.getenv('GRASS_HTML_BROWSER')
  586. if not browser:
  587. if macosx:
  588. # OSX doesn't execute browsers from the shell PATH - route through a
  589. # script
  590. browser = gpath('etc', "html_browser_mac.sh")
  591. os.environ['GRASS_HTML_BROWSER_MACOSX'] = "-b com.apple.helpviewer"
  592. if windows:
  593. browser = "start"
  594. elif cygwin:
  595. browser = "explorer"
  596. else:
  597. # the usual suspects
  598. browsers = ["xdg-open", "x-www-browser", "htmlview", "konqueror", "mozilla",
  599. "mozilla-firefox", "firefox", "iceweasel", "opera",
  600. "netscape", "dillo", "lynx", "links", "w3c"]
  601. for b in browsers:
  602. if find_exe(b):
  603. browser = b
  604. break
  605. elif macosx:
  606. # OSX doesn't execute browsers from the shell PATH - route through a
  607. # script
  608. os.environ['GRASS_HTML_BROWSER_MACOSX'] = "-b %s" % browser
  609. browser = gpath('etc', "html_browser_mac.sh")
  610. if not browser:
  611. warning(_("Searched for a web browser, but none found"))
  612. # even so we set konqueror to make lib/gis/parser.c happy:
  613. # TODO: perhaps something more probable would be better, e.g. xdg-open
  614. browser = "konqueror"
  615. os.environ['GRASS_HTML_BROWSER'] = browser
  616. def ensure_home():
  617. """Set HOME if not set on MS Windows"""
  618. if windows and not os.getenv('HOME'):
  619. os.environ['HOME'] = os.path.join(os.getenv('HOMEDRIVE'),
  620. os.getenv('HOMEPATH'))
  621. def create_initial_gisrc(filename):
  622. # for convenience, define GISDBASE as pwd:
  623. s = r"""GISDBASE: %s
  624. LOCATION_NAME: <UNKNOWN>
  625. MAPSET: <UNKNOWN>
  626. """ % os.getcwd()
  627. writefile(filename, s)
  628. def check_gui(expected_gui):
  629. grass_gui = expected_gui
  630. # Check if we are running X windows by checking the DISPLAY variable
  631. if os.getenv('DISPLAY') or windows or macosx:
  632. # Check if python is working properly
  633. if expected_gui in ('wxpython', 'gtext'):
  634. nul = open(os.devnull, 'w')
  635. p = Popen([os.environ['GRASS_PYTHON']], stdin=subprocess.PIPE,
  636. stdout=nul, stderr=nul)
  637. nul.close()
  638. p.stdin.write("variable=True".encode(ENCODING))
  639. p.stdin.close()
  640. p.wait()
  641. msg = None
  642. if p.returncode != 0:
  643. # Python was not found - switch to text interface mode
  644. msg = _("The python command does not work as expected!\n"
  645. "Please check your GRASS_PYTHON environment variable.\n"
  646. "Use the -help option for details.\n")
  647. if not os.path.exists(wxpath("wxgui.py")):
  648. msg = _("GRASS GUI not found. Please check your installation.")
  649. if msg:
  650. warning(_("{}\nSwitching to text based interface mode.\n\n"
  651. "Hit RETURN to continue.\n").format(msg))
  652. sys.stdin.readline()
  653. grass_gui = 'text'
  654. else:
  655. # Display a message if a graphical interface was expected
  656. if expected_gui != 'text':
  657. # Set the interface mode to text
  658. warning(_("It appears that the X Windows system is not active.\n"
  659. "A graphical based user interface is not supported.\n"
  660. "(DISPLAY variable is not set.)\n"
  661. "Switching to text based interface mode.\n\n"
  662. "Hit RETURN to continue.\n"))
  663. sys.stdin.readline()
  664. grass_gui = 'text'
  665. return grass_gui
  666. def save_gui(gisrc, grass_gui):
  667. """Save the user interface variable in the grassrc file"""
  668. if os.access(gisrc, os.F_OK):
  669. kv = read_gisrc(gisrc)
  670. kv['GUI'] = grass_gui
  671. write_gisrc(kv, gisrc)
  672. def create_location(gisdbase, location, geostring):
  673. """Create GRASS Location using georeferenced file or EPSG
  674. EPSG code format is ``EPSG:code`` or ``EPSG:code:datum_trans``.
  675. :param gisdbase: Path to GRASS GIS database directory
  676. :param location: name of new Location
  677. :param geostring: path to a georeferenced file or EPSG code
  678. """
  679. if gpath('etc', 'python') not in sys.path:
  680. sys.path.append(gpath('etc', 'python'))
  681. from grass.script import core as gcore # pylint: disable=E0611
  682. try:
  683. if geostring and geostring.upper().find('EPSG:') > -1:
  684. # create location using EPSG code
  685. epsg = geostring.split(':', 1)[1]
  686. if ':' in epsg:
  687. epsg, datum_trans = epsg.split(':', 1)
  688. else:
  689. datum_trans = None
  690. gcore.create_location(gisdbase, location,
  691. epsg=epsg, datum_trans=datum_trans)
  692. elif geostring == 'XY':
  693. # create an XY location
  694. gcore.create_location(gisdbase, location)
  695. else:
  696. # create location using georeferenced file
  697. gcore.create_location(gisdbase, location,
  698. filename=geostring)
  699. except gcore.ScriptError as err:
  700. fatal(err.value.strip('"').strip("'").replace('\\n', os.linesep))
  701. # TODO: distinguish between valid for getting maps and usable as current
  702. # https://lists.osgeo.org/pipermail/grass-dev/2016-September/082317.html
  703. # interface created according to the current usage
  704. def is_mapset_valid(full_mapset):
  705. """Return True if GRASS Mapset is valid"""
  706. # WIND is created from DEFAULT_WIND by `g.region -d` and functions
  707. # or modules which create a new mapset. Most modules will fail if
  708. # WIND doesn't exist (assuming that neither GRASS_REGION nor
  709. # WIND_OVERRIDE environmental variables are set).
  710. return os.access(os.path.join(full_mapset, "WIND"), os.R_OK)
  711. def is_location_valid(gisdbase, location):
  712. """Return True if GRASS Location is valid
  713. :param gisdbase: Path to GRASS GIS database directory
  714. :param location: name of a Location
  715. """
  716. # DEFAULT_WIND file should not be required until you do something
  717. # that actually uses them. The check is just a heuristic; a directory
  718. # containing a PERMANENT/DEFAULT_WIND file is probably a GRASS
  719. # location, while a directory lacking it probably isn't.
  720. return os.access(os.path.join(gisdbase, location,
  721. "PERMANENT", "DEFAULT_WIND"), os.F_OK)
  722. # basically checking location, possibly split into two functions
  723. # (mapset one can call location one)
  724. def get_mapset_invalid_reason(gisdbase, location, mapset):
  725. """Returns a message describing what is wrong with the Mapset
  726. The goal is to provide the most suitable error message
  727. (rather than to do a quick check).
  728. :param gisdbase: Path to GRASS GIS database directory
  729. :param location: name of a Location
  730. :param mapset: name of a Mapset
  731. :returns: translated message
  732. """
  733. full_location = os.path.join(gisdbase, location)
  734. full_permanent = os.path.join(full_location, 'PERMANENT')
  735. full_mapset = os.path.join(full_location, mapset)
  736. # first checking the location validity
  737. if not os.path.exists(full_location):
  738. return _("Location <%s> doesn't exist") % full_location
  739. elif 'PERMANENT' not in os.listdir(full_location):
  740. return _("<%s> is not a valid GRASS Location"
  741. " because PERMANENT Mapset is missing") % full_location
  742. elif not os.path.isdir(full_permanent):
  743. return _("<%s> is not a valid GRASS Location"
  744. " because PERMANENT is not a directory") % full_location
  745. # partially based on the is_location_valid() function
  746. elif not os.path.isfile(os.path.join(full_permanent,
  747. 'DEFAULT_WIND')):
  748. return _("<%s> is not a valid GRASS Location"
  749. " because PERMANENT Mapset does not have a DEFAULT_WIND file"
  750. " (default computational region)") % full_location
  751. # if location is valid, check mapset
  752. elif mapset not in os.listdir(full_location):
  753. return _("Mapset <{mapset}> doesn't exist in GRASS Location <{loc}>. "
  754. "A new mapset can be created by '-c' switch.").format(
  755. mapset=mapset, loc=location)
  756. elif not os.path.isdir(full_mapset):
  757. return _("<%s> is not a GRASS Mapset"
  758. " because it is not a directory") % mapset
  759. elif not os.path.isfile(os.path.join(full_mapset, 'WIND')):
  760. return _("<%s> is not a valid GRASS Mapset"
  761. " because it does not have a WIND file") % mapset
  762. # based on the is_mapset_valid() function
  763. elif not os.access(os.path.join(full_mapset, "WIND"), os.R_OK):
  764. return _("<%s> is not a valid GRASS Mapset"
  765. " because its WIND file is not readable") % mapset
  766. else:
  767. return _("Mapset <{mapset}> or Location <{location}> is"
  768. " invalid for an unknown reason").format(
  769. mapset=mapset, loc=location)
  770. def can_create_location(gisdbase, location):
  771. """Checks if location can be created"""
  772. path = os.path.join(gisdbase, location)
  773. if os.path.exists(path):
  774. return False
  775. return True
  776. def cannot_create_location_reason(gisdbase, location):
  777. """Returns a message describing why location cannot be created
  778. The goal is to provide the most suitable error message
  779. (rather than to do a quick check).
  780. :param gisdbase: Path to GRASS GIS database directory
  781. :param location: name of a Location
  782. :returns: translated message
  783. """
  784. path = os.path.join(gisdbase, location)
  785. if is_location_valid(gisdbase, location):
  786. return _("Unable to create new location because"
  787. " the location <{location}>"
  788. " already exists.").format(**locals())
  789. elif os.path.isfile(path):
  790. return _("Unable to create new location <{location}> because"
  791. " <{path}> is a file.").format(**locals())
  792. elif os.path.isdir(path):
  793. return _("Unable to create new location <{location}> because"
  794. " the directory <{path}>"
  795. " already exists.").format(**locals())
  796. else:
  797. return _("Unable to create new location in"
  798. " the directory <{path}>"
  799. " for an unknown reason.").format(**locals())
  800. def set_mapset(gisrc, arg=None, geofile=None, create_new=False,
  801. tmp_location=False, tmpdir=None):
  802. """Selected Location and Mapset are checked and created if requested
  803. The gisrc (GRASS environment file) is written at the end
  804. (nothing is returned).
  805. tmp_location requires tmpdir (which is used as gisdbase)
  806. """
  807. # TODO: arg param seems to be always the mapset parameter (or a dash
  808. # in a distant past), refactor
  809. l = arg
  810. if l:
  811. if l == '.':
  812. l = os.getcwd()
  813. elif not os.path.isabs(l):
  814. l = os.path.abspath(l)
  815. l, mapset = os.path.split(l)
  816. if not mapset:
  817. l, mapset = os.path.split(l)
  818. l, location_name = os.path.split(l)
  819. gisdbase = l
  820. # all was None for tmp loc so that case goes here quickly
  821. # TODO: but the above code needs review anyway
  822. if tmp_location:
  823. # set gisdbase to temporary directory
  824. gisdbase = tmpdir
  825. # we are already in a unique directory, so we can use fixed name
  826. location_name = "tmploc"
  827. # we need only one mapset
  828. mapset = "PERMANENT"
  829. debug("Using temporary location <{gdb}{sep}{lc}>".format(
  830. gdb=gisdbase, lc=location_name, sep=os.path.sep))
  831. if gisdbase and location_name and mapset:
  832. path = os.path.join(gisdbase, location_name, mapset)
  833. # check if 'path' is a valid GRASS location/mapset
  834. path_is_valid_mapset = is_mapset_valid(path)
  835. if path_is_valid_mapset and create_new:
  836. warning(_("Mapset <{}> already exists. Ignoring the"
  837. " request to create it. Note that this warning"
  838. " may become an error in future versions.")
  839. .format(path))
  840. if not path_is_valid_mapset:
  841. if not create_new:
  842. # 'path' is not a valid mapset and user does not
  843. # want to create anything new
  844. fatal(get_mapset_invalid_reason(gisdbase, location_name, mapset))
  845. else:
  846. # 'path' is not valid and the user wants to create
  847. # mapset on the fly
  848. # check if 'location_name' is a valid GRASS location
  849. if not is_location_valid(gisdbase, location_name):
  850. if not tmp_location:
  851. # 'location_name' is not a valid GRASS location
  852. # and user requested its creation, so we parsed
  853. # the path wrong and need to move one level
  854. # and use 'PERMANENT' mapset
  855. # (we already got that right in case of tmploc)
  856. gisdbase = os.path.join(gisdbase, location_name)
  857. location_name = mapset
  858. mapset = "PERMANENT"
  859. if not can_create_location(gisdbase, location_name):
  860. fatal(cannot_create_location_reason(
  861. gisdbase, location_name))
  862. # create new location based on the provided EPSG/...
  863. message(_("Creating new GRASS GIS location <{}>...")
  864. .format(location_name))
  865. create_location(gisdbase, location_name, geofile)
  866. else:
  867. # 'location_name' is a valid GRASS location,
  868. # create new mapset
  869. message(_("Creating new GRASS GIS mapset <{}>...")
  870. .format(mapset))
  871. if os.path.isfile(path):
  872. # not a valid mapset, but dir exists, assuming
  873. # broken/incomplete mapset
  874. fatal(_("Unable to create new mapset <{mapset}>"
  875. " because <{path}> is a file.")
  876. .format(mapset=mapset, path=path))
  877. elif os.path.isdir(path):
  878. # not a valid mapset, but dir exists, assuming
  879. # broken/incomplete mapset
  880. warning(_("The mapset <{}> is missing the WIND file"
  881. " (computational region). It will be"
  882. " fixed now. Note that this warning"
  883. " may become an error in future versions.")
  884. .format(mapset))
  885. else:
  886. # create mapset directory
  887. os.mkdir(path)
  888. # make directory a mapset, add the region
  889. # copy PERMANENT/DEFAULT_WIND to <mapset>/WIND
  890. s = readfile(os.path.join(gisdbase, location_name,
  891. "PERMANENT", "DEFAULT_WIND"))
  892. writefile(os.path.join(path, "WIND"), s)
  893. if os.access(gisrc, os.R_OK):
  894. kv = read_gisrc(gisrc)
  895. else:
  896. kv = {}
  897. kv['GISDBASE'] = gisdbase
  898. kv['LOCATION_NAME'] = location_name
  899. kv['MAPSET'] = mapset
  900. write_gisrc(kv, gisrc)
  901. else:
  902. fatal(_("GRASS GIS database directory, location and mapset"
  903. " not set properly."
  904. " Use GUI or command line to set them."))
  905. def set_mapset_interactive(grass_gui):
  906. """User selects Location and Mapset in an interative way
  907. The gisrc (GRASS environment file) is written at the end.
  908. """
  909. if not os.path.exists(wxpath("gis_set.py")) and grass_gui != 'text':
  910. debug("No GUI available, switching to text mode")
  911. return False
  912. # Check for text interface
  913. if grass_gui == 'text':
  914. # TODO: maybe this should be removed and solved from outside
  915. # this depends on what we expect from this function
  916. # should gisrc be ok after running or is it allowed to be still not set
  917. pass
  918. # Check for GUI
  919. elif grass_gui in ('gtext', 'wxpython'):
  920. gui_startup(grass_gui)
  921. else:
  922. # Shouldn't need this but you never know
  923. fatal(_("Invalid user interface specified - <%s>. "
  924. "Use the --help option to see valid interface names.") % grass_gui)
  925. return True
  926. def gui_startup(grass_gui):
  927. """Start GUI for startup (setting gisrc file)"""
  928. if grass_gui in ('wxpython', 'gtext'):
  929. ret = call([os.getenv('GRASS_PYTHON'), wxpath("gis_set.py")])
  930. # this if could be simplified to three branches (0, 5, rest)
  931. # if there is no need to handle unknown code separately
  932. if ret == 0:
  933. pass
  934. elif ret in [1, 2]:
  935. # 1 probably error coming from gis_set.py
  936. # 2 probably file not found from python interpreter
  937. # formerly we were starting in text mode instead, now we just fail
  938. # which is more straightforward for everybody
  939. fatal(_("Error in GUI startup. See messages above (if any)"
  940. " and if necessary, please"
  941. " report this error to the GRASS developers.\n"
  942. "On systems with package manager, make sure you have the right"
  943. " GUI package, probably named grass-gui, installed.\n"
  944. "To run GRASS GIS in text mode use the --text flag.\n"
  945. "Use '--help' for further options\n"
  946. " {cmd_name} --help\n"
  947. "See also: https://grass.osgeo.org/{cmd_name}/manuals/helptext.html").format(
  948. cmd_name=cmd_name))
  949. elif ret == 5: # defined in gui/wxpython/gis_set.py
  950. # User wants to exit from GRASS
  951. message(_("Exit was requested in GUI.\nGRASS GIS will not start. Bye."))
  952. sys.exit(0)
  953. else:
  954. fatal(_("Invalid return code from GUI startup script.\n"
  955. "Please advise GRASS developers of this error."))
  956. # we don't follow the LOCATION_NAME legacy naming here but we have to still
  957. # translate to it, so always double check
  958. class MapsetSettings(object):
  959. """Holds GRASS GIS database directory, Location and Mapset
  960. Provides few convenient functions.
  961. """
  962. def __init__(self):
  963. self.gisdbase = None
  964. self.location = None
  965. self.mapset = None
  966. self._full_mapset = None
  967. # TODO: perhaps full_mapset would be better as mapset_path
  968. # TODO: works only when set for the first time
  969. # this follows the current usage but we must invalidate when
  970. # the others are changed (use properties for that)
  971. @property
  972. def full_mapset(self):
  973. if self._full_mapset is None:
  974. self._full_mapset = os.path.join(self.gisdbase, self.location,
  975. self.mapset)
  976. return self._full_mapset
  977. # TODO: perhaps conversion to bool would be nicer
  978. def is_valid(self):
  979. return self.gisdbase and self.location and self.mapset
  980. # TODO: does it really makes sense to tell user about gisrcrc?
  981. # anything could have happened in between loading from gisrcrc and now
  982. # (we do e.g. GUI or creating loctation)
  983. def load_gisrc(gisrc, gisrcrc):
  984. """Get the settings of Location and Mapset from the gisrc file
  985. :returns: MapsetSettings object
  986. """
  987. mapset_settings = MapsetSettings()
  988. kv = read_gisrc(gisrc)
  989. mapset_settings.gisdbase = kv.get('GISDBASE')
  990. mapset_settings.location = kv.get('LOCATION_NAME')
  991. mapset_settings.mapset = kv.get('MAPSET')
  992. if not mapset_settings.is_valid():
  993. fatal(_("Error reading data path information from g.gisenv.\n"
  994. "GISDBASE={gisbase}\n"
  995. "LOCATION_NAME={location}\n"
  996. "MAPSET={mapset}\n\n"
  997. "Check the <{file}> file.").format(
  998. gisbase=mapset_settings.gisdbase,
  999. location=mapset_settings.location,
  1000. mapset=mapset_settings.mapset,
  1001. file=gisrcrc))
  1002. return mapset_settings
  1003. # load environmental variables from grass_env_file
  1004. def load_env(grass_env_file):
  1005. if not os.access(grass_env_file, os.R_OK):
  1006. return
  1007. for line in readfile(grass_env_file).split(os.linesep):
  1008. try:
  1009. k, v = map(lambda x: x.strip(), line.strip().split(' ', 1)[1].split('=', 1))
  1010. except:
  1011. continue
  1012. debug("Environmental variable set {0}={1}".format(k, v))
  1013. os.environ[k] = v
  1014. # Allow for mixed ISIS-GRASS Environment
  1015. if os.getenv('ISISROOT'):
  1016. isis = os.getenv('ISISROOT')
  1017. os.environ['ISIS_LIB'] = isis + os.sep + "lib"
  1018. os.environ['ISIS_3RDPARTY'] = isis + os.sep + "3rdParty" + os.sep + "lib"
  1019. os.environ['QT_PLUGIN_PATH'] = isis + os.sep + "3rdParty" + os.sep + "plugins"
  1020. # os.environ['ISIS3DATA'] = isis + "$ISIS3DATA"
  1021. libpath = os.getenv('LD_LIBRARY_PATH', '')
  1022. isislibpath = os.getenv('ISIS_LIB')
  1023. isis3rdparty = os.getenv('ISIS_3RDPARTY')
  1024. os.environ['LD_LIBRARY_PATH'] = libpath + os.pathsep + isislibpath + os.pathsep + isis3rdparty
  1025. def set_language(grass_config_dir):
  1026. # This function is used to override system default language and locale
  1027. # Such override can be requested only from wxGUI
  1028. # An override if user has provided correct environmental variables as
  1029. # LC_MESSAGES or LANG is not necessary.
  1030. # Unfortunately currently a working solution for Windows is lacking
  1031. # thus it always on Vista and XP will print an error.
  1032. # See discussion for Windows not following its own documentation and
  1033. # not accepting ISO codes as valid locale identifiers http://bugs.python.org/issue10466
  1034. language = 'None' # Such string sometimes is present in wx file
  1035. encoding = None
  1036. # Override value is stored in wxGUI preferences file.
  1037. # As it's the only thing required, we'll just grep it out.
  1038. try:
  1039. fd = open(os.path.join(grass_config_dir, 'wx'), 'r')
  1040. except:
  1041. # Even if there is no override, we still need to set locale.
  1042. pass
  1043. else:
  1044. for line in fd:
  1045. if re.search('^language', line):
  1046. line = line.rstrip(' %s' % os.linesep)
  1047. language = ''.join(line.split(';')[-1:])
  1048. break
  1049. fd.close()
  1050. # Backwards compatability with old wx preferences files
  1051. if language == 'C':
  1052. language = 'en'
  1053. if language == 'None' or language == '' or not language:
  1054. # Language override is disabled (system language specified)
  1055. # As by default program runs with C locale, but users expect to
  1056. # have their default locale, we'll just set default locale
  1057. try:
  1058. locale.setlocale(locale.LC_ALL, '')
  1059. except locale.Error as e:
  1060. # If we get here, system locale settings are terribly wrong
  1061. # There is no point to continue as GRASS/Python will fail
  1062. # in some other unpredictable way.
  1063. sys.stderr.write(
  1064. "System locale is not usable (LC_ALL variable not defined)."
  1065. " Most likely it indicates misconfigured environment.\n")
  1066. sys.stderr.write("Reported error message: %s\n" % e)
  1067. # it would be too drastic to exit
  1068. # sys.exit("Fix system locale settings and then try again.")
  1069. locale.setlocale(locale.LC_ALL, 'C')
  1070. sys.stderr.write("Default locale settings are missing. GRASS running with C locale.")
  1071. language, encoding = locale.getdefaultlocale()
  1072. if not language:
  1073. sys.stderr.write("Default locale settings are missing. GRASS running with C locale.")
  1074. return
  1075. else:
  1076. debug("A language override has been requested."
  1077. " Trying to switch GRASS into '%s'..." % language)
  1078. try:
  1079. locale.setlocale(locale.LC_ALL, language)
  1080. except locale.Error as e:
  1081. try:
  1082. # Locale lang.encoding might be missing. Let's try
  1083. # UTF-8 encoding before giving up as on Linux systems
  1084. # lang.UTF-8 locales are more common than legacy
  1085. # ISO-8859 ones.
  1086. encoding = 'UTF-8'
  1087. normalized = locale.normalize('%s.%s' % (language, encoding))
  1088. locale.setlocale(locale.LC_ALL, normalized)
  1089. except locale.Error as e:
  1090. if language == 'en':
  1091. # A workaround for Python Issue30755
  1092. # https://bugs.python.org/issue30755
  1093. if locale.normalize('C.UTF-8') == 'en_US.UTF-8':
  1094. locale.setlocale(locale.LC_ALL, 'C')
  1095. os.environ['LANGUAGE'] = 'C'
  1096. os.environ['LANG'] = 'C'
  1097. os.environ['LC_MESSAGES'] = 'C'
  1098. os.environ['LC_NUMERIC'] = 'C'
  1099. os.environ['LC_TIME'] = 'C'
  1100. sys.stderr.write(
  1101. "To avoid Unicode errors in GUI, install"
  1102. " en_US.UTF-8 locale and restart GRASS.\n"
  1103. "Also consider upgrading your Python version"
  1104. " to one containing fix for Python Issue 30755.\n")
  1105. return
  1106. # en_US locale might be missing, still all messages in
  1107. # GRASS are already in en_US language.
  1108. # Using plain C as locale forces encodings to ascii
  1109. # thus lets try our luck with C.UTF-8 first.
  1110. # See bugs #3441 and #3423
  1111. try:
  1112. locale.setlocale(locale.LC_ALL, 'C.UTF-8')
  1113. except locale.Error as e:
  1114. # All lost. Setting to C as much as possible.
  1115. # We can not call locale.normalize on C as it
  1116. # will transform it to en_US and we already know
  1117. # it doesn't work.
  1118. locale.setlocale(locale.LC_ALL, 'C')
  1119. os.environ['LANGUAGE'] = 'C'
  1120. os.environ['LANG'] = 'C'
  1121. os.environ['LC_MESSAGES'] = 'C'
  1122. os.environ['LC_NUMERIC'] = 'C'
  1123. os.environ['LC_TIME'] = 'C'
  1124. gettext.install('grasslibs', gpath('locale'))
  1125. sys.stderr.write(
  1126. "All attempts to enable English language have"
  1127. " failed. GRASS running with C locale.\n"
  1128. "If you observe UnicodeError in Python,"
  1129. " install en_US.UTF-8"
  1130. " locale and restart GRASS.\n")
  1131. return
  1132. else:
  1133. # The last attempt...
  1134. try:
  1135. encoding = locale.getpreferredencoding()
  1136. normalized = locale.normalize('%s.%s' % (language, encoding))
  1137. locale.setlocale(locale.LC_ALL, normalized)
  1138. except locale.Error as e:
  1139. # If we got so far, attempts to set up language and locale have failed
  1140. # on this system
  1141. sys.stderr.write("Failed to enforce user specified language '%s' with error: '%s'\n" % (language, e))
  1142. sys.stderr.write("A LANGUAGE environmental variable has been set.\nPart of messages will be displayed in the requested language.\n")
  1143. # Even if setting locale will fail, let's set LANG in a hope,
  1144. # that UI will use it GRASS texts will be in selected language,
  1145. # system messages (i.e. OK, Cancel etc.) - in system default
  1146. # language
  1147. os.environ['LANGUAGE'] = language
  1148. os.environ['LANG'] = language
  1149. return
  1150. # Set up environment for subprocesses
  1151. os.environ['LANGUAGE'] = language
  1152. os.environ['LANG'] = language
  1153. if language == 'ko_KR' and encoding == 'cp949':
  1154. # The default encoding for the Korean language in Windows is cp949,
  1155. # Microsoft's proprietary extension to euc-kr, but gettext prints no
  1156. # translated messages at all in the Command Prompt window if LC_CTYPE
  1157. # is set to ko_KR.cp949. Here, force LC_CTYPE to be euc-kr.
  1158. normalized = 'euc-kr'
  1159. encoding = None
  1160. elif encoding:
  1161. normalized = locale.normalize('%s.%s' % (language, encoding))
  1162. else:
  1163. normalized = language
  1164. for lc in ('LC_CTYPE', 'LC_MESSAGES', 'LC_TIME', 'LC_COLLATE',
  1165. 'LC_MONETARY', 'LC_PAPER', 'LC_NAME', 'LC_ADDRESS',
  1166. 'LC_TELEPHONE', 'LC_MEASUREMENT', 'LC_IDENTIFICATION'):
  1167. os.environ[lc] = normalized
  1168. # Some code in GRASS might not like other decimal separators than .
  1169. # Other potential sources for problems are: LC_TIME LC_CTYPE
  1170. locale.setlocale(locale.LC_NUMERIC, 'C')
  1171. os.environ['LC_NUMERIC'] = 'C'
  1172. if os.getenv('LC_ALL'):
  1173. del os.environ['LC_ALL'] # Remove LC_ALL to not override LC_NUMERIC
  1174. # From now on enforce the new language
  1175. if encoding:
  1176. gettext.install('grasslibs', gpath('locale'), codeset=encoding)
  1177. else:
  1178. gettext.install('grasslibs', gpath('locale'))
  1179. # TODO: grass_gui parameter is a hack and should be removed, see below
  1180. def lock_mapset(mapset_path, force_gislock_removal, user, grass_gui):
  1181. """Lock the mapset and return name of the lock file
  1182. Behavior on error must be changed somehow; now it fatals but GUI case is
  1183. unresolved.
  1184. """
  1185. if not os.path.exists(mapset_path):
  1186. fatal(_("Path '%s' doesn't exist") % mapset_path)
  1187. if not os.access(mapset_path, os.W_OK):
  1188. error = _("Path '%s' not accessible.") % mapset_path
  1189. stat_info = os.stat(mapset_path)
  1190. mapset_uid = stat_info.st_uid
  1191. if mapset_uid != os.getuid():
  1192. # GTC %s is mapset's folder path
  1193. error = "%s\n%s" % (error, _("You are not the owner of '%s'.") % mapset_path)
  1194. fatal(error)
  1195. # Check for concurrent use
  1196. lockfile = os.path.join(mapset_path, ".gislock")
  1197. ret = call([gpath("etc", "lock"), lockfile, "%d" % os.getpid()])
  1198. msg = None
  1199. if ret == 2:
  1200. if not force_gislock_removal:
  1201. msg = _("%(user)s is currently running GRASS in selected mapset"
  1202. " (file %(file)s found). Concurrent use not allowed.\n"
  1203. "You can force launching GRASS using -f flag"
  1204. " (note that you need permission for this operation)."
  1205. " Have another look in the processor "
  1206. "manager just to be sure..." % {
  1207. 'user': user, 'file': lockfile})
  1208. else:
  1209. try_remove(lockfile)
  1210. message(_("%(user)s is currently running GRASS in selected mapset"
  1211. " (file %(file)s found). Forcing to launch GRASS..." % {
  1212. 'user': user, 'file': lockfile}))
  1213. elif ret != 0:
  1214. msg = _("Unable to properly access '%s'.\n"
  1215. "Please notify system personnel.") % lockfile
  1216. # TODO: the gui decision should be done by the caller
  1217. # this needs some change to the function interface, return tuple or
  1218. # use exceptions (better option)
  1219. if msg:
  1220. if grass_gui == "wxpython":
  1221. call([os.getenv('GRASS_PYTHON'), wxpath("gis_set_error.py"), msg])
  1222. # TODO: here we probably miss fatal or exit, needs to be added
  1223. else:
  1224. fatal(msg)
  1225. debug("Mapset <{mapset}> locked using '{lockfile}'".format(
  1226. mapset=mapset_path, lockfile=lockfile))
  1227. return lockfile
  1228. # TODO: the gisrcrc here does not make sense, remove it from load_gisrc
  1229. def unlock_gisrc_mapset(gisrc, gisrcrc):
  1230. """Unlock mapset from the gisrc file"""
  1231. settings = load_gisrc(gisrc, gisrcrc)
  1232. lockfile = os.path.join(settings.full_mapset, ".gislock")
  1233. # this fails silently, perhaps a warning would be helpful to
  1234. # catch cases when removal was not possible due to e.g. another
  1235. # session force-removing the file (unlocking the mapset)
  1236. try_remove(lockfile)
  1237. def make_fontcap():
  1238. # TODO: is GRASS_FONT_CAP ever defined? It seems it must be defined in system
  1239. fc = os.getenv('GRASS_FONT_CAP')
  1240. if fc and not os.access(fc, os.R_OK):
  1241. message(_("Building user fontcap..."))
  1242. call(["g.mkfontcap"])
  1243. def ensure_db_connected(mapset):
  1244. """Predefine default driver if DB connection not defined
  1245. :param mapset: full path to the mapset
  1246. """
  1247. if not os.access(os.path.join(mapset, "VAR"), os.F_OK):
  1248. call(['db.connect', '-c', '--quiet'])
  1249. def get_shell():
  1250. # set SHELL on ms windowns
  1251. # this was at the very beginning of the script but it can be anywhere
  1252. if windows:
  1253. if os.getenv('GRASS_SH'):
  1254. os.environ['SHELL'] = os.getenv('GRASS_SH')
  1255. if not os.getenv('SHELL'):
  1256. os.environ['SHELL'] = os.getenv('COMSPEC', 'cmd.exe')
  1257. # cygwin has many problems with the shell setup
  1258. # below, so i hardcoded everything here.
  1259. if sys.platform == 'cygwin':
  1260. sh = "cygwin"
  1261. shellname = "GNU Bash (Cygwin)"
  1262. os.environ['SHELL'] = "/usr/bin/bash.exe"
  1263. os.environ['OSTYPE'] = "cygwin"
  1264. else:
  1265. # in docker the 'SHELL' variable may not be
  1266. # visible in a Python session unless 'ENV SHELL /bin/bash' is set in Dockerfile
  1267. try:
  1268. sh = os.path.basename(os.getenv('SHELL'))
  1269. except:
  1270. sh = 'sh'
  1271. os.environ['SHELL'] = sh
  1272. if windows and sh:
  1273. sh = os.path.splitext(sh)[0]
  1274. if sh == "ksh":
  1275. shellname = "Korn Shell"
  1276. elif sh == "csh":
  1277. shellname = "C Shell"
  1278. elif sh == "tcsh":
  1279. shellname = "TC Shell"
  1280. elif sh == "bash":
  1281. shellname = "Bash Shell"
  1282. elif sh == "sh":
  1283. shellname = "Bourne Shell"
  1284. elif sh == "zsh":
  1285. shellname = "Z Shell"
  1286. elif sh == "cmd":
  1287. shellname = "Command Shell"
  1288. else:
  1289. shellname = "shell"
  1290. # check for SHELL
  1291. if not os.getenv('SHELL'):
  1292. fatal(_("The SHELL variable is not set"))
  1293. return sh, shellname
  1294. def get_grass_env_file(sh, grass_config_dir):
  1295. """Get name of the shell-specific GRASS environment (rc) file"""
  1296. if sh in ['csh', 'tcsh']:
  1297. grass_env_file = os.path.join(grass_config_dir, 'cshrc')
  1298. elif sh in ['bash', 'msh', 'cygwin', 'sh']:
  1299. grass_env_file = os.path.join(grass_config_dir, 'bashrc')
  1300. elif sh == 'zsh':
  1301. grass_env_file = os.path.join(grass_config_dir, 'zshrc')
  1302. elif sh == 'cmd':
  1303. grass_env_file = os.path.join(grass_config_dir, 'env.bat')
  1304. else:
  1305. grass_env_file = os.path.join(grass_config_dir, 'bashrc')
  1306. warning(_("Unsupported shell <{sh}>: {env_file}").format(
  1307. sh=sh, env_file=grass_env_file))
  1308. return grass_env_file
  1309. def get_batch_job_from_env_variable():
  1310. """Get script to execute from batch job variable if available
  1311. Fails with fatal if variable is set but content unusable.
  1312. """
  1313. # hack to process batch jobs:
  1314. batch_job = os.getenv('GRASS_BATCH_JOB')
  1315. # variable defined, but user might not have been careful enough
  1316. if batch_job:
  1317. if not os.access(batch_job, os.F_OK):
  1318. # wrong file
  1319. fatal(_("Job file <%s> has been defined in "
  1320. "the 'GRASS_BATCH_JOB' variable but not found. Exiting."
  1321. "\n\n"
  1322. "Use 'unset GRASS_BATCH_JOB' to disable "
  1323. "batch job processing.") % batch_job)
  1324. elif not os.access(batch_job, os.X_OK):
  1325. # right file, but ...
  1326. fatal(_("Change file permission to 'executable' for <%s>")
  1327. % batch_job)
  1328. return batch_job
  1329. def run_batch_job(batch_job):
  1330. """Runs script, module or any command
  1331. If *batch_job* is a string (insecure) shell=True is used for execution.
  1332. :param batch_job: executable and parameters in a list or a string
  1333. """
  1334. batch_job_string = batch_job
  1335. if not isinstance(batch_job, string_types):
  1336. # for messages only
  1337. batch_job_string = ' '.join(batch_job)
  1338. message(_("Executing <%s> ...") % batch_job_string)
  1339. if isinstance(batch_job, string_types):
  1340. # shell=True is keeping the original GRASS_BATCH_JOB behavior
  1341. def quote(string):
  1342. if '"' in string:
  1343. return "'%s'" % batch_job
  1344. else:
  1345. return '"%s"' % batch_job
  1346. batch_job = quote(batch_job)
  1347. proc = Popen(batch_job, shell=True)
  1348. else:
  1349. try:
  1350. proc = Popen(batch_job, shell=False)
  1351. except OSError as error:
  1352. fatal(_("Execution of <{cmd}> failed:\n"
  1353. "{error}").format(cmd=batch_job_string, error=error))
  1354. returncode = proc.wait()
  1355. message(_("Execution of <%s> finished.") % batch_job_string)
  1356. return returncode
  1357. def start_gui(grass_gui):
  1358. """Start specified GUI
  1359. :param grass_gui: GUI name (allowed values: 'wxpython')
  1360. """
  1361. # Start the chosen GUI but ignore text
  1362. debug("GRASS GUI should be <%s>" % grass_gui)
  1363. # Check for gui interface
  1364. if grass_gui == "wxpython":
  1365. Popen([os.getenv('GRASS_PYTHON'), wxpath("wxgui.py")])
  1366. def close_gui():
  1367. """Close GUI if running"""
  1368. if gpath('etc', 'python') not in sys.path:
  1369. sys.path.append(gpath('etc', 'python'))
  1370. from grass.script import core as gcore # pylint: disable=E0611
  1371. env = gcore.gisenv()
  1372. if 'GUI_PID' not in env:
  1373. return
  1374. import signal
  1375. for pid in env['GUI_PID'].split(','):
  1376. debug("Exiting GUI with pid={0}".format(pid))
  1377. try:
  1378. os.kill(int(pid), signal.SIGTERM)
  1379. except OSError as e:
  1380. message(_("Unable to close GUI. {0}").format(e))
  1381. def clear_screen():
  1382. """Clear terminal"""
  1383. if windows:
  1384. pass
  1385. # TODO: uncomment when PDCurses works.
  1386. # cls
  1387. else:
  1388. if not is_debug():
  1389. call(["tput", "clear"])
  1390. def show_banner():
  1391. """Write GRASS GIS ASCII name to stderr"""
  1392. sys.stderr.write(r"""
  1393. __________ ___ __________ _______________
  1394. / ____/ __ \/ | / ___/ ___/ / ____/ _/ ___/
  1395. / / __/ /_/ / /| | \__ \\_ \ / / __ / / \__ \
  1396. / /_/ / _, _/ ___ |___/ /__/ / / /_/ // / ___/ /
  1397. \____/_/ |_/_/ |_/____/____/ \____/___//____/
  1398. """)
  1399. def say_hello():
  1400. """Write welcome to stderr including Subversion revision if in svn copy"""
  1401. sys.stderr.write(_("Welcome to GRASS GIS %s") % grass_version)
  1402. if grass_version.endswith('svn'):
  1403. try:
  1404. filerev = open(gpath('etc', 'VERSIONNUMBER'))
  1405. linerev = filerev.readline().rstrip('\n')
  1406. filerev.close()
  1407. revision = linerev.split(' ')[1]
  1408. sys.stderr.write(' (' + revision + ')')
  1409. except:
  1410. pass
  1411. def show_info(shellname, grass_gui, default_gui):
  1412. """Write basic infor about GRASS GIS and GRASS session to stderr"""
  1413. sys.stderr.write(
  1414. r"""
  1415. %-41shttp://grass.osgeo.org
  1416. %-41s%s (%s)
  1417. %-41sg.manual -i
  1418. %-41sg.version -c
  1419. %-41sg.version -x
  1420. """ % (_("GRASS GIS homepage:"),
  1421. # GTC Running through: SHELL NAME
  1422. _("This version running through:"),
  1423. shellname, os.getenv('SHELL'),
  1424. _("Help is available with the command:"),
  1425. _("See the licence terms with:"),
  1426. _("See citation options with:")))
  1427. if grass_gui == 'wxpython':
  1428. message("%-41sg.gui wxpython" % _("If required, restart the GUI with:"))
  1429. else:
  1430. message("%-41sg.gui %s" % (_("Start the GUI with:"), default_gui))
  1431. message("%-41sexit" % _("When ready to quit enter:"))
  1432. message("")
  1433. def csh_startup(location, location_name, mapset, grass_env_file):
  1434. userhome = os.getenv('HOME') # save original home
  1435. home = location
  1436. os.environ['HOME'] = home
  1437. cshrc = os.path.join(home, ".cshrc")
  1438. tcshrc = os.path.join(home, ".tcshrc")
  1439. try_remove(cshrc)
  1440. try_remove(tcshrc)
  1441. f = open(cshrc, 'w')
  1442. f.write("set home = %s\n" % userhome)
  1443. f.write("set history = 3000 savehist = 3000 noclobber ignoreeof\n")
  1444. f.write("set histfile = %s\n" % os.path.join(os.getenv('HOME'),
  1445. ".history"))
  1446. f.write("set prompt = '\\\n")
  1447. f.write("Mapset <%s> in Location <%s> \\\n" % (mapset, location_name))
  1448. f.write("GRASS GIS %s > '\n" % grass_version)
  1449. f.write("set BOGUS=``;unset BOGUS\n")
  1450. # csh shell rc file left for backward compatibility
  1451. path = os.path.join(userhome, ".grass.cshrc")
  1452. if os.access(path, os.R_OK):
  1453. f.write(readfile(path) + '\n')
  1454. if os.access(grass_env_file, os.R_OK):
  1455. f.write(readfile(grass_env_file) + '\n')
  1456. mail_re = re.compile(r"^ *set *mail *= *")
  1457. for filename in [".cshrc", ".tcshrc", ".login"]:
  1458. path = os.path.join(userhome, filename)
  1459. if os.access(path, os.R_OK):
  1460. s = readfile(path)
  1461. lines = s.splitlines()
  1462. for l in lines:
  1463. if mail_re.match(l):
  1464. f.write(l)
  1465. path = os.getenv('PATH').split(':')
  1466. f.write("set path = ( %s ) \n" % ' '.join(path))
  1467. f.close()
  1468. writefile(tcshrc, readfile(cshrc))
  1469. process = Popen([gpath("etc", "run"), os.getenv('SHELL')])
  1470. os.environ['HOME'] = userhome
  1471. return process
  1472. def bash_startup(location, location_name, grass_env_file):
  1473. # save command history in mapset dir and remember more
  1474. os.environ['HISTFILE'] = os.path.join(location, ".bash_history")
  1475. if not os.getenv('HISTSIZE') and not os.getenv('HISTFILESIZE'):
  1476. os.environ['HISTSIZE'] = "3000"
  1477. # instead of changing $HOME, start bash with:
  1478. # --rcfile "$LOCATION/.bashrc" ?
  1479. # if so, must care be taken to explicitly call .grass.bashrc et al
  1480. # for non-interactive bash batch jobs?
  1481. userhome = os.getenv('HOME') # save original home
  1482. home = location # save .bashrc in $LOCATION
  1483. os.environ['HOME'] = home
  1484. bashrc = os.path.join(home, ".bashrc")
  1485. try_remove(bashrc)
  1486. f = open(bashrc, 'w')
  1487. f.write("test -r ~/.alias && . ~/.alias\n")
  1488. if os.getenv('ISISROOT'):
  1489. # GRASS GIS and ISIS blend
  1490. grass_name = "ISIS-GRASS"
  1491. else:
  1492. grass_name = "GRASS"
  1493. f.write("PS1='{name} {version} ({location}):\\w > '\n".format(
  1494. name=grass_name, version=grass_version, location=location_name))
  1495. # TODO: have a function and/or module to test this
  1496. mask2d_test = 'test -f "$MAPSET_PATH/cell/MASK"'
  1497. mask3d_test = 'test -d "$MAPSET_PATH/grid3/RASTER3D_MASK"'
  1498. # double curly brackets means single one for format function
  1499. # setting LOCATION for backwards compatibility
  1500. f.write(
  1501. """grass_prompt() {{
  1502. MAPSET_PATH="`g.gisenv get=GISDBASE,LOCATION_NAME,MAPSET separator='/'`"
  1503. LOCATION="$MAPSET_PATH"
  1504. if {mask2d_test} && {mask3d_test} ; then
  1505. echo [{both_masks}]
  1506. elif {mask2d_test} ; then
  1507. echo [{mask2d}]
  1508. elif {mask3d_test} ; then
  1509. echo [{mask3d}]
  1510. fi
  1511. }}
  1512. PROMPT_COMMAND=grass_prompt\n""".format(
  1513. both_masks=_("2D and 3D raster MASKs present"),
  1514. mask2d=_("Raster MASK present"),
  1515. mask3d=_("3D raster MASK present"),
  1516. mask2d_test=mask2d_test, mask3d_test=mask3d_test
  1517. ))
  1518. # read other settings (aliases, ...) since environmental variables
  1519. # have been already set by load_env(), see #3462
  1520. for env_file in [os.path.join(userhome, ".grass.bashrc"),
  1521. grass_env_file]:
  1522. if not os.access(env_file, os.R_OK):
  1523. continue
  1524. for line in readfile(env_file).splitlines():
  1525. # Bug related to OS X "SIP", see
  1526. # https://trac.osgeo.org/grass/ticket/3462#comment:13
  1527. if macosx or not line.startswith('export'):
  1528. f.write(line + '\n')
  1529. f.write("export PATH=\"%s\"\n" % os.getenv('PATH'))
  1530. f.write("export HOME=\"%s\"\n" % userhome) # restore user home path
  1531. f.close()
  1532. process = Popen([gpath("etc", "run"), os.getenv('SHELL')])
  1533. os.environ['HOME'] = userhome
  1534. return process
  1535. def default_startup(location, location_name):
  1536. if windows:
  1537. os.environ['PS1'] = "GRASS %s> " % (grass_version)
  1538. # "$ETC/run" doesn't work at all???
  1539. process = subprocess.Popen([os.getenv('SHELL')])
  1540. else:
  1541. os.environ['PS1'] = "GRASS %s (%s):\\w > " % (grass_version, location_name)
  1542. process = Popen([gpath("etc", "run"), os.getenv('SHELL')])
  1543. return process
  1544. def done_message():
  1545. # here was something for batch job but it was never called
  1546. message(_("Done."))
  1547. message("")
  1548. message(_("Goodbye from GRASS GIS"))
  1549. message("")
  1550. def clean_temp():
  1551. message(_("Cleaning up temporary files..."))
  1552. nul = open(os.devnull, 'w')
  1553. call([gpath("etc", "clean_temp")], stdout=nul)
  1554. nul.close()
  1555. def grep(pattern, lines):
  1556. """Search lines (list of strings) and return them when beginning matches.
  1557. >>> grep("a", ['abc', 'cab', 'sdr', 'aaa', 'sss'])
  1558. ['abc', 'aaa']
  1559. """
  1560. expr = re.compile(pattern)
  1561. return [elem for elem in lines if expr.match(elem)]
  1562. def print_params():
  1563. """Write compile flags and other configuration to stderr"""
  1564. plat = gpath('include', 'Make', 'Platform.make')
  1565. if not os.path.exists(plat):
  1566. fatal(_("Please install the GRASS GIS development package"))
  1567. fileplat = open(plat)
  1568. linesplat = fileplat.readlines()
  1569. fileplat.close()
  1570. params = sys.argv[2:]
  1571. if not params:
  1572. params = ['arch', 'build', 'compiler', 'path', 'revision', 'version']
  1573. for arg in params:
  1574. if arg == 'path':
  1575. sys.stdout.write("%s\n" % gisbase)
  1576. elif arg == 'arch':
  1577. val = grep('ARCH', linesplat)
  1578. sys.stdout.write("%s\n" % val[0].split('=')[1].strip())
  1579. elif arg == 'build':
  1580. build = gpath('include', 'grass', 'confparms.h')
  1581. filebuild = open(build)
  1582. val = filebuild.readline()
  1583. filebuild.close()
  1584. sys.stdout.write("%s\n" % val.strip().strip('"').strip())
  1585. elif arg == 'compiler':
  1586. val = grep('CC', linesplat)
  1587. sys.stdout.write("%s\n" % val[0].split('=')[1].strip())
  1588. elif arg == 'revision':
  1589. rev = gpath('include', 'grass', 'gis.h')
  1590. filerev = open(rev)
  1591. linesrev = filerev.readlines()
  1592. val = grep('#define GIS_H_VERSION', linesrev)
  1593. filerev.close()
  1594. sys.stdout.write(
  1595. "%s\n" % val[0].split(':')[1].rstrip('$"\n').strip())
  1596. elif arg == 'version':
  1597. sys.stdout.write("%s\n" % grass_version)
  1598. else:
  1599. message(_("Parameter <%s> not supported") % arg)
  1600. def get_username():
  1601. """Get name of the current user"""
  1602. if windows:
  1603. user = os.getenv('USERNAME')
  1604. if not user:
  1605. user = "user_name"
  1606. else:
  1607. user = os.getenv('USER')
  1608. if not user:
  1609. user = os.getenv('LOGNAME')
  1610. if not user:
  1611. try:
  1612. p = Popen(['whoami'], stdout=subprocess.PIPE)
  1613. s = p.stdout.read()
  1614. p.wait()
  1615. user = s.strip()
  1616. except:
  1617. pass
  1618. if not user:
  1619. user = "user_%d" % os.getuid()
  1620. return user
  1621. class Parameters(object):
  1622. """Structure to hold standard part of command line parameters"""
  1623. # we don't need to define any methods
  1624. # pylint: disable=R0903
  1625. def __init__(self):
  1626. self.grass_gui = None
  1627. self.create_new = None
  1628. self.exit_grass = None
  1629. self.force_gislock_removal = None
  1630. self.mapset = None
  1631. self.geofile = None
  1632. self.tmp_location = False
  1633. def parse_cmdline(argv, default_gui):
  1634. """Parse the standard part of command line parameters"""
  1635. params = Parameters()
  1636. args = []
  1637. for i in argv:
  1638. # Check if the user asked for the version
  1639. if i in ["-v", "--version"]:
  1640. message("GRASS GIS %s" % grass_version)
  1641. message('\n' + readfile(gpath("etc", "license")))
  1642. sys.exit()
  1643. # Check if the user asked for help
  1644. elif i in ["help", "-h", "-help", "--help", "--h"]:
  1645. help_message(default_gui=default_gui)
  1646. sys.exit()
  1647. # Check if the --text flag was given
  1648. elif i in ["-text", "--text"]:
  1649. params.grass_gui = 'text'
  1650. # Check if the --gtext flag was given
  1651. elif i in ["-gtext", "--gtext"]:
  1652. params.grass_gui = 'gtext'
  1653. # Check if the --gui flag was given
  1654. elif i in ["-gui", "--gui"]:
  1655. params.grass_gui = default_gui
  1656. # Check if the -wxpython flag was given
  1657. elif i in ["-wxpython", "-wx", "--wxpython", "--wx"]:
  1658. params.grass_gui = 'wxpython'
  1659. # Check if the user wants to create a new mapset
  1660. elif i == "-c":
  1661. params.create_new = True
  1662. elif i == "-e":
  1663. params.exit_grass = True
  1664. elif i == "-f":
  1665. params.force_gislock_removal = True
  1666. elif i == "--config":
  1667. print_params()
  1668. sys.exit()
  1669. elif i == "--tmp-location":
  1670. params.tmp_location = True
  1671. else:
  1672. args.append(i)
  1673. if len(args) > 1:
  1674. params.mapset = args[1]
  1675. params.geofile = args[0]
  1676. elif len(args) == 1:
  1677. if params.tmp_location:
  1678. params.geofile = args[0]
  1679. else:
  1680. params.mapset = args[0]
  1681. else:
  1682. params.mapset = None
  1683. return params
  1684. # The main script starts here
  1685. # Get the system name
  1686. windows = sys.platform == 'win32'
  1687. cygwin = "cygwin" in sys.platform
  1688. macosx = "darwin" in sys.platform
  1689. # TODO: it is OK to remove this?
  1690. # at the beginning of this file were are happily getting GISBASE
  1691. # from the environment and we don't care about inconsistencies it might cause
  1692. # The following was commented out because of breaking winGRASS
  1693. # if 'GISBASE' in os.environ:
  1694. # sys.exit(_("ERROR: GRASS GIS is already running "
  1695. # "(environmental variable GISBASE found)"))
  1696. # this is not really an issue, we should be able to overpower another session
  1697. # Set GISBASE
  1698. os.environ['GISBASE'] = gisbase
  1699. def main():
  1700. """The main function which does the whole setup and run procedure
  1701. Only few things are set on the module level.
  1702. """
  1703. # Set default GUI
  1704. default_gui = "wxpython"
  1705. # explain what is happening in debug mode (visible only in debug mode)
  1706. debug("GRASS_DEBUG environmental variable is set. It is meant to be"
  1707. " an internal variable for debugging only this script.\n"
  1708. " Use 'g.gisenv set=\"DEBUG=[0-5]\"'"
  1709. " to turn GRASS GIS debug mode on if you wish to do so.")
  1710. # Set GRASS version number for R interface etc
  1711. # (must be an env var for MS Windows)
  1712. os.environ['GRASS_VERSION'] = grass_version
  1713. # Set the GIS_LOCK variable to current process id
  1714. gis_lock = str(os.getpid())
  1715. os.environ['GIS_LOCK'] = gis_lock
  1716. grass_config_dir = get_grass_config_dir()
  1717. batch_job = get_batch_job_from_env_variable()
  1718. # Parse the command-line options and set several global variables
  1719. batch_exec_param = '--exec'
  1720. try:
  1721. # raises ValueError when not found
  1722. index = sys.argv.index(batch_exec_param)
  1723. batch_job = sys.argv[index + 1:]
  1724. clean_argv = sys.argv[1:index]
  1725. params = parse_cmdline(clean_argv, default_gui=default_gui)
  1726. except ValueError:
  1727. params = parse_cmdline(sys.argv[1:], default_gui=default_gui)
  1728. if params.exit_grass and not params.create_new:
  1729. fatal(_("Flag -e requires also flag -c"))
  1730. if params.tmp_location and not params.geofile:
  1731. fatal(_("Coordinate reference system argument (e.g. EPSG)"
  1732. " is needed for --tmp-location"))
  1733. if params.tmp_location and params.mapset:
  1734. fatal(_("Only one argument (e.g. EPSG) is needed for"
  1735. " --tmp-location, mapset name <{}> provided").format(
  1736. params.mapset))
  1737. # For now, we allow, but not advertise/document, --tmp-location
  1738. # without --exec (usefulness to be evaluated).
  1739. grass_gui = params.grass_gui # put it to variable, it is used a lot
  1740. # TODO: with --tmp-location there is no point in loading settings
  1741. # i.e. rc file from home dir, but the code is too spread out
  1742. # to disable it at this point
  1743. gisrcrc = get_gisrc_from_config_dir(grass_config_dir, batch_job)
  1744. # Set the username
  1745. user = get_username()
  1746. # TODO: this might need to be moved before processing of parameters
  1747. # and getting batch job
  1748. # Set language
  1749. # This has to be called before any _() function call!
  1750. # Subsequent functions are using _() calls and
  1751. # thus must be called only after Language has been set.
  1752. set_language(grass_config_dir)
  1753. # Set shell (needs to be called before load_env())
  1754. sh, shellname = get_shell()
  1755. grass_env_file = get_grass_env_file(sh, grass_config_dir)
  1756. # Load environmental variables from the file (needs to be called
  1757. # before create_tmp())
  1758. load_env(grass_env_file)
  1759. # Create the temporary directory and session grassrc file
  1760. tmpdir = create_tmp(user, gis_lock)
  1761. cleaner = Cleaner()
  1762. cleaner.tmpdir = tmpdir
  1763. # object is not destroyed when its method is registered
  1764. atexit.register(cleaner.cleanup)
  1765. # Create the session grassrc file
  1766. gisrc = create_gisrc(tmpdir, gisrcrc)
  1767. ensure_home()
  1768. # Set PATH, PYTHONPATH, ...
  1769. set_paths(grass_config_dir=grass_config_dir)
  1770. # Set GRASS_PAGER, GRASS_PYTHON, GRASS_GNUPLOT, GRASS_PROJSHARE
  1771. set_defaults()
  1772. set_display_defaults()
  1773. # Set GRASS_HTML_BROWSER
  1774. set_browser()
  1775. # First time user - GISRC is defined in the GRASS script
  1776. if not os.access(gisrc, os.F_OK):
  1777. if grass_gui == 'text' and not params.mapset:
  1778. fatal(_("Unable to start GRASS GIS. You have the choice to:\n"
  1779. " - Launch the graphical user interface with"
  1780. " the '--gui' switch\n"
  1781. " {cmd_name} --gui\n"
  1782. " - Launch with path to "
  1783. "the location/mapset as an argument\n"
  1784. " {cmd_name} /path/to/location/mapset`\n"
  1785. " - Create a location with '-c' and launch in its"
  1786. " PERMANENT mapset\n"
  1787. " {cmd_name} -c EPSG:number /path/to/location\n"
  1788. " {cmd_name} -c geofile /path/to/location\n"
  1789. " - Create manually the GISRC file ({gisrcrc})\n"
  1790. " - Use '--help' for further options\n"
  1791. " {cmd_name} --help\n"
  1792. "See also: https://grass.osgeo.org/{cmd_name}/manuals/helptext.html").format(
  1793. cmd_name=cmd_name, gisrcrc=gisrcrc))
  1794. create_initial_gisrc(gisrc)
  1795. message(_("Starting GRASS GIS..."))
  1796. # Ensure GUI is set
  1797. if batch_job or params.exit_grass:
  1798. grass_gui = 'text'
  1799. else:
  1800. if not grass_gui:
  1801. # if GUI was not set previously (e.g. command line),
  1802. # get it from rc file or env variable
  1803. grass_gui = read_gui(gisrc, default_gui)
  1804. # check that the GUI works but only if not doing a batch job
  1805. grass_gui = check_gui(expected_gui=grass_gui)
  1806. # save GUI only if we are not doibg batch job
  1807. save_gui(gisrc, grass_gui)
  1808. # Parsing argument to get LOCATION
  1809. if not params.mapset and not params.tmp_location:
  1810. # Try interactive startup
  1811. # User selects LOCATION and MAPSET if not set
  1812. if not set_mapset_interactive(grass_gui):
  1813. # No GUI available, update gisrc file
  1814. fatal(_("<{0}> requested, but not available. Run GRASS in text "
  1815. "mode (--text) or install missing package (usually "
  1816. "'grass-gui').").format(grass_gui))
  1817. else:
  1818. # Try non-interactive start up
  1819. if params.tmp_location:
  1820. # tmp loc requires other things to be set as well
  1821. set_mapset(gisrc=gisrc, geofile=params.geofile,
  1822. create_new=True,
  1823. tmp_location=params.tmp_location, tmpdir=tmpdir)
  1824. elif params.create_new and params.geofile:
  1825. set_mapset(gisrc=gisrc, arg=params.mapset,
  1826. geofile=params.geofile, create_new=True)
  1827. else:
  1828. set_mapset(gisrc=gisrc, arg=params.mapset,
  1829. create_new=params.create_new)
  1830. # Set GISDBASE, LOCATION_NAME, MAPSET, LOCATION from $GISRC
  1831. # e.g. wxGUI startup screen writes to the gisrc file,
  1832. # so loading it is the only universal way to obtain the values
  1833. # this suppose that both programs share the right path to gisrc file
  1834. # TODO: perhaps gisrcrc should be removed from here
  1835. # alternatively, we can check validity here with all the info we have
  1836. # about what was used to create gisrc
  1837. mapset_settings = load_gisrc(gisrc, gisrcrc=gisrcrc)
  1838. location = mapset_settings.full_mapset
  1839. # check and create .gislock file
  1840. lock_mapset(mapset_settings.full_mapset, user=user,
  1841. force_gislock_removal=params.force_gislock_removal,
  1842. grass_gui=grass_gui)
  1843. # unlock the mapset which is current at the time of turning off
  1844. # in case mapset was changed
  1845. atexit.register(lambda: unlock_gisrc_mapset(gisrc, gisrcrc))
  1846. # We now own the mapset (set and lock), so we can clean temporary
  1847. # files which previous session may have left behind. We do it even
  1848. # for first time user because the cost is low and first time user
  1849. # doesn't necessarily mean that the mapset is used for the first time.
  1850. clean_temp()
  1851. # clean always at exit, cleans whatever is current mapset based on
  1852. # the GISRC env variable
  1853. atexit.register(clean_temp)
  1854. # build user fontcap if specified but not present
  1855. make_fontcap()
  1856. # TODO: is this really needed? Modules should call this when/if required.
  1857. ensure_db_connected(location)
  1858. # Display the version and license info
  1859. # only non-error, interactive version continues from here
  1860. if batch_job:
  1861. returncode = run_batch_job(batch_job)
  1862. sys.exit(returncode)
  1863. elif params.exit_grass:
  1864. sys.exit(0)
  1865. else:
  1866. clear_screen()
  1867. show_banner()
  1868. say_hello()
  1869. show_info(shellname=shellname,
  1870. grass_gui=grass_gui, default_gui=default_gui)
  1871. if grass_gui == "wxpython":
  1872. message(_("Launching <%s> GUI in the background, please wait...")
  1873. % grass_gui)
  1874. if sh in ['csh', 'tcsh']:
  1875. shell_process = csh_startup(mapset_settings.full_mapset,
  1876. mapset_settings.location,
  1877. mapset_settings.mapset,
  1878. grass_env_file)
  1879. elif sh in ['bash', 'msh', 'cygwin']:
  1880. shell_process = bash_startup(mapset_settings.full_mapset,
  1881. mapset_settings.location,
  1882. grass_env_file)
  1883. else:
  1884. shell_process = default_startup(mapset_settings.full_mapset,
  1885. mapset_settings.location)
  1886. # start GUI and register shell PID in rc file
  1887. start_gui(grass_gui)
  1888. kv = read_gisrc(gisrc)
  1889. kv['PID'] = str(shell_process.pid)
  1890. write_gisrc(kv, gisrc)
  1891. exit_val = shell_process.wait()
  1892. if exit_val != 0:
  1893. warning(_("Failed to start shell '%s'") % os.getenv('SHELL'))
  1894. # close GUI if running
  1895. close_gui()
  1896. # here we are at the end of grass session
  1897. clear_screen()
  1898. # save 'last used' GISRC after removing variables which shouldn't
  1899. # be saved, e.g. d.mon related
  1900. clean_env(gisrc)
  1901. if not params.tmp_location:
  1902. writefile(gisrcrc, readfile(gisrc))
  1903. # After this point no more grass modules may be called
  1904. done_message()
  1905. if __name__ == '__main__':
  1906. main()