grass.py 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235
  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(_("GISDBASE, LOCATION_NAME and MAPSET variables not set properly.\n"
  903. "Interactive startup needed."))
  904. def set_mapset_interactive(grass_gui):
  905. """User selects Location and Mapset in an interative way
  906. The gisrc (GRASS environment file) is written at the end.
  907. """
  908. if not os.path.exists(wxpath("gis_set.py")) and grass_gui != 'text':
  909. debug("No GUI available, switching to text mode")
  910. return False
  911. # Check for text interface
  912. if grass_gui == 'text':
  913. # TODO: maybe this should be removed and solved from outside
  914. # this depends on what we expect from this function
  915. # should gisrc be ok after running or is it allowed to be still not set
  916. pass
  917. # Check for GUI
  918. elif grass_gui in ('gtext', 'wxpython'):
  919. gui_startup(grass_gui)
  920. else:
  921. # Shouldn't need this but you never know
  922. fatal(_("Invalid user interface specified - <%s>. "
  923. "Use the --help option to see valid interface names.") % grass_gui)
  924. return True
  925. def gui_startup(grass_gui):
  926. """Start GUI for startup (setting gisrc file)"""
  927. if grass_gui in ('wxpython', 'gtext'):
  928. ret = call([os.getenv('GRASS_PYTHON'), wxpath("gis_set.py")])
  929. # this if could be simplified to three branches (0, 5, rest)
  930. # if there is no need to handle unknown code separately
  931. if ret == 0:
  932. pass
  933. elif ret in [1, 2]:
  934. # 1 probably error coming from gis_set.py
  935. # 2 probably file not found from python interpreter
  936. # formerly we were starting in text mode instead, now we just fail
  937. # which is more straightforward for everybody
  938. fatal(_("Error in GUI startup. See messages above (if any)"
  939. " and if necessary, please"
  940. " report this error to the GRASS developers.\n"
  941. "On systems with package manager, make sure you have the right"
  942. " GUI package, probably named grass-gui, installed.\n"
  943. "To run GRASS GIS in text mode use the --text flag.\n"
  944. "Use '--help' for further options\n"
  945. " {cmd_name} --help\n"
  946. "See also: https://grass.osgeo.org/{cmd_name}/manuals/helptext.html").format(
  947. cmd_name=cmd_name))
  948. elif ret == 5: # defined in gui/wxpython/gis_set.py
  949. # User wants to exit from GRASS
  950. message(_("Exit was requested in GUI.\nGRASS GIS will not start. Bye."))
  951. sys.exit(0)
  952. else:
  953. fatal(_("Invalid return code from GUI startup script.\n"
  954. "Please advise GRASS developers of this error."))
  955. # we don't follow the LOCATION_NAME legacy naming here but we have to still
  956. # translate to it, so always double check
  957. class MapsetSettings(object):
  958. """Holds GRASS GIS database directory, Location and Mapset
  959. Provides few convenient functions.
  960. """
  961. def __init__(self):
  962. self.gisdbase = None
  963. self.location = None
  964. self.mapset = None
  965. self._full_mapset = None
  966. # TODO: perhaps full_mapset would be better as mapset_path
  967. # TODO: works only when set for the first time
  968. # this follows the current usage but we must invalidate when
  969. # the others are changed (use properties for that)
  970. @property
  971. def full_mapset(self):
  972. if self._full_mapset is None:
  973. self._full_mapset = os.path.join(self.gisdbase, self.location,
  974. self.mapset)
  975. return self._full_mapset
  976. # TODO: perhaps conversion to bool would be nicer
  977. def is_valid(self):
  978. return self.gisdbase and self.location and self.mapset
  979. # TODO: does it really makes sense to tell user about gisrcrc?
  980. # anything could have happened in between loading from gisrcrc and now
  981. # (we do e.g. GUI or creating loctation)
  982. def load_gisrc(gisrc, gisrcrc):
  983. """Get the settings of Location and Mapset from the gisrc file
  984. :returns: MapsetSettings object
  985. """
  986. mapset_settings = MapsetSettings()
  987. kv = read_gisrc(gisrc)
  988. mapset_settings.gisdbase = kv.get('GISDBASE')
  989. mapset_settings.location = kv.get('LOCATION_NAME')
  990. mapset_settings.mapset = kv.get('MAPSET')
  991. if not mapset_settings.is_valid():
  992. fatal(_("Error reading data path information from g.gisenv.\n"
  993. "GISDBASE={gisbase}\n"
  994. "LOCATION_NAME={location}\n"
  995. "MAPSET={mapset}\n\n"
  996. "Check the <{file}> file.").format(
  997. gisbase=mapset_settings.gisdbase,
  998. location=mapset_settings.location,
  999. mapset=mapset_settings.mapset,
  1000. file=gisrcrc))
  1001. return mapset_settings
  1002. # load environmental variables from grass_env_file
  1003. def load_env(grass_env_file):
  1004. if not os.access(grass_env_file, os.R_OK):
  1005. return
  1006. for line in readfile(grass_env_file).split(os.linesep):
  1007. try:
  1008. k, v = map(lambda x: x.strip(), line.strip().split(' ', 1)[1].split('=', 1))
  1009. except:
  1010. continue
  1011. debug("Environmental variable set {0}={1}".format(k, v))
  1012. os.environ[k] = v
  1013. # Allow for mixed ISIS-GRASS Environment
  1014. if os.getenv('ISISROOT'):
  1015. isis = os.getenv('ISISROOT')
  1016. os.environ['ISIS_LIB'] = isis + os.sep + "lib"
  1017. os.environ['ISIS_3RDPARTY'] = isis + os.sep + "3rdParty" + os.sep + "lib"
  1018. os.environ['QT_PLUGIN_PATH'] = isis + os.sep + "3rdParty" + os.sep + "plugins"
  1019. # os.environ['ISIS3DATA'] = isis + "$ISIS3DATA"
  1020. libpath = os.getenv('LD_LIBRARY_PATH', '')
  1021. isislibpath = os.getenv('ISIS_LIB')
  1022. isis3rdparty = os.getenv('ISIS_3RDPARTY')
  1023. os.environ['LD_LIBRARY_PATH'] = libpath + os.pathsep + isislibpath + os.pathsep + isis3rdparty
  1024. def set_language(grass_config_dir):
  1025. # This function is used to override system default language and locale
  1026. # Such override can be requested only from wxGUI
  1027. # An override if user has provided correct environmental variables as
  1028. # LC_MESSAGES or LANG is not necessary.
  1029. # Unfortunately currently a working solution for Windows is lacking
  1030. # thus it always on Vista and XP will print an error.
  1031. # See discussion for Windows not following its own documentation and
  1032. # not accepting ISO codes as valid locale identifiers http://bugs.python.org/issue10466
  1033. language = 'None' # Such string sometimes is present in wx file
  1034. encoding = None
  1035. # Override value is stored in wxGUI preferences file.
  1036. # As it's the only thing required, we'll just grep it out.
  1037. try:
  1038. fd = open(os.path.join(grass_config_dir, 'wx'), 'r')
  1039. except:
  1040. # Even if there is no override, we still need to set locale.
  1041. pass
  1042. else:
  1043. for line in fd:
  1044. if re.search('^language', line):
  1045. line = line.rstrip(' %s' % os.linesep)
  1046. language = ''.join(line.split(';')[-1:])
  1047. break
  1048. fd.close()
  1049. # Backwards compatability with old wx preferences files
  1050. if language == 'C':
  1051. language = 'en'
  1052. if language == 'None' or language == '' or not language:
  1053. # Language override is disabled (system language specified)
  1054. # As by default program runs with C locale, but users expect to
  1055. # have their default locale, we'll just set default locale
  1056. try:
  1057. locale.setlocale(locale.LC_ALL, '')
  1058. except locale.Error as e:
  1059. # If we get here, system locale settings are terribly wrong
  1060. # There is no point to continue as GRASS/Python will fail
  1061. # in some other unpredictable way.
  1062. sys.stderr.write(
  1063. "System locale is not usable (LC_ALL variable not defined)."
  1064. " Most likely it indicates misconfigured environment.\n")
  1065. sys.stderr.write("Reported error message: %s\n" % e)
  1066. # it would be too drastic to exit
  1067. # sys.exit("Fix system locale settings and then try again.")
  1068. locale.setlocale(locale.LC_ALL, 'C')
  1069. sys.stderr.write("Default locale settings are missing. GRASS running with C locale.")
  1070. language, encoding = locale.getdefaultlocale()
  1071. if not language:
  1072. sys.stderr.write("Default locale settings are missing. GRASS running with C locale.")
  1073. return
  1074. else:
  1075. debug("A language override has been requested."
  1076. " Trying to switch GRASS into '%s'..." % language)
  1077. try:
  1078. locale.setlocale(locale.LC_ALL, language)
  1079. except locale.Error as e:
  1080. try:
  1081. # Locale lang.encoding might be missing. Let's try
  1082. # UTF-8 encoding before giving up as on Linux systems
  1083. # lang.UTF-8 locales are more common than legacy
  1084. # ISO-8859 ones.
  1085. encoding = 'UTF-8'
  1086. normalized = locale.normalize('%s.%s' % (language, encoding))
  1087. locale.setlocale(locale.LC_ALL, normalized)
  1088. except locale.Error as e:
  1089. if language == 'en':
  1090. # A workaround for Python Issue30755
  1091. # https://bugs.python.org/issue30755
  1092. if locale.normalize('C.UTF-8') == 'en_US.UTF-8':
  1093. locale.setlocale(locale.LC_ALL, 'C')
  1094. os.environ['LANGUAGE'] = 'C'
  1095. os.environ['LANG'] = 'C'
  1096. os.environ['LC_MESSAGES'] = 'C'
  1097. os.environ['LC_NUMERIC'] = 'C'
  1098. os.environ['LC_TIME'] = 'C'
  1099. sys.stderr.write(
  1100. "To avoid Unicode errors in GUI, install"
  1101. " en_US.UTF-8 locale and restart GRASS.\n"
  1102. "Also consider upgrading your Python version"
  1103. " to one containing fix for Python Issue 30755.\n")
  1104. return
  1105. # en_US locale might be missing, still all messages in
  1106. # GRASS are already in en_US language.
  1107. # Using plain C as locale forces encodings to ascii
  1108. # thus lets try our luck with C.UTF-8 first.
  1109. # See bugs #3441 and #3423
  1110. try:
  1111. locale.setlocale(locale.LC_ALL, 'C.UTF-8')
  1112. except locale.Error as e:
  1113. # All lost. Setting to C as much as possible.
  1114. # We can not call locale.normalize on C as it
  1115. # will transform it to en_US and we already know
  1116. # it doesn't work.
  1117. locale.setlocale(locale.LC_ALL, 'C')
  1118. os.environ['LANGUAGE'] = 'C'
  1119. os.environ['LANG'] = 'C'
  1120. os.environ['LC_MESSAGES'] = 'C'
  1121. os.environ['LC_NUMERIC'] = 'C'
  1122. os.environ['LC_TIME'] = 'C'
  1123. gettext.install('grasslibs', gpath('locale'))
  1124. sys.stderr.write(
  1125. "All attempts to enable English language have"
  1126. " failed. GRASS running with C locale.\n"
  1127. "If you observe UnicodeError in Python,"
  1128. " install en_US.UTF-8"
  1129. " locale and restart GRASS.\n")
  1130. return
  1131. else:
  1132. # The last attempt...
  1133. try:
  1134. encoding = locale.getpreferredencoding()
  1135. normalized = locale.normalize('%s.%s' % (language, encoding))
  1136. locale.setlocale(locale.LC_ALL, normalized)
  1137. except locale.Error as e:
  1138. # If we got so far, attempts to set up language and locale have failed
  1139. # on this system
  1140. sys.stderr.write("Failed to enforce user specified language '%s' with error: '%s'\n" % (language, e))
  1141. sys.stderr.write("A LANGUAGE environmental variable has been set.\nPart of messages will be displayed in the requested language.\n")
  1142. # Even if setting locale will fail, let's set LANG in a hope,
  1143. # that UI will use it GRASS texts will be in selected language,
  1144. # system messages (i.e. OK, Cancel etc.) - in system default
  1145. # language
  1146. os.environ['LANGUAGE'] = language
  1147. os.environ['LANG'] = language
  1148. return
  1149. # Set up environment for subprocesses
  1150. os.environ['LANGUAGE'] = language
  1151. os.environ['LANG'] = language
  1152. if language == 'ko_KR' and encoding == 'cp949':
  1153. # The default encoding for the Korean language in Windows is cp949,
  1154. # Microsoft's proprietary extension to euc-kr, but gettext prints no
  1155. # translated messages at all in the Command Prompt window if LC_CTYPE
  1156. # is set to ko_KR.cp949. Here, force LC_CTYPE to be euc-kr.
  1157. normalized = 'euc-kr'
  1158. encoding = None
  1159. elif encoding:
  1160. normalized = locale.normalize('%s.%s' % (language, encoding))
  1161. else:
  1162. normalized = language
  1163. for lc in ('LC_CTYPE', 'LC_MESSAGES', 'LC_TIME', 'LC_COLLATE',
  1164. 'LC_MONETARY', 'LC_PAPER', 'LC_NAME', 'LC_ADDRESS',
  1165. 'LC_TELEPHONE', 'LC_MEASUREMENT', 'LC_IDENTIFICATION'):
  1166. os.environ[lc] = normalized
  1167. # Some code in GRASS might not like other decimal separators than .
  1168. # Other potential sources for problems are: LC_TIME LC_CTYPE
  1169. locale.setlocale(locale.LC_NUMERIC, 'C')
  1170. os.environ['LC_NUMERIC'] = 'C'
  1171. if os.getenv('LC_ALL'):
  1172. del os.environ['LC_ALL'] # Remove LC_ALL to not override LC_NUMERIC
  1173. # From now on enforce the new language
  1174. if encoding:
  1175. gettext.install('grasslibs', gpath('locale'), codeset=encoding)
  1176. else:
  1177. gettext.install('grasslibs', gpath('locale'))
  1178. # TODO: grass_gui parameter is a hack and should be removed, see below
  1179. def lock_mapset(mapset_path, force_gislock_removal, user, grass_gui):
  1180. """Lock the mapset and return name of the lock file
  1181. Behavior on error must be changed somehow; now it fatals but GUI case is
  1182. unresolved.
  1183. """
  1184. if not os.path.exists(mapset_path):
  1185. fatal(_("Path '%s' doesn't exist") % mapset_path)
  1186. if not os.access(mapset_path, os.W_OK):
  1187. error = _("Path '%s' not accessible.") % mapset_path
  1188. stat_info = os.stat(mapset_path)
  1189. mapset_uid = stat_info.st_uid
  1190. if mapset_uid != os.getuid():
  1191. # GTC %s is mapset's folder path
  1192. error = "%s\n%s" % (error, _("You are not the owner of '%s'.") % mapset_path)
  1193. fatal(error)
  1194. # Check for concurrent use
  1195. lockfile = os.path.join(mapset_path, ".gislock")
  1196. ret = call([gpath("etc", "lock"), lockfile, "%d" % os.getpid()])
  1197. msg = None
  1198. if ret == 2:
  1199. if not force_gislock_removal:
  1200. msg = _("%(user)s is currently running GRASS in selected mapset"
  1201. " (file %(file)s found). Concurrent use not allowed.\n"
  1202. "You can force launching GRASS using -f flag"
  1203. " (note that you need permission for this operation)."
  1204. " Have another look in the processor "
  1205. "manager just to be sure..." % {
  1206. 'user': user, 'file': lockfile})
  1207. else:
  1208. try_remove(lockfile)
  1209. message(_("%(user)s is currently running GRASS in selected mapset"
  1210. " (file %(file)s found). Forcing to launch GRASS..." % {
  1211. 'user': user, 'file': lockfile}))
  1212. elif ret != 0:
  1213. msg = _("Unable to properly access '%s'.\n"
  1214. "Please notify system personnel.") % lockfile
  1215. # TODO: the gui decision should be done by the caller
  1216. # this needs some change to the function interface, return tuple or
  1217. # use exceptions (better option)
  1218. if msg:
  1219. if grass_gui == "wxpython":
  1220. call([os.getenv('GRASS_PYTHON'), wxpath("gis_set_error.py"), msg])
  1221. # TODO: here we probably miss fatal or exit, needs to be added
  1222. else:
  1223. fatal(msg)
  1224. debug("Mapset <{mapset}> locked using '{lockfile}'".format(
  1225. mapset=mapset_path, lockfile=lockfile))
  1226. return lockfile
  1227. # TODO: the gisrcrc here does not make sense, remove it from load_gisrc
  1228. def unlock_gisrc_mapset(gisrc, gisrcrc):
  1229. """Unlock mapset from the gisrc file"""
  1230. settings = load_gisrc(gisrc, gisrcrc)
  1231. lockfile = os.path.join(settings.full_mapset, ".gislock")
  1232. # this fails silently, perhaps a warning would be helpful to
  1233. # catch cases when removal was not possible due to e.g. another
  1234. # session force-removing the file (unlocking the mapset)
  1235. try_remove(lockfile)
  1236. def make_fontcap():
  1237. # TODO: is GRASS_FONT_CAP ever defined? It seems it must be defined in system
  1238. fc = os.getenv('GRASS_FONT_CAP')
  1239. if fc and not os.access(fc, os.R_OK):
  1240. message(_("Building user fontcap..."))
  1241. call(["g.mkfontcap"])
  1242. def ensure_db_connected(mapset):
  1243. """Predefine default driver if DB connection not defined
  1244. :param mapset: full path to the mapset
  1245. """
  1246. if not os.access(os.path.join(mapset, "VAR"), os.F_OK):
  1247. call(['db.connect', '-c', '--quiet'])
  1248. def get_shell():
  1249. # set SHELL on ms windowns
  1250. # this was at the very beginning of the script but it can be anywhere
  1251. if windows:
  1252. if os.getenv('GRASS_SH'):
  1253. os.environ['SHELL'] = os.getenv('GRASS_SH')
  1254. if not os.getenv('SHELL'):
  1255. os.environ['SHELL'] = os.getenv('COMSPEC', 'cmd.exe')
  1256. # cygwin has many problems with the shell setup
  1257. # below, so i hardcoded everything here.
  1258. if sys.platform == 'cygwin':
  1259. sh = "cygwin"
  1260. shellname = "GNU Bash (Cygwin)"
  1261. os.environ['SHELL'] = "/usr/bin/bash.exe"
  1262. os.environ['OSTYPE'] = "cygwin"
  1263. else:
  1264. # in docker the 'SHELL' variable may not be
  1265. # visible in a Python session unless 'ENV SHELL /bin/bash' is set in Dockerfile
  1266. try:
  1267. sh = os.path.basename(os.getenv('SHELL'))
  1268. except:
  1269. sh = 'sh'
  1270. os.environ['SHELL'] = sh
  1271. if windows and sh:
  1272. sh = os.path.splitext(sh)[0]
  1273. if sh == "ksh":
  1274. shellname = "Korn Shell"
  1275. elif sh == "csh":
  1276. shellname = "C Shell"
  1277. elif sh == "tcsh":
  1278. shellname = "TC Shell"
  1279. elif sh == "bash":
  1280. shellname = "Bash Shell"
  1281. elif sh == "sh":
  1282. shellname = "Bourne Shell"
  1283. elif sh == "zsh":
  1284. shellname = "Z Shell"
  1285. elif sh == "cmd":
  1286. shellname = "Command Shell"
  1287. else:
  1288. shellname = "shell"
  1289. # check for SHELL
  1290. if not os.getenv('SHELL'):
  1291. fatal(_("The SHELL variable is not set"))
  1292. return sh, shellname
  1293. def get_grass_env_file(sh, grass_config_dir):
  1294. """Get name of the shell-specific GRASS environment (rc) file"""
  1295. if sh in ['csh', 'tcsh']:
  1296. grass_env_file = os.path.join(grass_config_dir, 'cshrc')
  1297. elif sh in ['bash', 'msh', 'cygwin', 'sh']:
  1298. grass_env_file = os.path.join(grass_config_dir, 'bashrc')
  1299. elif sh == 'zsh':
  1300. grass_env_file = os.path.join(grass_config_dir, 'zshrc')
  1301. elif sh == 'cmd':
  1302. grass_env_file = os.path.join(grass_config_dir, 'env.bat')
  1303. else:
  1304. grass_env_file = os.path.join(grass_config_dir, 'bashrc')
  1305. warning(_("Unsupported shell <{sh}>: {env_file}").format(
  1306. sh=sh, env_file=grass_env_file))
  1307. return grass_env_file
  1308. def get_batch_job_from_env_variable():
  1309. """Get script to execute from batch job variable if available
  1310. Fails with fatal if variable is set but content unusable.
  1311. """
  1312. # hack to process batch jobs:
  1313. batch_job = os.getenv('GRASS_BATCH_JOB')
  1314. # variable defined, but user might not have been careful enough
  1315. if batch_job:
  1316. if not os.access(batch_job, os.F_OK):
  1317. # wrong file
  1318. fatal(_("Job file <%s> has been defined in "
  1319. "the 'GRASS_BATCH_JOB' variable but not found. Exiting."
  1320. "\n\n"
  1321. "Use 'unset GRASS_BATCH_JOB' to disable "
  1322. "batch job processing.") % batch_job)
  1323. elif not os.access(batch_job, os.X_OK):
  1324. # right file, but ...
  1325. fatal(_("Change file permission to 'executable' for <%s>")
  1326. % batch_job)
  1327. return batch_job
  1328. def run_batch_job(batch_job):
  1329. """Runs script, module or any command
  1330. If *batch_job* is a string (insecure) shell=True is used for execution.
  1331. :param batch_job: executable and parameters in a list or a string
  1332. """
  1333. batch_job_string = batch_job
  1334. if not isinstance(batch_job, string_types):
  1335. # for messages only
  1336. batch_job_string = ' '.join(batch_job)
  1337. message(_("Executing <%s> ...") % batch_job_string)
  1338. if isinstance(batch_job, string_types):
  1339. # shell=True is keeping the original GRASS_BATCH_JOB behavior
  1340. def quote(string):
  1341. if '"' in string:
  1342. return "'%s'" % batch_job
  1343. else:
  1344. return '"%s"' % batch_job
  1345. batch_job = quote(batch_job)
  1346. proc = Popen(batch_job, shell=True)
  1347. else:
  1348. try:
  1349. proc = Popen(batch_job, shell=False)
  1350. except OSError as error:
  1351. fatal(_("Execution of <{cmd}> failed:\n"
  1352. "{error}").format(cmd=batch_job_string, error=error))
  1353. returncode = proc.wait()
  1354. message(_("Execution of <%s> finished.") % batch_job_string)
  1355. return returncode
  1356. def start_gui(grass_gui):
  1357. """Start specified GUI
  1358. :param grass_gui: GUI name (allowed values: 'wxpython')
  1359. """
  1360. # Start the chosen GUI but ignore text
  1361. debug("GRASS GUI should be <%s>" % grass_gui)
  1362. # Check for gui interface
  1363. if grass_gui == "wxpython":
  1364. Popen([os.getenv('GRASS_PYTHON'), wxpath("wxgui.py")])
  1365. def close_gui():
  1366. """Close GUI if running"""
  1367. if gpath('etc', 'python') not in sys.path:
  1368. sys.path.append(gpath('etc', 'python'))
  1369. from grass.script import core as gcore # pylint: disable=E0611
  1370. env = gcore.gisenv()
  1371. if 'GUI_PID' not in env:
  1372. return
  1373. import signal
  1374. for pid in env['GUI_PID'].split(','):
  1375. debug("Exiting GUI with pid={0}".format(pid))
  1376. try:
  1377. os.kill(int(pid), signal.SIGTERM)
  1378. except OSError as e:
  1379. message(_("Unable to close GUI. {0}").format(e))
  1380. def clear_screen():
  1381. """Clear terminal"""
  1382. if windows:
  1383. pass
  1384. # TODO: uncomment when PDCurses works.
  1385. # cls
  1386. else:
  1387. if not is_debug():
  1388. call(["tput", "clear"])
  1389. def show_banner():
  1390. """Write GRASS GIS ASCII name to stderr"""
  1391. sys.stderr.write(r"""
  1392. __________ ___ __________ _______________
  1393. / ____/ __ \/ | / ___/ ___/ / ____/ _/ ___/
  1394. / / __/ /_/ / /| | \__ \\_ \ / / __ / / \__ \
  1395. / /_/ / _, _/ ___ |___/ /__/ / / /_/ // / ___/ /
  1396. \____/_/ |_/_/ |_/____/____/ \____/___//____/
  1397. """)
  1398. def say_hello():
  1399. """Write welcome to stderr including Subversion revision if in svn copy"""
  1400. sys.stderr.write(_("Welcome to GRASS GIS %s") % grass_version)
  1401. if grass_version.endswith('svn'):
  1402. try:
  1403. filerev = open(gpath('etc', 'VERSIONNUMBER'))
  1404. linerev = filerev.readline().rstrip('\n')
  1405. filerev.close()
  1406. revision = linerev.split(' ')[1]
  1407. sys.stderr.write(' (' + revision + ')')
  1408. except:
  1409. pass
  1410. def show_info(shellname, grass_gui, default_gui):
  1411. """Write basic infor about GRASS GIS and GRASS session to stderr"""
  1412. sys.stderr.write(
  1413. r"""
  1414. %-41shttp://grass.osgeo.org
  1415. %-41s%s (%s)
  1416. %-41sg.manual -i
  1417. %-41sg.version -c
  1418. %-41sg.version -x
  1419. """ % (_("GRASS GIS homepage:"),
  1420. # GTC Running through: SHELL NAME
  1421. _("This version running through:"),
  1422. shellname, os.getenv('SHELL'),
  1423. _("Help is available with the command:"),
  1424. _("See the licence terms with:"),
  1425. _("See citation options with:")))
  1426. if grass_gui == 'wxpython':
  1427. message("%-41sg.gui wxpython" % _("If required, restart the GUI with:"))
  1428. else:
  1429. message("%-41sg.gui %s" % (_("Start the GUI with:"), default_gui))
  1430. message("%-41sexit" % _("When ready to quit enter:"))
  1431. message("")
  1432. def csh_startup(location, location_name, mapset, grass_env_file):
  1433. userhome = os.getenv('HOME') # save original home
  1434. home = location
  1435. os.environ['HOME'] = home
  1436. cshrc = os.path.join(home, ".cshrc")
  1437. tcshrc = os.path.join(home, ".tcshrc")
  1438. try_remove(cshrc)
  1439. try_remove(tcshrc)
  1440. f = open(cshrc, 'w')
  1441. f.write("set home = %s\n" % userhome)
  1442. f.write("set history = 3000 savehist = 3000 noclobber ignoreeof\n")
  1443. f.write("set histfile = %s\n" % os.path.join(os.getenv('HOME'),
  1444. ".history"))
  1445. f.write("set prompt = '\\\n")
  1446. f.write("Mapset <%s> in Location <%s> \\\n" % (mapset, location_name))
  1447. f.write("GRASS GIS %s > '\n" % grass_version)
  1448. f.write("set BOGUS=``;unset BOGUS\n")
  1449. # csh shell rc file left for backward compatibility
  1450. path = os.path.join(userhome, ".grass.cshrc")
  1451. if os.access(path, os.R_OK):
  1452. f.write(readfile(path) + '\n')
  1453. if os.access(grass_env_file, os.R_OK):
  1454. f.write(readfile(grass_env_file) + '\n')
  1455. mail_re = re.compile(r"^ *set *mail *= *")
  1456. for filename in [".cshrc", ".tcshrc", ".login"]:
  1457. path = os.path.join(userhome, filename)
  1458. if os.access(path, os.R_OK):
  1459. s = readfile(path)
  1460. lines = s.splitlines()
  1461. for l in lines:
  1462. if mail_re.match(l):
  1463. f.write(l)
  1464. path = os.getenv('PATH').split(':')
  1465. f.write("set path = ( %s ) \n" % ' '.join(path))
  1466. f.close()
  1467. writefile(tcshrc, readfile(cshrc))
  1468. process = Popen([gpath("etc", "run"), os.getenv('SHELL')])
  1469. os.environ['HOME'] = userhome
  1470. return process
  1471. def bash_startup(location, location_name, grass_env_file):
  1472. # save command history in mapset dir and remember more
  1473. os.environ['HISTFILE'] = os.path.join(location, ".bash_history")
  1474. if not os.getenv('HISTSIZE') and not os.getenv('HISTFILESIZE'):
  1475. os.environ['HISTSIZE'] = "3000"
  1476. # instead of changing $HOME, start bash with:
  1477. # --rcfile "$LOCATION/.bashrc" ?
  1478. # if so, must care be taken to explicitly call .grass.bashrc et al
  1479. # for non-interactive bash batch jobs?
  1480. userhome = os.getenv('HOME') # save original home
  1481. home = location # save .bashrc in $LOCATION
  1482. os.environ['HOME'] = home
  1483. bashrc = os.path.join(home, ".bashrc")
  1484. try_remove(bashrc)
  1485. f = open(bashrc, 'w')
  1486. f.write("test -r ~/.alias && . ~/.alias\n")
  1487. if os.getenv('ISISROOT'):
  1488. # GRASS GIS and ISIS blend
  1489. grass_name = "ISIS-GRASS"
  1490. else:
  1491. grass_name = "GRASS"
  1492. f.write("PS1='{name} {version} ({location}):\\w > '\n".format(
  1493. name=grass_name, version=grass_version, location=location_name))
  1494. # TODO: have a function and/or module to test this
  1495. mask2d_test = 'test -f "$MAPSET_PATH/cell/MASK"'
  1496. mask3d_test = 'test -d "$MAPSET_PATH/grid3/RASTER3D_MASK"'
  1497. # double curly brackets means single one for format function
  1498. # setting LOCATION for backwards compatibility
  1499. f.write(
  1500. """grass_prompt() {{
  1501. MAPSET_PATH="`g.gisenv get=GISDBASE,LOCATION_NAME,MAPSET separator='/'`"
  1502. LOCATION="$MAPSET_PATH"
  1503. if {mask2d_test} && {mask3d_test} ; then
  1504. echo [{both_masks}]
  1505. elif {mask2d_test} ; then
  1506. echo [{mask2d}]
  1507. elif {mask3d_test} ; then
  1508. echo [{mask3d}]
  1509. fi
  1510. }}
  1511. PROMPT_COMMAND=grass_prompt\n""".format(
  1512. both_masks=_("2D and 3D raster MASKs present"),
  1513. mask2d=_("Raster MASK present"),
  1514. mask3d=_("3D raster MASK present"),
  1515. mask2d_test=mask2d_test, mask3d_test=mask3d_test
  1516. ))
  1517. # read other settings (aliases, ...) since environmental variables
  1518. # have been already set by load_env(), see #3462
  1519. for env_file in [os.path.join(userhome, ".grass.bashrc"),
  1520. grass_env_file]:
  1521. if not os.access(env_file, os.R_OK):
  1522. continue
  1523. for line in readfile(env_file).splitlines():
  1524. # Bug related to OS X "SIP", see
  1525. # https://trac.osgeo.org/grass/ticket/3462#comment:13
  1526. if macosx or not line.startswith('export'):
  1527. f.write(line + '\n')
  1528. f.write("export PATH=\"%s\"\n" % os.getenv('PATH'))
  1529. f.write("export HOME=\"%s\"\n" % userhome) # restore user home path
  1530. f.close()
  1531. process = Popen([gpath("etc", "run"), os.getenv('SHELL')])
  1532. os.environ['HOME'] = userhome
  1533. return process
  1534. def default_startup(location, location_name):
  1535. if windows:
  1536. os.environ['PS1'] = "GRASS %s> " % (grass_version)
  1537. # "$ETC/run" doesn't work at all???
  1538. process = subprocess.Popen([os.getenv('SHELL')])
  1539. else:
  1540. os.environ['PS1'] = "GRASS %s (%s):\\w > " % (grass_version, location_name)
  1541. process = Popen([gpath("etc", "run"), os.getenv('SHELL')])
  1542. return process
  1543. def done_message():
  1544. # here was something for batch job but it was never called
  1545. message(_("Done."))
  1546. message("")
  1547. message(_("Goodbye from GRASS GIS"))
  1548. message("")
  1549. def clean_temp():
  1550. message(_("Cleaning up temporary files..."))
  1551. nul = open(os.devnull, 'w')
  1552. call([gpath("etc", "clean_temp")], stdout=nul)
  1553. nul.close()
  1554. def grep(pattern, lines):
  1555. """Search lines (list of strings) and return them when beginning matches.
  1556. >>> grep("a", ['abc', 'cab', 'sdr', 'aaa', 'sss'])
  1557. ['abc', 'aaa']
  1558. """
  1559. expr = re.compile(pattern)
  1560. return [elem for elem in lines if expr.match(elem)]
  1561. def print_params():
  1562. """Write compile flags and other configuration to stderr"""
  1563. plat = gpath('include', 'Make', 'Platform.make')
  1564. if not os.path.exists(plat):
  1565. fatal(_("Please install the GRASS GIS development package"))
  1566. fileplat = open(plat)
  1567. linesplat = fileplat.readlines()
  1568. fileplat.close()
  1569. params = sys.argv[2:]
  1570. if not params:
  1571. params = ['arch', 'build', 'compiler', 'path', 'revision', 'version']
  1572. for arg in params:
  1573. if arg == 'path':
  1574. sys.stdout.write("%s\n" % gisbase)
  1575. elif arg == 'arch':
  1576. val = grep('ARCH', linesplat)
  1577. sys.stdout.write("%s\n" % val[0].split('=')[1].strip())
  1578. elif arg == 'build':
  1579. build = gpath('include', 'grass', 'confparms.h')
  1580. filebuild = open(build)
  1581. val = filebuild.readline()
  1582. filebuild.close()
  1583. sys.stdout.write("%s\n" % val.strip().strip('"').strip())
  1584. elif arg == 'compiler':
  1585. val = grep('CC', linesplat)
  1586. sys.stdout.write("%s\n" % val[0].split('=')[1].strip())
  1587. elif arg == 'revision':
  1588. rev = gpath('include', 'grass', 'gis.h')
  1589. filerev = open(rev)
  1590. linesrev = filerev.readlines()
  1591. val = grep('#define GIS_H_VERSION', linesrev)
  1592. filerev.close()
  1593. sys.stdout.write(
  1594. "%s\n" % val[0].split(':')[1].rstrip('$"\n').strip())
  1595. elif arg == 'version':
  1596. sys.stdout.write("%s\n" % grass_version)
  1597. else:
  1598. message(_("Parameter <%s> not supported") % arg)
  1599. def get_username():
  1600. """Get name of the current user"""
  1601. if windows:
  1602. user = os.getenv('USERNAME')
  1603. if not user:
  1604. user = "user_name"
  1605. else:
  1606. user = os.getenv('USER')
  1607. if not user:
  1608. user = os.getenv('LOGNAME')
  1609. if not user:
  1610. try:
  1611. p = Popen(['whoami'], stdout=subprocess.PIPE)
  1612. s = p.stdout.read()
  1613. p.wait()
  1614. user = s.strip()
  1615. except:
  1616. pass
  1617. if not user:
  1618. user = "user_%d" % os.getuid()
  1619. return user
  1620. class Parameters(object):
  1621. """Structure to hold standard part of command line parameters"""
  1622. # we don't need to define any methods
  1623. # pylint: disable=R0903
  1624. def __init__(self):
  1625. self.grass_gui = None
  1626. self.create_new = None
  1627. self.exit_grass = None
  1628. self.force_gislock_removal = None
  1629. self.mapset = None
  1630. self.geofile = None
  1631. self.tmp_location = False
  1632. def parse_cmdline(argv, default_gui):
  1633. """Parse the standard part of command line parameters"""
  1634. params = Parameters()
  1635. args = []
  1636. for i in argv:
  1637. # Check if the user asked for the version
  1638. if i in ["-v", "--version"]:
  1639. message("GRASS GIS %s" % grass_version)
  1640. message('\n' + readfile(gpath("etc", "license")))
  1641. sys.exit()
  1642. # Check if the user asked for help
  1643. elif i in ["help", "-h", "-help", "--help", "--h"]:
  1644. help_message(default_gui=default_gui)
  1645. sys.exit()
  1646. # Check if the --text flag was given
  1647. elif i in ["-text", "--text"]:
  1648. params.grass_gui = 'text'
  1649. # Check if the --gtext flag was given
  1650. elif i in ["-gtext", "--gtext"]:
  1651. params.grass_gui = 'gtext'
  1652. # Check if the --gui flag was given
  1653. elif i in ["-gui", "--gui"]:
  1654. params.grass_gui = default_gui
  1655. # Check if the -wxpython flag was given
  1656. elif i in ["-wxpython", "-wx", "--wxpython", "--wx"]:
  1657. params.grass_gui = 'wxpython'
  1658. # Check if the user wants to create a new mapset
  1659. elif i == "-c":
  1660. params.create_new = True
  1661. elif i == "-e":
  1662. params.exit_grass = True
  1663. elif i == "-f":
  1664. params.force_gislock_removal = True
  1665. elif i == "--config":
  1666. print_params()
  1667. sys.exit()
  1668. elif i == "--tmp-location":
  1669. params.tmp_location = True
  1670. else:
  1671. args.append(i)
  1672. if len(args) > 1:
  1673. params.mapset = args[1]
  1674. params.geofile = args[0]
  1675. elif len(args) == 1:
  1676. if params.tmp_location:
  1677. params.geofile = args[0]
  1678. else:
  1679. params.mapset = args[0]
  1680. else:
  1681. params.mapset = None
  1682. return params
  1683. # The main script starts here
  1684. # Get the system name
  1685. windows = sys.platform == 'win32'
  1686. cygwin = "cygwin" in sys.platform
  1687. macosx = "darwin" in sys.platform
  1688. # TODO: it is OK to remove this?
  1689. # at the beginning of this file were are happily getting GISBASE
  1690. # from the environment and we don't care about inconsistencies it might cause
  1691. # The following was commented out because of breaking winGRASS
  1692. # if 'GISBASE' in os.environ:
  1693. # sys.exit(_("ERROR: GRASS GIS is already running "
  1694. # "(environmental variable GISBASE found)"))
  1695. # this is not really an issue, we should be able to overpower another session
  1696. # Set GISBASE
  1697. os.environ['GISBASE'] = gisbase
  1698. def main():
  1699. """The main function which does the whole setup and run procedure
  1700. Only few things are set on the module level.
  1701. """
  1702. # Set default GUI
  1703. default_gui = "wxpython"
  1704. # explain what is happening in debug mode (visible only in debug mode)
  1705. debug("GRASS_DEBUG environmental variable is set. It is meant to be"
  1706. " an internal variable for debugging only this script.\n"
  1707. " Use 'g.gisenv set=\"DEBUG=[0-5]\"'"
  1708. " to turn GRASS GIS debug mode on if you wish to do so.")
  1709. # Set GRASS version number for R interface etc
  1710. # (must be an env var for MS Windows)
  1711. os.environ['GRASS_VERSION'] = grass_version
  1712. # Set the GIS_LOCK variable to current process id
  1713. gis_lock = str(os.getpid())
  1714. os.environ['GIS_LOCK'] = gis_lock
  1715. grass_config_dir = get_grass_config_dir()
  1716. batch_job = get_batch_job_from_env_variable()
  1717. # Parse the command-line options and set several global variables
  1718. batch_exec_param = '--exec'
  1719. try:
  1720. # raises ValueError when not found
  1721. index = sys.argv.index(batch_exec_param)
  1722. batch_job = sys.argv[index + 1:]
  1723. clean_argv = sys.argv[1:index]
  1724. params = parse_cmdline(clean_argv, default_gui=default_gui)
  1725. except ValueError:
  1726. params = parse_cmdline(sys.argv[1:], default_gui=default_gui)
  1727. if params.exit_grass and not params.create_new:
  1728. fatal(_("Flag -e requires also flag -c"))
  1729. if params.tmp_location and not params.geofile:
  1730. fatal(_("Coordinate reference system argument (e.g. EPSG)"
  1731. " is needed for --tmp-location"))
  1732. if params.tmp_location and params.mapset:
  1733. fatal(_("Only one argument (e.g. EPSG) is needed for"
  1734. " --tmp-location, mapset name <{}> provided").format(
  1735. params.mapset))
  1736. # For now, we allow, but not advertise/document, --tmp-location
  1737. # without --exec (usefulness to be evaluated).
  1738. grass_gui = params.grass_gui # put it to variable, it is used a lot
  1739. # TODO: with --tmp-location there is no point in loading settings
  1740. # i.e. rc file from home dir, but the code is too spread out
  1741. # to disable it at this point
  1742. gisrcrc = get_gisrc_from_config_dir(grass_config_dir, batch_job)
  1743. # Set the username
  1744. user = get_username()
  1745. # TODO: this might need to be moved before processing of parameters
  1746. # and getting batch job
  1747. # Set language
  1748. # This has to be called before any _() function call!
  1749. # Subsequent functions are using _() calls and
  1750. # thus must be called only after Language has been set.
  1751. set_language(grass_config_dir)
  1752. # Set shell (needs to be called before load_env())
  1753. sh, shellname = get_shell()
  1754. grass_env_file = get_grass_env_file(sh, grass_config_dir)
  1755. # Load environmental variables from the file (needs to be called
  1756. # before create_tmp())
  1757. load_env(grass_env_file)
  1758. # Create the temporary directory and session grassrc file
  1759. tmpdir = create_tmp(user, gis_lock)
  1760. cleaner = Cleaner()
  1761. cleaner.tmpdir = tmpdir
  1762. # object is not destroyed when its method is registered
  1763. atexit.register(cleaner.cleanup)
  1764. # Create the session grassrc file
  1765. gisrc = create_gisrc(tmpdir, gisrcrc)
  1766. ensure_home()
  1767. # Set PATH, PYTHONPATH, ...
  1768. set_paths(grass_config_dir=grass_config_dir)
  1769. # Set GRASS_PAGER, GRASS_PYTHON, GRASS_GNUPLOT, GRASS_PROJSHARE
  1770. set_defaults()
  1771. set_display_defaults()
  1772. # Set GRASS_HTML_BROWSER
  1773. set_browser()
  1774. # First time user - GISRC is defined in the GRASS script
  1775. if not os.access(gisrc, os.F_OK):
  1776. if grass_gui == 'text' and not params.mapset:
  1777. fatal(_("Unable to start GRASS GIS. You have the choice to:\n"
  1778. " - Launch the graphical user interface with"
  1779. " the '--gui' switch\n"
  1780. " {cmd_name} --gui\n"
  1781. " - Launch with path to "
  1782. "the location/mapset as an argument\n"
  1783. " {cmd_name} /path/to/location/mapset`\n"
  1784. " - Create a location with '-c' and launch in its"
  1785. " PERMANENT mapset\n"
  1786. " {cmd_name} -c EPSG:number /path/to/location\n"
  1787. " {cmd_name} -c geofile /path/to/location\n"
  1788. " - Create manually the GISRC file ({gisrcrc})\n"
  1789. " - Use '--help' for further options\n"
  1790. " {cmd_name} --help\n"
  1791. "See also: https://grass.osgeo.org/{cmd_name}/manuals/helptext.html").format(
  1792. cmd_name=cmd_name, gisrcrc=gisrcrc))
  1793. create_initial_gisrc(gisrc)
  1794. message(_("Starting GRASS GIS..."))
  1795. # Ensure GUI is set
  1796. if batch_job or params.exit_grass:
  1797. grass_gui = 'text'
  1798. else:
  1799. if not grass_gui:
  1800. # if GUI was not set previously (e.g. command line),
  1801. # get it from rc file or env variable
  1802. grass_gui = read_gui(gisrc, default_gui)
  1803. # check that the GUI works but only if not doing a batch job
  1804. grass_gui = check_gui(expected_gui=grass_gui)
  1805. # save GUI only if we are not doibg batch job
  1806. save_gui(gisrc, grass_gui)
  1807. # Parsing argument to get LOCATION
  1808. if not params.mapset and not params.tmp_location:
  1809. # Try interactive startup
  1810. # User selects LOCATION and MAPSET if not set
  1811. if not set_mapset_interactive(grass_gui):
  1812. # No GUI available, update gisrc file
  1813. fatal(_("<{0}> requested, but not available. Run GRASS in text "
  1814. "mode (--text) or install missing package (usually "
  1815. "'grass-gui').").format(grass_gui))
  1816. else:
  1817. # Try non-interactive start up
  1818. if params.tmp_location:
  1819. # tmp loc requires other things to be set as well
  1820. set_mapset(gisrc=gisrc, geofile=params.geofile,
  1821. create_new=True,
  1822. tmp_location=params.tmp_location, tmpdir=tmpdir)
  1823. elif params.create_new and params.geofile:
  1824. set_mapset(gisrc=gisrc, arg=params.mapset,
  1825. geofile=params.geofile, create_new=True)
  1826. else:
  1827. set_mapset(gisrc=gisrc, arg=params.mapset,
  1828. create_new=params.create_new)
  1829. # Set GISDBASE, LOCATION_NAME, MAPSET, LOCATION from $GISRC
  1830. # e.g. wxGUI startup screen writes to the gisrc file,
  1831. # so loading it is the only universal way to obtain the values
  1832. # this suppose that both programs share the right path to gisrc file
  1833. # TODO: perhaps gisrcrc should be removed from here
  1834. # alternatively, we can check validity here with all the info we have
  1835. # about what was used to create gisrc
  1836. mapset_settings = load_gisrc(gisrc, gisrcrc=gisrcrc)
  1837. location = mapset_settings.full_mapset
  1838. # check and create .gislock file
  1839. lock_mapset(mapset_settings.full_mapset, user=user,
  1840. force_gislock_removal=params.force_gislock_removal,
  1841. grass_gui=grass_gui)
  1842. # unlock the mapset which is current at the time of turning off
  1843. # in case mapset was changed
  1844. atexit.register(lambda: unlock_gisrc_mapset(gisrc, gisrcrc))
  1845. # We now own the mapset (set and lock), so we can clean temporary
  1846. # files which previous session may have left behind. We do it even
  1847. # for first time user because the cost is low and first time user
  1848. # doesn't necessarily mean that the mapset is used for the first time.
  1849. clean_temp()
  1850. # clean always at exit, cleans whatever is current mapset based on
  1851. # the GISRC env variable
  1852. atexit.register(clean_temp)
  1853. # build user fontcap if specified but not present
  1854. make_fontcap()
  1855. # TODO: is this really needed? Modules should call this when/if required.
  1856. ensure_db_connected(location)
  1857. # Display the version and license info
  1858. # only non-error, interactive version continues from here
  1859. if batch_job:
  1860. returncode = run_batch_job(batch_job)
  1861. sys.exit(returncode)
  1862. elif params.exit_grass:
  1863. sys.exit(0)
  1864. else:
  1865. clear_screen()
  1866. show_banner()
  1867. say_hello()
  1868. show_info(shellname=shellname,
  1869. grass_gui=grass_gui, default_gui=default_gui)
  1870. if grass_gui == "wxpython":
  1871. message(_("Launching <%s> GUI in the background, please wait...")
  1872. % grass_gui)
  1873. if sh in ['csh', 'tcsh']:
  1874. shell_process = csh_startup(mapset_settings.full_mapset,
  1875. mapset_settings.location,
  1876. mapset_settings.mapset,
  1877. grass_env_file)
  1878. elif sh in ['bash', 'msh', 'cygwin']:
  1879. shell_process = bash_startup(mapset_settings.full_mapset,
  1880. mapset_settings.location,
  1881. grass_env_file)
  1882. else:
  1883. shell_process = default_startup(mapset_settings.full_mapset,
  1884. mapset_settings.location)
  1885. # start GUI and register shell PID in rc file
  1886. start_gui(grass_gui)
  1887. kv = read_gisrc(gisrc)
  1888. kv['PID'] = str(shell_process.pid)
  1889. write_gisrc(kv, gisrc)
  1890. exit_val = shell_process.wait()
  1891. if exit_val != 0:
  1892. warning(_("Failed to start shell '%s'") % os.getenv('SHELL'))
  1893. # close GUI if running
  1894. close_gui()
  1895. # here we are at the end of grass session
  1896. clear_screen()
  1897. # save 'last used' GISRC after removing variables which shouldn't
  1898. # be saved, e.g. d.mon related
  1899. clean_env(gisrc)
  1900. if not params.tmp_location:
  1901. writefile(gisrcrc, readfile(gisrc))
  1902. # After this point no more grass modules may be called
  1903. done_message()
  1904. if __name__ == '__main__':
  1905. main()