grass.py 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  1. #!/usr/bin/env python
  2. #############################################################################
  3. #
  4. # MODULE: GRASS initialization (Python)
  5. # AUTHOR(S): Original author unknown - probably CERL
  6. # Andreas Lange - Germany - andreas.lange at rhein-main.de
  7. # Huidae Cho - Korea - grass4u at gmail.com
  8. # Justin Hickey - Thailand - jhickey at hpcc.nectec.or.th
  9. # Markus Neteler - Germany/Italy - neteler at itc.it
  10. # Hamish Bowman - New Zealand - hamish_b at yahoo,com
  11. # Converted to Python (based on init.sh) by Glynn Clements
  12. # Martin Landa - Czech Republic - landa.martin at gmail.com
  13. # PURPOSE: Sets up some environment variables.
  14. # It also parses any remaining command line options for
  15. # setting the GISDBASE, LOCATION, and/or MAPSET.
  16. # Finally it starts GRASS with the appropriate user
  17. # interface and cleans up after it is finished.
  18. # COPYRIGHT: (C) 2000-2010 by the GRASS Development Team
  19. #
  20. # This program is free software under the GNU General
  21. # Public License (>=v2). Read the file COPYING that
  22. # comes with GRASS for details.
  23. #
  24. #############################################################################
  25. import sys
  26. import os
  27. import atexit
  28. import string
  29. import subprocess
  30. import re
  31. # Variables substituted during build process
  32. # Set the GISBASE variable
  33. gisbase = "@GISBASE@"
  34. cmd_name = "@START_UP@"
  35. grass_version = "@GRASS_VERSION_NUMBER@"
  36. ld_library_path_var = '@LD_LIBRARY_PATH_VAR@'
  37. config_projshare = "@CONFIG_PROJSHARE@"
  38. grass_config_dirname = "@GRASS_CONFIG_DIR@"
  39. gisbase = os.path.normpath(gisbase)
  40. ### i18N
  41. import gettext
  42. gettext.install('grasslibs', os.path.join(gisbase, 'locale'), unicode=True)
  43. tmpdir = None
  44. lockfile = None
  45. location = None
  46. create_new = None
  47. grass_gui = None
  48. def try_remove(path):
  49. try:
  50. os.remove(path)
  51. except:
  52. pass
  53. def try_rmdir(path):
  54. try:
  55. os.rmdir(path)
  56. except:
  57. pass
  58. def cleanup_dir(dir):
  59. if not dir:
  60. return
  61. for root, dirs, files in os.walk(dir, topdown = False):
  62. for name in files:
  63. try_remove(os.path.join(root, name))
  64. for name in dirs:
  65. try_rmdir(os.path.join(root, name))
  66. def cleanup():
  67. tmpdir, lockfile
  68. # all exits after setting up $tmpdir should also tidy it up
  69. cleanup_dir(tmpdir)
  70. if lockfile:
  71. try_remove(lockfile)
  72. def fatal(msg):
  73. sys.exit(msg)
  74. def message(msg):
  75. sys.stderr.write(msg + "\n")
  76. sys.stderr.flush()
  77. def readfile(path):
  78. f = open(path, 'r')
  79. s = f.read()
  80. f.close()
  81. return s
  82. def writefile(path, s):
  83. f = open(path, 'w')
  84. f.write(s)
  85. f.close()
  86. def call(cmd, **kwargs):
  87. if windows:
  88. kwargs['shell'] = True
  89. return subprocess.call(cmd, **kwargs)
  90. def Popen(cmd, **kwargs):
  91. if windows:
  92. kwargs['shell'] = True
  93. return subprocess.Popen(cmd, **kwargs)
  94. def gfile(*args):
  95. return os.path.join(gisbase, *args)
  96. help_text = r"""
  97. %s:
  98. $CMD_NAME [-h | -help | --help] [-v | --version] [-c]
  99. [-text | -gui | -wxpython | -wx]
  100. [[[<GISDBASE>/]<LOCATION_NAME>/]<MAPSET>]
  101. %s:
  102. -h or -help or --help %s
  103. -v or --version %s
  104. -c %s
  105. -text %s
  106. %s
  107. -gui %s
  108. %s
  109. -wxpython or -wx %s
  110. %s
  111. %s:
  112. GISDBASE %s
  113. LOCATION_NAME %s
  114. MAPSET %s
  115. GISDBASE/LOCATION_NAME/MAPSET %s
  116. %s:
  117. GRASS_GUI %s
  118. GRASS_WISH %s
  119. GRASS_HTML_BROWSER %s
  120. GRASS_ADDON_PATH %s
  121. GRASS_BATCH_JOB %s
  122. GRASS_PYTHON %s
  123. """ % (_("Usage"),
  124. _("Flags"),
  125. _("print this help message"),
  126. _("show version information and exit"),
  127. _("create given mapset if it doesn't exist"),
  128. _("use text based interface"),
  129. _("and set as default"),
  130. _("use graphical user interface ($DEFAULT_GUI by default)"),
  131. _("and set as default"),
  132. _("use wxPython based graphical user interface"),
  133. _("and set as default"),
  134. _("Parameters"),
  135. _("initial database (path to GIS data)"),
  136. _("initial location"),
  137. _("initial mapset"),
  138. _("fully qualified initial mapset directory"),
  139. _("Environment variables relevant for startup"),
  140. _("select GUI (text, gui, wxpython)"),
  141. _("set wish shell name to override 'wish'"),
  142. _("set html web browser for help pages"),
  143. _("set additional path(s) to local GRASS modules"),
  144. _("shell script to be processed as batch job"),
  145. _("set python shell name to override 'python'"))
  146. def help_message():
  147. t = string.Template(help_text)
  148. s = t.substitute(CMD_NAME = cmd_name, DEFAULT_GUI = default_gui)
  149. sys.stderr.write(s)
  150. def create_tmp():
  151. global tmpdir
  152. ## use $TMPDIR if it exists, then $TEMP, otherwise /tmp
  153. tmp = os.getenv('TMPDIR')
  154. if not tmp:
  155. tmp = os.getenv('TEMP')
  156. if not tmp:
  157. tmp = '/tmp'
  158. tmpdir = os.path.join(tmp, "grass7-%s-%s" % (user, gis_lock))
  159. try:
  160. os.mkdir(tmpdir, 0700)
  161. except:
  162. fatal(_("Unable to create temporary directory! Exiting."))
  163. def create_gisrc():
  164. global gisrc, gisrcrc
  165. # Set the session grassrc file
  166. gisrc = os.path.join(tmpdir, "gisrc")
  167. os.environ['GISRC'] = gisrc
  168. # remove invalid GISRC file to avoid disturbing error messages:
  169. try:
  170. s = readfile(gisrcrc)
  171. if "UNKNOWN" in s:
  172. try_remove(gisrcrc)
  173. s = None
  174. except:
  175. s = None
  176. # Copy the global grassrc file to the session grassrc file
  177. if s:
  178. writefile(gisrc, s)
  179. def read_gisrc():
  180. kv = {}
  181. f = open(gisrc, 'r')
  182. for line in f:
  183. k, v = line.split(':', 1)
  184. kv[k.strip()] = v.strip()
  185. f.close()
  186. return kv
  187. def write_gisrc(kv):
  188. f = open(gisrc, 'w')
  189. for k, v in kv.iteritems():
  190. f.write("%s: %s\n" % (k, v))
  191. f.close()
  192. def read_gui():
  193. global grass_gui
  194. # At this point the GRASS user interface variable has been set from the
  195. # command line, been set from an external environment variable, or is
  196. # not set. So we check if it is not set
  197. if not grass_gui:
  198. # Check for a reference to the GRASS user interface in the grassrc file
  199. if os.access(gisrc, os.R_OK):
  200. kv = read_gisrc()
  201. if not kv.has_key('GRASS_GUI'):
  202. # Set the GRASS user interface to the default if needed
  203. grass_gui = default_gui
  204. else:
  205. grass_gui = kv['GRASS_GUI']
  206. if not grass_gui:
  207. grass_gui = default_gui
  208. if grass_gui == 'gui':
  209. grass_gui = default_gui
  210. # FIXME oldtcltk, gis.m, d.m no longer exist
  211. if grass_gui in ['d.m', 'gis.m', 'oldtcltk', 'tcltk']:
  212. grass_gui = default_gui
  213. def get_locale():
  214. global locale
  215. locale = None
  216. for var in ['LC_ALL', 'LC_MESSAGES', 'LANG']:
  217. loc = os.getenv(var)
  218. if loc:
  219. locale = loc[0:2]
  220. return
  221. def path_prepend(dir, var):
  222. path = os.getenv(var)
  223. if path:
  224. path = dir + os.pathsep + path
  225. else:
  226. path = dir
  227. os.environ[var] = path
  228. def path_append(dir, var):
  229. path = os.getenv(var)
  230. if path:
  231. path = path + os.pathsep + dir
  232. else:
  233. path = dir
  234. os.environ[var] = path
  235. def set_paths():
  236. addon_path = os.getenv('GRASS_ADDON_PATH')
  237. if addon_path:
  238. path_prepend(addon_path, 'PATH')
  239. path_prepend(gfile('scripts'), 'PATH')
  240. path_prepend(gfile('bin'), 'PATH')
  241. # Set PYTHONPATH to find GRASS Python modules
  242. path_prepend(gfile('etc', 'python'), 'PYTHONPATH')
  243. # Add .py (Python) to list of executable extensions to search for in MS-Windows PATH
  244. if windows:
  245. path_append('.PY', 'PATHEXT')
  246. def find_exe(pgm):
  247. for dir in os.getenv('PATH').split(os.pathsep):
  248. path = os.path.join(dir, pgm)
  249. if os.access(path, os.X_OK):
  250. return path
  251. return None
  252. def set_defaults():
  253. # GRASS_PAGER
  254. if not os.getenv('GRASS_PAGER'):
  255. if find_exe("more"):
  256. pager = "more"
  257. elif find_exe("less"):
  258. pager = "less"
  259. elif windows:
  260. pager = "more"
  261. else:
  262. pager = "cat"
  263. os.environ['GRASS_PAGER'] = pager
  264. # GRASS_WISH
  265. if not os.getenv('GRASS_WISH'):
  266. os.environ['GRASS_WISH'] = "wish"
  267. # GRASS_PYTHON
  268. if not os.getenv('GRASS_PYTHON'):
  269. if windows:
  270. os.environ['GRASS_PYTHON'] = "python.exe"
  271. else:
  272. os.environ['GRASS_PYTHON'] = "python"
  273. # GRASS_GNUPLOT
  274. if not os.getenv('GRASS_GNUPLOT'):
  275. os.environ['GRASS_GNUPLOT'] = "gnuplot -persist"
  276. # GRASS_PROJSHARE
  277. if not os.getenv('GRASS_PROJSHARE'):
  278. os.environ['GRASS_PROJSHARE'] = config_projshare
  279. def set_browser():
  280. # GRASS_HTML_BROWSER
  281. browser = os.getenv('GRASS_HTML_BROWSER')
  282. if not browser:
  283. if macosx:
  284. # OSX doesn't execute browsers from the shell PATH - route thru a script
  285. browser = gfile('etc', "html_browser_mac.sh")
  286. os.environ['GRASS_HTML_BROWSER_MACOSX'] = "-b com.apple.helpviewer"
  287. if windows or cygwin:
  288. # MinGW startup moved to into init.bat
  289. browser = "explorer"
  290. else:
  291. # the usual suspects
  292. browsers = [ "xdg-open", "htmlview", "konqueror", "mozilla", "mozilla-firefox",
  293. "firefox", "iceweasel", "opera", "netscape", "dillo", "lynx", "links", "w3c" ]
  294. for b in browsers:
  295. if find_exe(b):
  296. browser = b
  297. break
  298. elif macosx:
  299. # OSX doesn't execute browsers from the shell PATH - route thru a script
  300. os.environ['GRASS_HTML_BROWSER_MACOSX'] = "-b %s" % browser
  301. browser = gfile('etc', "html_browser_mac.sh")
  302. if not browser:
  303. warning(_("Searched for a web browser, but none found"))
  304. # even so we set konqueror to make lib/gis/parser.c happy:
  305. browser = "konqueror"
  306. os.environ['GRASS_HTML_BROWSER'] = browser
  307. def grass_intro():
  308. if locale:
  309. path = gfile("locale", locale, "etc", "grass_intro")
  310. if not os.access(path, os.R_OK):
  311. path = gfile("etc", "grass_intro")
  312. else:
  313. path = gfile("etc", "grass_intro")
  314. f = open(path, 'r')
  315. for line in f:
  316. sys.stderr.write(line)
  317. f.close()
  318. sys.stderr.write("\n")
  319. sys.stderr.write(_("Hit RETURN to continue"))
  320. sys.stdin.readline()
  321. #for convenience, define pwd as GISDBASE:
  322. s = r"""GISDBASE: %s
  323. LOCATION_NAME: <UNKNOWN>
  324. MAPSET: <UNKNOWN>
  325. """ % os.getcwd()
  326. writefile(gisrc, s)
  327. def check_gui():
  328. global grass_gui, wxpython_base
  329. # Check if we are running X windows by checking the DISPLAY variable
  330. if os.getenv('DISPLAY') or windows:
  331. # Check if python is working properly
  332. if grass_gui == 'wxpython':
  333. nul = open(os.devnull, 'w')
  334. p = Popen([os.environ['GRASS_PYTHON']],
  335. stdin = subprocess.PIPE,
  336. stdout = nul, stderr = nul)
  337. nul.close()
  338. p.stdin.write("variable=True")
  339. p.stdin.close()
  340. p.wait()
  341. if p.returncode == 0:
  342. # Set the wxpython base directory
  343. wxpython_base = gfile("etc", "gui", "wxpython")
  344. else:
  345. # Python was not found - switch to text interface mode
  346. warning(_("The python command does not work as expected!\n"
  347. "Please check your GRASS_PYTHON environment variable.\n"
  348. "Use the -help option for details.\n"
  349. "Switching to text based interface mode.\n\n"
  350. "Hit RETURN to continue.\n"))
  351. sys.stdin.readline()
  352. grass_gui = 'text'
  353. else:
  354. # Display a message if a graphical interface was expected
  355. if grass_gui != 'text':
  356. # Set the interface mode to text
  357. warning(_("It appears that the X Windows system is not active.\n"
  358. "A graphical based user interface is not supported.\n"
  359. "Switching to text based interface mode.\n\n"
  360. "Hit RETURN to continue"""))
  361. sys.stdin.readline()
  362. grass_gui = 'text'
  363. # Save the user interface variable in the grassrc file - choose a temporary
  364. # file name that should not match another file
  365. if os.access(gisrc, os.F_OK):
  366. kv = read_gisrc()
  367. kv['GRASS_GUI'] = grass_gui
  368. write_gisrc(kv)
  369. def non_interactive(arg):
  370. global gisdbase, location_name, mapset, location
  371. # Try non-interactive startup
  372. l = None
  373. if arg == '-':
  374. if location:
  375. l = location
  376. else:
  377. l = arg
  378. if l:
  379. if l == '.':
  380. l = os.getcwd()
  381. elif not os.path.isabs(l):
  382. l = os.path.abspath(l)
  383. l, mapset = os.path.split(l)
  384. if not mapset:
  385. l, mapset = os.path.split(l)
  386. l, location_name = os.path.split(l)
  387. gisdbase = l
  388. if gisdbase and location_name and mapset:
  389. location = os.path.join(gisdbase, location_name, mapset)
  390. if not os.access(os.path.join(location, "WIND"), os.R_OK):
  391. if location_name == "PERMANENT":
  392. fatal(_("<%s> is not a valid GRASS location") % location)
  393. else:
  394. # the user wants to create mapset on the fly
  395. if create_new:
  396. if not os.access(os.path.join(os.path.join(gisdbase, location_name, "PERMANENT", "DEFAULT_WIND")), os.F_OK):
  397. fatal(_("The location <%s> does not exist. Please create it first.") % location_name)
  398. else:
  399. os.mkdirs(location)
  400. # copy PERMANENT/DEFAULT_WIND to <mapset>/WIND
  401. s = readfile(os.path.join(gisdbase, location_name, "PERMANENT", "DEFAULT_WIND"))
  402. writefile(os.path.join(location, "WIND"), s)
  403. message(_("Missing WIND file fixed"))
  404. else:
  405. fatal(_("<%s> is not a valid GRASS location") % location)
  406. if os.access(gisrc, os.R_OK):
  407. kv = read_gisrc()
  408. else:
  409. kv = {}
  410. kv['GISDBASE'] = gisdbase
  411. kv['LOCATION_NAME'] = location_name
  412. kv['MAPSET'] = mapset
  413. write_gisrc(kv)
  414. else:
  415. fatal(_("GISDBASE, LOCATION_NAME and MAPSET variables not set properly.\n"
  416. "Interactive startup needed."))
  417. def set_data():
  418. # User selects LOCATION and MAPSET if not set
  419. if not location:
  420. # Check for text interface
  421. if grass_gui == 'text':
  422. pass
  423. # Check for GUI
  424. elif grass_gui == 'wxpython':
  425. gui_startup()
  426. else:
  427. # Shouldn't need this but you never know
  428. fatal(_("Invalid user interface specified - <%s>.\n"
  429. "Use the --help option to see valid interface names.") % grass_gui)
  430. def gui_startup():
  431. if grass_gui == 'wxpython':
  432. thetest = call([os.getenv('GRASS_PYTHON'),
  433. gfile(wxpython_base, "gis_set.py")])
  434. if thetest == 0:
  435. pass
  436. elif thetest == 1:
  437. # The startup script printed an error message so wait
  438. # for user to read it
  439. message(_("Error in GUI startup. If necessary, please "
  440. "report this error to the GRASS developers.\n"
  441. "Switching to text mode now.\n\n"
  442. "Hit RETURN to continue..."))
  443. sys.stdin.readline()
  444. os.execlp(cmd_name, "-text")
  445. sys.exit(1)
  446. elif thetest == 2:
  447. # User wants to exit from GRASS
  448. message(_("Received EXIT message from GUI.\nGRASS is not started. Bye."))
  449. sys.exit(0)
  450. else:
  451. fatal(_("Invalid return code from GUI startup script.\n"
  452. "Please advise GRASS developers of this error."))
  453. def load_gisrc():
  454. global gisdbase, location_name, mapset, location
  455. kv = read_gisrc()
  456. gisdbase = kv.get('GISDBASE')
  457. location_name = kv.get('LOCATION_NAME')
  458. mapset = kv.get('MAPSET')
  459. if not gisdbase or not location_name or not mapset:
  460. fatal(_("Error reading data path information from g.gisenv.\n"
  461. "GISDBASE=%(gisbase)s\n"
  462. "LOCATION_NAME=%(location)s\n"
  463. "MAPSET=%(mapset)s\n\n"
  464. "Check the <%s(file)> file." % \
  465. { 'gisbase' : gisdbase, 'location' : location_name,
  466. 'mapset' : mapset, 'file' : gisrcrc }))
  467. location = os.path.join(gisdbase, location_name, mapset)
  468. def check_lock():
  469. global lockfile
  470. # Check for concurrent use
  471. lockfile = os.path.join(location, ".gislock")
  472. ret = call([gfile("etc", "lock"),
  473. lockfile,
  474. "%d" % os.getpid()])
  475. if ret == 0:
  476. msg = None
  477. elif ret == 2:
  478. msg = _("%(user)s is currently running GRASS in selected mapset (file %(file)s found). "
  479. "Concurrent use not allowed." % \
  480. { 'user' : user, 'file' : lockfile })
  481. else:
  482. msg = _("Unable to properly access \"%s\"\nPlease notify system personel.") % lockfile
  483. if msg:
  484. if grass_gui == "wxpython":
  485. thetest = call([os.getenv('GRASS_PYTHON'), os.path.join(wxpython_base, "gis_set_error.py"), msg])
  486. else:
  487. fatal(msg)
  488. def make_fontcap():
  489. fc = os.getenv('GRASS_FONT_CAP')
  490. if fc and not os.access(fc, os.R_OK):
  491. message(_("Building user fontcap..."))
  492. call(["g.mkfontcap"])
  493. def check_shell():
  494. global sh, shellname
  495. # cygwin has many problems with the shell setup
  496. # below, so i hardcoded everything here.
  497. if os.getenv('CYGWIN'):
  498. sh = "cygwin"
  499. shellname = "GNU Bash (Cygwin)"
  500. os.environ['SHELL'] = "/usr/bin/bash.exe"
  501. os.environ['OSTYPE'] = "cygwin"
  502. else:
  503. sh = os.path.basename(os.getenv('SHELL'))
  504. if sh == "ksh":
  505. shellname = "Korn Shell"
  506. elif sh == "csh":
  507. shellname = "C Shell"
  508. elif sh == "tcsh":
  509. shellname = "TC Shell"
  510. elif sh == "bash":
  511. shellname = "Bash Shell"
  512. elif sh == "sh":
  513. shellname = "Bourne Shell"
  514. else:
  515. shellname = "shell"
  516. # check for SHELL
  517. if not os.getenv('SHELL'):
  518. fatal(_("The SHELL variable is not set"))
  519. def check_batch_job():
  520. global batch_job
  521. # hack to process batch jobs:
  522. batch_job = os.getenv('GRASS_BATCH_JOB')
  523. if batch_job:
  524. # defined, but ...
  525. if not os.access(batch_job, os.F_OK):
  526. # wrong file
  527. fatal(_("Job file '%s' has been defined in "
  528. "the 'GRASS_BATCH_JOB' variable but not found. Exiting.\n\n"
  529. "Use 'unset GRASS_BATCH_JOB' to disable batch job processing.") % batch_job)
  530. elif not os.access(batch_job, os.X_OK):
  531. # right file, but ...
  532. fatal(_("Change file permission to 'executable' for '%s'") % batch_job)
  533. else:
  534. message(_("Executing '%s' ...") % batch_job)
  535. grass_gui = "text"
  536. shell = batch_job
  537. bj = Popen(shell,shell=True)
  538. bj.wait()
  539. message(_("Execution of '%s' finished.") % batch_job)
  540. def start_gui():
  541. # Start the chosen GUI but ignore text
  542. if grass_debug:
  543. message(_("GRASS GUI should be '%s'") % grass_gui)
  544. # Check for gui interface
  545. if grass_gui == "wxpython":
  546. Popen([os.getenv('GRASS_PYTHON'),
  547. gfile(wxpython_base, "wxgui.py")])
  548. def clear_screen():
  549. if windows:
  550. pass
  551. # TODO: uncomment when PDCurses works.
  552. # cls
  553. else:
  554. if not os.getenv('GRASS_BATCH_JOB') and not grass_debug:
  555. call(["tput", "clear"])
  556. def show_banner():
  557. sys.stderr.write(r"""
  558. __________ ___ __________ _______________
  559. / ____/ __ \/ | / ___/ ___/ / ____/ _/ ___/
  560. / / __/ /_/ / /| | \__ \\_ \ / / __ / / \__ \
  561. / /_/ / _, _/ ___ |___/ /__/ / / /_/ // / ___/ /
  562. \____/_/ |_/_/ |_/____/____/ \____/___//____/
  563. """)
  564. def say_hello():
  565. if locale:
  566. path = gfile("locale", locale, "etc", "welcome")
  567. if not os.access(path, os.R_OK):
  568. path = gfile("etc", "welcome")
  569. else:
  570. path = gfile("etc", "welcome")
  571. s = readfile(path)
  572. sys.stderr.write(s)
  573. def show_info():
  574. sys.stderr.write(
  575. r"""
  576. %-41shttp://grass.osgeo.org
  577. %-41s%s (%s)
  578. %-41sg.manual -i
  579. %-41sg.version -c
  580. """ % (_("GRASS homepage:"),
  581. _("This version running through:"),
  582. shellname, os.getenv('SHELL'),
  583. _("Help is available with the command:"),
  584. _("See the licence terms with:")))
  585. if grass_gui == 'wxpython':
  586. message("%-41sg.gui wxpython" % _("If required, restart the GUI with:"))
  587. else:
  588. message("%-41sg.gui %s" % (_("Start the GUI with:"), default_gui))
  589. message("%-41sexit" % _("When ready to quit enter:"))
  590. message("")
  591. def csh_startup():
  592. global exit_val
  593. userhome = os.getenv('HOME') # save original home
  594. home = location
  595. os.environ['HOME'] = home
  596. cshrc = os.path.join(home, ".cshrc")
  597. tcshrc = os.path.join(home, ".tcshrc")
  598. try_remove(cshrc)
  599. try_remove(tcshrc)
  600. f = open(cshrc, 'w')
  601. f.write("set home = %s" % userhome)
  602. f.write("set history = 3000 savehist = 3000 noclobber ignoreeof")
  603. f.write("set histfile = %s" % os.path.join(os.getenv('HOME'), ".history"))
  604. f.write("set prompt = '\\")
  605. f.write("Mapset <%s> in Location <%s> \\" % (mapset, location_name))
  606. f.write("GRASS %s > '" % grass_version)
  607. f.write("set BOGUS=``;unset BOGUS")
  608. path = os.path.join(userhome, ".grass.cshrc")
  609. if os.access(path, os.R_OK):
  610. f.write(readfile(path))
  611. mail_re = re.compile(r"^ *set *mail *= *")
  612. for filename in [".cshrc", ".tcshrc", ".login"]:
  613. path = os.path.join(userhome, filename)
  614. if os.access(path, os.R_OK):
  615. s = readfile(path)
  616. lines = s.splitlines()
  617. for l in lines:
  618. if mail_re.match(l):
  619. f.write(l)
  620. path = os.getenv('PATH').split(':')
  621. f.write("set path = ( %s ) " % ' '.join(path))
  622. f.close()
  623. writefile(tcshrc, readfile(cshrc))
  624. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  625. os.environ['HOME'] = userhome
  626. def bash_startup():
  627. global exit_val
  628. # save command history in mapset dir and remember more
  629. os.environ['HISTFILE'] = os.path.join(location, ".bash_history")
  630. if not os.getenv('HISTSIZE') and not os.getenv('HISTFILESIZE'):
  631. os.environ['HISTSIZE'] = "3000"
  632. # instead of changing $HOME, start bash with: --rcfile "$LOCATION/.bashrc" ?
  633. # if so, must care be taken to explicity call .grass.bashrc et al for
  634. # non-interactive bash batch jobs?
  635. userhome = os.getenv('HOME') # save original home
  636. home = location # save .bashrc in $LOCATION
  637. os.environ['HOME'] = home
  638. bashrc = os.path.join(home, ".bashrc")
  639. try_remove(bashrc)
  640. f = open(bashrc, 'w')
  641. f.write("test -r ~/.alias && . ~/.alias\n")
  642. f.write("PS1='GRASS %s (%s):\w > '\n" % (grass_version, location_name))
  643. path = os.path.join(userhome, ".grass.bashrc")
  644. if os.access(path, os.R_OK):
  645. f.write(readfile(path) + '\n')
  646. f.write("export PATH=\"%s\"\n" % os.getenv('PATH'))
  647. f.write("export HOME=\"%s\"\n" % userhome) # restore user home path
  648. for env, value in os.environ.iteritems():
  649. if env.find('GRASS_') < 0:
  650. continue
  651. f.write("export %s=\"%s\"\n" % (env, value))
  652. f.close()
  653. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  654. os.environ['HOME'] = userhome
  655. def default_startup():
  656. global exit_val
  657. if windows:
  658. os.environ['PS1'] = "GRASS %s> " % (grass_version)
  659. # "$ETC/run" doesn't work at all???
  660. exit_val = subprocess.call([os.getenv('SHELL')])
  661. cleanup_dir(os.path.join(location, ".tmp")) # remove GUI session files from .tmp
  662. else:
  663. os.environ['PS1'] = "GRASS %s (%s):\w > " % (grass_version, location_name)
  664. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  665. if exit_val != 0:
  666. fatal(_("Failed to start shell '%s'") % os.getenv('SHELL'))
  667. def done_message():
  668. if batch_job and os.access(batch_job, os.X_OK):
  669. message(_("Batch job '%s' (defined in GRASS_BATCH_JOB variable) was executed.") % batch_job)
  670. message(_("Goodbye from GRASS GIS"))
  671. sys.exit(exit_val)
  672. else:
  673. message(_("Done."))
  674. message("")
  675. message(_("Goodbye from GRASS GIS"))
  676. message("")
  677. def clean_temp():
  678. message(_("Cleaning up temporary files..."))
  679. nul = open(os.devnull, 'w')
  680. call([gfile("etc", "clean_temp")], stdout = nul, stderr = nul)
  681. nul.close()
  682. def get_username():
  683. global user
  684. if windows:
  685. user = os.getenv('USERNAME')
  686. if not user:
  687. user = "user_name"
  688. else:
  689. user = os.getenv('USER')
  690. if not user:
  691. user = os.getenv('LOGNAME')
  692. if not user:
  693. try:
  694. p = Popen(['whoami'], stdout = subprocess.PIPE)
  695. s = p.stdout.read()
  696. p.wait()
  697. user = s.strip()
  698. except:
  699. pass
  700. if not user:
  701. user = "user_%d" % os.getuid()
  702. def parse_cmdline():
  703. global args, grass_gui, create_new
  704. args = []
  705. for i in sys.argv[1:]:
  706. # Check if the user asked for the version
  707. if i in ["-v","--version"]:
  708. message(readfile(gfile("etc", "license")))
  709. sys.exit()
  710. # Check if the user asked for help
  711. elif i in ["help","-h","-help","--help"]:
  712. help_message()
  713. sys.exit()
  714. # Check if the -text flag was given
  715. elif i == "-text":
  716. grass_gui = 'text'
  717. # Check if the -gui flag was given
  718. elif i == "-gui":
  719. grass_gui = default_gui
  720. # Check if the -wxpython flag was given
  721. elif i in ["-wxpython","-wx"]:
  722. grass_gui = 'wxpython'
  723. # Check if the user wants to create a new mapset
  724. elif i == "-c":
  725. create_new = True
  726. else:
  727. args.append(i)
  728. ### MAIN script starts here
  729. # Get the system name
  730. windows = sys.platform == 'win32'
  731. cygwin = "cygwin" in sys.platform
  732. macosx = "darwin" in sys.platform
  733. # Set GISBASE
  734. os.environ['GISBASE'] = gisbase
  735. # set HOME
  736. if windows and not os.getenv('HOME'):
  737. os.environ['HOME'] = os.path.join(os.getenv('HOMEDRIVE'), os.getenv('HOMEPATH'))
  738. # set SHELL
  739. if windows:
  740. if os.getenv('GRASS_SH'):
  741. os.environ['SHELL'] = os.getenv('GRASS_SH')
  742. if not os.getenv('SHELL'):
  743. os.environ['SHELL'] = os.getenv('COMSPEC', 'cmd.exe')
  744. grass_config_dir = os.path.join(os.getenv('HOME'), grass_config_dirname)
  745. atexit.register(cleanup)
  746. # Set default GUI
  747. default_gui = "wxpython"
  748. # the following is only meant to be an internal variable for debugging this script.
  749. # use 'g.gisenv set="DEBUG=[0-5]"' to turn GRASS debug mode on properly.
  750. grass_debug = os.getenv('GRASS_DEBUG')
  751. # Set GRASS version number for R interface etc (must be an env_var for MS-Windows)
  752. os.environ['GRASS_VERSION'] = grass_version
  753. # Set the GIS_LOCK variable to current process id
  754. gis_lock = str(os.getpid())
  755. os.environ['GIS_LOCK'] = gis_lock
  756. # Set the global grassrc file
  757. batch_job = os.getenv('GRASS_BATCH_JOB')
  758. if batch_job:
  759. gisrcrc = os.path.join(grass_config_dir, "rc.%s" % os.uname()[1])
  760. if not os.access(gisrcrc, os.R_OK):
  761. gisrcrc = os.path.join(grass_config_dir, "rc")
  762. else:
  763. gisrcrc = os.path.join(grass_config_dir, "rc")
  764. # Set the username and working directory
  765. get_username()
  766. # Parse the command-line options
  767. parse_cmdline()
  768. # Create the temporary directory and session grassrc file
  769. create_tmp()
  770. # Create the session grassrc file
  771. create_gisrc()
  772. # Ensure GRASS_GUI is set
  773. read_gui()
  774. # Get Locale name
  775. get_locale()
  776. # Set PATH, PYTHONPATH
  777. set_paths()
  778. # Set LD_LIBRARY_PATH (etc) to find GRASS shared libraries
  779. path_prepend(gfile("lib"), ld_library_path_var)
  780. # Set GRASS_PAGER, GRASS_WISH, GRASS_PYTHON, GRASS_GNUPLOT, GRASS_PROJSHARE
  781. set_defaults()
  782. # Set GRASS_HTML_BROWSER
  783. set_browser()
  784. #predefine monitor size for certain architectures
  785. if os.getenv('HOSTTYPE') == 'arm':
  786. #small monitor on ARM (iPAQ, zaurus... etc)
  787. os.environ['GRASS_HEIGHT'] = "320"
  788. os.environ['GRASS_WIDTH'] = "240"
  789. # First time user - GISRC is defined in the GRASS script
  790. if not os.access(gisrc, os.F_OK):
  791. grass_intro()
  792. else:
  793. clean_temp()
  794. message(_("Starting GRASS GIS..."))
  795. # Check that the GUI works
  796. check_gui()
  797. # Parsing argument to get LOCATION
  798. if args == []:
  799. # Try interactive startup
  800. location = None
  801. else:
  802. non_interactive(args[0])
  803. # User selects LOCATION and MAPSET if not set
  804. set_data()
  805. # Set GISDBASE, LOCATION_NAME, MAPSET, LOCATION from $GISRC
  806. load_gisrc()
  807. # Check .gislock file
  808. check_lock()
  809. # build user fontcap if specified but not present
  810. make_fontcap()
  811. # predefine default driver if DB connection not defined
  812. # is this really needed?? Modules should call this when/if required.
  813. if not os.access(os.path.join(location, "VAR"), os.F_OK):
  814. call(['db.connect', '-c', '--quiet'])
  815. check_shell()
  816. check_batch_job()
  817. if not batch_job:
  818. start_gui()
  819. clear_screen()
  820. # Display the version and license info
  821. if batch_job:
  822. say_hello()
  823. grass_gui = 'text'
  824. clear_screen()
  825. clean_temp()
  826. try_remove(lockfile)
  827. sys.exit(0)
  828. else:
  829. show_banner()
  830. say_hello()
  831. show_info()
  832. if sh in ['csh', 'tcsh']:
  833. csh_startup()
  834. elif sh in ['bash', 'msh', 'cygwin']:
  835. bash_startup()
  836. else:
  837. default_startup()
  838. clear_screen()
  839. clean_temp()
  840. try_remove(lockfile)
  841. # Save GISRC
  842. s = readfile(gisrc)
  843. if not os.path.exists(grass_config_dir):
  844. os.mkdir(grass_config_dir)
  845. writefile(gisrcrc, s)
  846. cleanup()
  847. #### after this point no more grass modules may be called ####
  848. done_message()