grass.py 31 KB

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