grass.py 40 KB

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