grass.py 39 KB

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