grass.py 65 KB

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