grass.py 79 KB

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