grass.py 25 KB

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