grass.py 28 KB

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