grass.py 28 KB

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