grass.py 55 KB

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