grass.py 28 KB

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