grass.py 58 KB

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