grass.py 38 KB

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