grass.py 68 KB

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