grass.py 28 KB

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