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. grass_env_file = None # see check_shell()
  47. if sys.platform == 'win32':
  48. grass_config_dirname = "GRASS7"
  49. grass_config_dir = os.path.join(os.getenv('APPDATA'), grass_config_dirname)
  50. else:
  51. grass_config_dirname = ".grass7"
  52. grass_config_dir = os.path.join(os.getenv('HOME'), grass_config_dirname)
  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 tmp dirs (system/location) should
  93. # also tidy it up
  94. cleanup_dir(tmpdir)
  95. try_rmdir(tmpdir)
  96. if location:
  97. tmpdir_loc = os.path.join(location, ".tmp")
  98. cleanup_dir(tmpdir_loc)
  99. try_rmdir(tmpdir_loc)
  100. # remove lock-file if requested
  101. if lockfile and remove_lockfile:
  102. try_remove(lockfile)
  103. def fatal(msg):
  104. sys.exit(msg)
  105. def message(msg):
  106. sys.stderr.write(msg + "\n")
  107. sys.stderr.flush()
  108. def readfile(path):
  109. f = open(path, 'r')
  110. s = f.read()
  111. f.close()
  112. return s
  113. def writefile(path, s):
  114. f = open(path, 'w')
  115. f.write(s)
  116. f.close()
  117. def call(cmd, **kwargs):
  118. if windows:
  119. kwargs['shell'] = True
  120. return subprocess.call(cmd, **kwargs)
  121. def Popen(cmd, **kwargs):
  122. if windows:
  123. kwargs['shell'] = True
  124. return subprocess.Popen(cmd, **kwargs)
  125. def gfile(*args):
  126. return os.path.join(gisbase, *args)
  127. help_text = r"""GRASS GIS %s
  128. Geographic Resources Analysis Support System (GRASS GIS).
  129. %s:
  130. $CMD_NAME [-h | -help | --help] [-v | --version] [-c | -c geofile | -c EPSG:code]
  131. [-text | -gui] [--config param]
  132. [[[<GISDBASE>/]<LOCATION_NAME>/]<MAPSET>]
  133. %s:
  134. -h or -help or --help %s
  135. -v or --version %s
  136. -c %s
  137. -text %s
  138. %s
  139. -gui %s
  140. %s
  141. --config %s
  142. %s
  143. %s:
  144. GISDBASE %s
  145. LOCATION_NAME %s
  146. MAPSET %s
  147. GISDBASE/LOCATION_NAME/MAPSET %s
  148. %s:
  149. GRASS_GUI %s
  150. GRASS_HTML_BROWSER %s
  151. GRASS_ADDON_PATH %s
  152. GRASS_ADDON_BASE %s
  153. GRASS_BATCH_JOB %s
  154. GRASS_PYTHON %s
  155. """ % (grass_version,
  156. _("Usage"),
  157. _("Flags"),
  158. _("print this help message"),
  159. _("show version information and exit"),
  160. _("create given database, location or mapset if it doesn't exist"),
  161. _("use text based interface"),
  162. _("and set as default"),
  163. _("use $DEFAULT_GUI graphical user interface"),
  164. _("and set as default"),
  165. _("print GRASS configuration parameters"),
  166. _("options: arch,build,compiler,path,revision"),
  167. _("Parameters"),
  168. _("initial database (path to GIS data)"),
  169. _("initial location"),
  170. _("initial mapset"),
  171. _("fully qualified initial mapset directory"),
  172. _("Environment variables relevant for startup"),
  173. _("select GUI (text, gui)"),
  174. _("set html web browser for help pages"),
  175. _("set additional path(s) to local GRASS modules or user scripts"),
  176. _("set additional GISBASE for locally installed GRASS Addons"),
  177. _("shell script to be processed as batch job"),
  178. _("set python shell name to override 'python'"))
  179. def help_message():
  180. t = string.Template(help_text)
  181. s = t.substitute(CMD_NAME = cmd_name, DEFAULT_GUI = default_gui)
  182. sys.stderr.write(s)
  183. def create_tmp():
  184. global tmpdir
  185. ## use $TMPDIR if it exists, then $TEMP, otherwise /tmp
  186. tmp = os.getenv('TMPDIR')
  187. if not tmp:
  188. tmp = os.getenv('TEMP')
  189. if not tmp:
  190. tmp = tempfile.gettempdir()
  191. if not tmp:
  192. tmp = '/tmp'
  193. tmpdir = os.path.join(tmp, "grass7-%s-%s" % (user, gis_lock))
  194. try:
  195. os.mkdir(tmpdir, 0700)
  196. except:
  197. fatal(_("Unable to create temporary directory <%s>! Exiting.") % tmpdir)
  198. def create_gisrc():
  199. global gisrc, gisrcrc
  200. # Set the session grassrc file
  201. gisrc = os.path.join(tmpdir, "gisrc")
  202. os.environ['GISRC'] = gisrc
  203. # remove invalid GISRC file to avoid disturbing error messages:
  204. try:
  205. s = readfile(gisrcrc)
  206. if "UNKNOWN" in s:
  207. try_remove(gisrcrc)
  208. s = None
  209. except:
  210. s = None
  211. # Copy the global grassrc file to the session grassrc file
  212. if s:
  213. writefile(gisrc, s)
  214. def read_gisrc():
  215. kv = {}
  216. try:
  217. f = open(gisrc, 'r')
  218. except IOError:
  219. return kv
  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 read_env_file(path):
  226. kv = {}
  227. f = open(path, 'r')
  228. for line in f:
  229. k, v = line.split(':', 1)
  230. kv[k.strip()] = v.strip()
  231. f.close()
  232. return kv
  233. def write_gisrc(kv):
  234. f = open(gisrc, 'w')
  235. for k, v in kv.iteritems():
  236. f.write("%s: %s\n" % (k, v))
  237. f.close()
  238. def read_gui():
  239. global grass_gui
  240. # At this point the GRASS user interface variable has been set from the
  241. # command line, been set from an external environment variable, or is
  242. # not set. So we check if it is not set
  243. if not grass_gui:
  244. # Check for a reference to the GRASS user interface in the grassrc file
  245. if os.access(gisrc, os.R_OK):
  246. kv = read_gisrc()
  247. if 'GRASS_GUI' in os.environ:
  248. grass_gui = os.environ['GRASS_GUI']
  249. elif 'GUI' in kv:
  250. grass_gui = kv['GUI']
  251. elif 'GRASS_GUI' in kv:
  252. # For backward compatibility (GRASS_GUI renamed to GUI)
  253. grass_gui = kv['GRASS_GUI']
  254. else:
  255. # Set the GRASS user interface to the default if needed
  256. grass_gui = default_gui
  257. if not grass_gui:
  258. grass_gui = default_gui
  259. if grass_gui == 'gui':
  260. grass_gui = default_gui
  261. # FIXME oldtcltk, gis.m, d.m no longer exist
  262. if grass_gui in ['d.m', 'gis.m', 'oldtcltk', 'tcltk']:
  263. warning(_("GUI <%s> not supported in this version") % grass_gui)
  264. grass_gui = default_gui
  265. def path_prepend(dir, var):
  266. path = os.getenv(var)
  267. if path:
  268. path = dir + os.pathsep + path
  269. else:
  270. path = dir
  271. os.environ[var] = path
  272. def path_append(dir, var):
  273. path = os.getenv(var)
  274. if path:
  275. path = path + os.pathsep + dir
  276. else:
  277. path = dir
  278. os.environ[var] = path
  279. def set_paths():
  280. # addons (path)
  281. addon_path = os.getenv('GRASS_ADDON_PATH')
  282. if addon_path:
  283. for path in addon_path.split(os.pathsep):
  284. path_prepend(addon_path, 'PATH')
  285. # addons (base)
  286. addon_base = os.getenv('GRASS_ADDON_BASE')
  287. if not addon_base:
  288. addon_base = os.path.join(grass_config_dir, 'addons')
  289. os.environ['GRASS_ADDON_BASE'] = addon_base
  290. path_prepend(os.path.join(addon_base, 'scripts'), 'PATH')
  291. path_prepend(os.path.join(addon_base, 'bin'), 'PATH')
  292. # standard installation
  293. path_prepend(gfile('scripts'), 'PATH')
  294. path_prepend(gfile('bin'), 'PATH')
  295. # Set PYTHONPATH to find GRASS Python modules
  296. path_prepend(gfile('etc', 'python'), 'PYTHONPATH')
  297. # set path for the GRASS man pages
  298. grass_man_path = os.path.join(gisbase, 'docs', 'man')
  299. addons_man_path = os.path.join(addon_base, 'docs', 'man')
  300. man_path = os.getenv('MANPATH')
  301. if man_path:
  302. path_prepend(addons_man_path, 'MANPATH')
  303. path_prepend(grass_man_path, 'MANPATH')
  304. else:
  305. try:
  306. nul = open(os.devnull, 'w')
  307. p = Popen(['manpath'], stdout = subprocess.PIPE, stderr = nul)
  308. nul.close()
  309. s = p.stdout.read()
  310. p.wait()
  311. sys_man_path = s.strip()
  312. except:
  313. pass
  314. if sys_man_path:
  315. os.environ['MANPATH'] = sys_man_path
  316. path_prepend(addons_man_path, 'MANPATH')
  317. path_prepend(grass_man_path, 'MANPATH')
  318. else:
  319. os.environ['MANPATH'] = addons_man_path
  320. path_prepend(grass_man_path, 'MANPATH')
  321. # Add .py (Python) to list of executable extensions to search for
  322. # in MS-Windows PATH
  323. if windows:
  324. path_append('.PY', 'PATHEXT')
  325. def find_exe(pgm):
  326. for dir in os.getenv('PATH').split(os.pathsep):
  327. path = os.path.join(dir, pgm)
  328. if os.access(path, os.X_OK):
  329. return path
  330. return None
  331. def set_defaults():
  332. # GRASS_PAGER
  333. if not os.getenv('GRASS_PAGER'):
  334. if find_exe("more"):
  335. pager = "more"
  336. elif find_exe("less"):
  337. pager = "less"
  338. elif windows:
  339. pager = "more"
  340. else:
  341. pager = "cat"
  342. os.environ['GRASS_PAGER'] = pager
  343. # GRASS_PYTHON
  344. if not os.getenv('GRASS_PYTHON'):
  345. if windows:
  346. os.environ['GRASS_PYTHON'] = "python.exe"
  347. else:
  348. os.environ['GRASS_PYTHON'] = "python"
  349. # GRASS_GNUPLOT
  350. if not os.getenv('GRASS_GNUPLOT'):
  351. os.environ['GRASS_GNUPLOT'] = "gnuplot -persist"
  352. # GRASS_PROJSHARE
  353. if not os.getenv('GRASS_PROJSHARE'):
  354. os.environ['GRASS_PROJSHARE'] = config_projshare
  355. def set_browser():
  356. # GRASS_HTML_BROWSER
  357. browser = os.getenv('GRASS_HTML_BROWSER')
  358. if not browser:
  359. if macosx:
  360. # OSX doesn't execute browsers from the shell PATH - route thru a script
  361. browser = gfile('etc', "html_browser_mac.sh")
  362. os.environ['GRASS_HTML_BROWSER_MACOSX'] = "-b com.apple.helpviewer"
  363. if windows or cygwin:
  364. # MinGW startup moved to into init.bat
  365. browser = "explorer"
  366. else:
  367. # the usual suspects
  368. browsers = [ "xdg-open", "htmlview", "konqueror", "mozilla", "mozilla-firefox",
  369. "firefox", "iceweasel", "opera", "netscape", "dillo", "lynx", "links", "w3c" ]
  370. for b in browsers:
  371. if find_exe(b):
  372. browser = b
  373. break
  374. elif macosx:
  375. # OSX doesn't execute browsers from the shell PATH - route thru a script
  376. os.environ['GRASS_HTML_BROWSER_MACOSX'] = "-b %s" % browser
  377. browser = gfile('etc', "html_browser_mac.sh")
  378. if not browser:
  379. warning(_("Searched for a web browser, but none found"))
  380. # even so we set konqueror to make lib/gis/parser.c happy:
  381. browser = "konqueror"
  382. os.environ['GRASS_HTML_BROWSER'] = browser
  383. def grass_intro():
  384. intro = r"""
  385. WELCOME TO GRASS %s
  386. 1) Have at your side all available GRASS tutorials
  387. 2) When working on your location, the following materials
  388. are extremely useful:
  389. - A topo map of your area
  390. - Current catalog of available computer maps
  391. 3) Check the GRASS webpages for feedback mailinglists and more:
  392. http://grass.osgeo.org
  393. http://www.grass-gis.org
  394. """ % grass_version
  395. sys.stderr.write(intro)
  396. sys.stderr.write("\n")
  397. sys.stderr.write(_("Hit RETURN to continue"))
  398. sys.stdin.readline()
  399. # for convenience, define pwd as GISDBASE:
  400. s = r"""GISDBASE: %s
  401. LOCATION_NAME: <UNKNOWN>
  402. MAPSET: <UNKNOWN>
  403. """ % os.getcwd()
  404. writefile(gisrc, s)
  405. def check_gui():
  406. global grass_gui, wxpython_base
  407. # Check if we are running X windows by checking the DISPLAY variable
  408. if os.getenv('DISPLAY') or windows:
  409. # Check if python is working properly
  410. if grass_gui == 'wxpython':
  411. nul = open(os.devnull, 'w')
  412. p = Popen([os.environ['GRASS_PYTHON']],
  413. stdin = subprocess.PIPE,
  414. stdout = nul, stderr = nul)
  415. nul.close()
  416. p.stdin.write("variable=True")
  417. p.stdin.close()
  418. p.wait()
  419. if p.returncode == 0:
  420. # Set the wxpython base directory
  421. wxpython_base = gfile("etc", "gui", "wxpython")
  422. else:
  423. # Python was not found - switch to text interface mode
  424. warning(_("The python command does not work as expected!\n"
  425. "Please check your GRASS_PYTHON environment variable.\n"
  426. "Use the -help option for details.\n"
  427. "Switching to text based interface mode.\n\n"
  428. "Hit RETURN to continue.\n"))
  429. sys.stdin.readline()
  430. grass_gui = 'text'
  431. else:
  432. # Display a message if a graphical interface was expected
  433. if grass_gui != 'text':
  434. # Set the interface mode to text
  435. warning(_("It appears that the X Windows system is not active.\n"
  436. "A graphical based user interface is not supported.\n"
  437. "Switching to text based interface mode.\n\n"
  438. "Hit RETURN to continue"""))
  439. sys.stdin.readline()
  440. grass_gui = 'text'
  441. # Save the user interface variable in the grassrc file - choose a temporary
  442. # file name that should not match another file
  443. if os.access(gisrc, os.F_OK):
  444. kv = read_gisrc()
  445. kv['GUI'] = grass_gui
  446. write_gisrc(kv)
  447. def non_interactive(arg, geofile = None):
  448. global gisdbase, location_name, mapset, location
  449. # Try non-interactive startup
  450. l = None
  451. if arg == '-':
  452. if location:
  453. l = location
  454. else:
  455. l = arg
  456. if l:
  457. if l == '.':
  458. l = os.getcwd()
  459. elif not os.path.isabs(l):
  460. l = os.path.abspath(l)
  461. l, mapset = os.path.split(l)
  462. if not mapset:
  463. l, mapset = os.path.split(l)
  464. l, location_name = os.path.split(l)
  465. gisdbase = l
  466. if gisdbase and location_name and mapset:
  467. location = os.path.join(gisdbase, location_name, mapset)
  468. if not os.access(os.path.join(location, "WIND"), os.R_OK):
  469. if location_name == "PERMANENT":
  470. fatal(_("<%s> is not a valid GRASS location") % location)
  471. else:
  472. # the user wants to create mapset on the fly
  473. if create_new:
  474. if not os.access(os.path.join(os.path.join(gisdbase, location_name,
  475. "PERMANENT", "DEFAULT_WIND")), os.F_OK):
  476. # create new location
  477. gisdbase = os.path.join(gisdbase, location_name)
  478. location_name = mapset
  479. mapset = "PERMANENT"
  480. if os.access(os.path.join(os.path.join(gisdbase, location_name,
  481. "PERMANENT", "DEFAULT_WIND")), os.F_OK):
  482. fatal(_("Failed to create new location. The location <%s> already exists." % location_name))
  483. sys.path.append(gfile('etc', 'python'))
  484. from grass.script import core as grass
  485. try:
  486. if geofile and geofile.find('EPSG:') > -1:
  487. epsg = geofile.split(':', 1)[1]
  488. grass.create_location(gisdbase, location_name, epsg = epsg)
  489. else:
  490. grass.create_location(gisdbase, location_name, filename = geofile)
  491. except grass.ScriptError, e:
  492. fatal(e.value.strip('"').strip("'").replace('\\n', os.linesep))
  493. else:
  494. # create new mapset
  495. os.mkdir(location)
  496. # copy PERMANENT/DEFAULT_WIND to <mapset>/WIND
  497. s = readfile(os.path.join(gisdbase, location_name, "PERMANENT", "DEFAULT_WIND"))
  498. writefile(os.path.join(location, "WIND"), s)
  499. message(_("Missing WIND file fixed"))
  500. else:
  501. fatal(_("<%s> is not a valid GRASS location") % location)
  502. if os.access(gisrc, os.R_OK):
  503. kv = read_gisrc()
  504. else:
  505. kv = {}
  506. kv['GISDBASE'] = gisdbase
  507. kv['LOCATION_NAME'] = location_name
  508. kv['MAPSET'] = mapset
  509. write_gisrc(kv)
  510. else:
  511. fatal(_("GISDBASE, LOCATION_NAME and MAPSET variables not set properly.\n"
  512. "Interactive startup needed."))
  513. def set_data():
  514. # User selects LOCATION and MAPSET if not set
  515. if not location:
  516. # Check for text interface
  517. if grass_gui == 'text':
  518. pass
  519. # Check for GUI
  520. elif grass_gui == 'wxpython':
  521. gui_startup()
  522. else:
  523. # Shouldn't need this but you never know
  524. fatal(_("Invalid user interface specified - <%s>.\n"
  525. "Use the --help option to see valid interface names.") % grass_gui)
  526. def gui_startup():
  527. if grass_gui == 'wxpython':
  528. thetest = call([os.getenv('GRASS_PYTHON'),
  529. gfile(wxpython_base, "gis_set.py")])
  530. if thetest == 0:
  531. pass
  532. elif thetest == 1:
  533. # The startup script printed an error message so wait
  534. # for user to read it
  535. message(_("Error in GUI startup. If necessary, please "
  536. "report this error to the GRASS developers.\n"
  537. "Switching to text mode now.\n\n"
  538. "Hit RETURN to continue..."))
  539. sys.stdin.readline()
  540. os.execlp(cmd_name, "-text")
  541. sys.exit(1)
  542. elif thetest == 2:
  543. # User wants to exit from GRASS
  544. message(_("Received EXIT message from GUI.\nGRASS is not started. Bye."))
  545. sys.exit(0)
  546. else:
  547. fatal(_("Invalid return code from GUI startup script.\n"
  548. "Please advise GRASS developers of this error."))
  549. def load_gisrc():
  550. global gisdbase, location_name, mapset, location
  551. kv = read_gisrc()
  552. gisdbase = kv.get('GISDBASE')
  553. location_name = kv.get('LOCATION_NAME')
  554. mapset = kv.get('MAPSET')
  555. if not gisdbase or not location_name or not mapset:
  556. fatal(_("Error reading data path information from g.gisenv.\n"
  557. "GISDBASE=%(gisbase)s\n"
  558. "LOCATION_NAME=%(location)s\n"
  559. "MAPSET=%(mapset)s\n\n"
  560. "Check the <%s(file)> file." % \
  561. { 'gisbase' : gisdbase, 'location' : location_name,
  562. 'mapset' : mapset, 'file' : gisrcrc }))
  563. location = os.path.join(gisdbase, location_name, mapset)
  564. # load environmental variables from grass_env_file
  565. def load_env():
  566. if not os.access(grass_env_file, os.R_OK):
  567. return
  568. for line in readfile(grass_env_file).split(os.linesep):
  569. try:
  570. k, v = map(lambda x: x.strip(), line.strip().split(' ', 1)[1].split('=', 1))
  571. except:
  572. continue
  573. os.environ[k] = v
  574. def set_language():
  575. import locale
  576. language = os.getenv('LANG')
  577. if not language:
  578. return
  579. language = language.split('.')[0] # Split off ignored .encoding part if present
  580. orig_language = language
  581. try:
  582. locale.setlocale(locale.LC_ALL, language)
  583. except locale.Error, e:
  584. if sys.platform != 'win32': # Don't try on Windows, it will probably not work
  585. # sys.stderr.write("Failed to set LC_ALL to %s (%s)\n" % (language, e))
  586. try:
  587. # Locale lang.encoding might be missing. Let's try
  588. # UTF-8 encoding before giving up as on Linux systems
  589. # lang.UTF-8 locales are more common than legacy
  590. # ISO-8859 ones.
  591. language = locale.normalize('%s.UTF-8' % (language))
  592. locale.setlocale(locale.LC_ALL, language)
  593. except locale.Error, e:
  594. # If we got so far, provided locale is not supported
  595. # on this system
  596. sys.stderr.write("Failed to set LC_ALL to %s (%s)\n" % (language, e))
  597. ### locale.getdefaultlocale() is probably related to gettext?
  598. # try:
  599. # default_locale = locale.getdefaultlocale()
  600. # except:
  601. # default_locale = None
  602. # if default_locale and default_locale[0]:
  603. # language = default_locale[0]
  604. # else:
  605. language = 'C'
  606. # Set up environment for subprocesses
  607. for lc in ('LC_CTYPE', 'LC_MESSAGES', 'LC_TIME', 'LC_COLLATE', 'LC_MONETARY', 'LC_PAPER',
  608. 'LC_NAME', 'LC_ADDRESS', 'LC_TELEPHONE', 'LC_MEASUREMENT', 'LC_IDENTIFICATION'):
  609. os.environ[lc] = language
  610. # Some code in GRASS might not like other decimal separators than .
  611. # Other potential sources for problems are: LC_TIME LC_CTYPE
  612. locale.setlocale(locale.LC_NUMERIC, 'C')
  613. os.environ['LC_NUMERIC'] = 'C'
  614. if os.getenv('LC_ALL'):
  615. del os.environ['LC_ALL'] # Remove LC_ALL to not override LC_NUMERIC
  616. # Even if setting locale has failed, let's set LANG in a hope,
  617. # that UI will use it GRASS texts will be in selected language,
  618. # system messages (i.e. OK, Cancel etc.) - in system default
  619. # language
  620. os.environ['LANGUAGE'] = orig_language
  621. os.environ['LANG'] = orig_language
  622. # Calling gettext.install twice seems to allow to see also
  623. # localized startup messages Black magic ;)
  624. gettext.install('grasslibs', os.path.join(gisbase, 'locale'), unicode = True)
  625. def check_lock():
  626. global lockfile
  627. if not os.path.exists(location):
  628. fatal(_("Path '%s' doesn't exist") % location)
  629. # Check for concurrent use
  630. lockfile = os.path.join(location, ".gislock")
  631. ret = call([gfile("etc", "lock"),
  632. lockfile,
  633. "%d" % os.getpid()])
  634. if ret == 0:
  635. msg = None
  636. elif ret == 2:
  637. msg = _("%(user)s is currently running GRASS in selected mapset (file %(file)s found). "
  638. "Concurrent use not allowed." % \
  639. { 'user' : user, 'file' : lockfile })
  640. else:
  641. msg = _("Unable to properly access '%s'.\n"
  642. "Please notify system personel.") % lockfile
  643. if msg:
  644. if grass_gui == "wxpython":
  645. thetest = call([os.getenv('GRASS_PYTHON'), os.path.join(wxpython_base, "gis_set_error.py"), msg])
  646. else:
  647. global remove_lockfile
  648. remove_lockfile = False
  649. fatal(msg)
  650. def make_fontcap():
  651. fc = os.getenv('GRASS_FONT_CAP')
  652. if fc and not os.access(fc, os.R_OK):
  653. message(_("Building user fontcap..."))
  654. call(["g.mkfontcap"])
  655. def check_shell():
  656. global sh, shellname, grass_env_file
  657. # cygwin has many problems with the shell setup
  658. # below, so i hardcoded everything here.
  659. if os.getenv('CYGWIN'):
  660. sh = "cygwin"
  661. shellname = "GNU Bash (Cygwin)"
  662. os.environ['SHELL'] = "/usr/bin/bash.exe"
  663. os.environ['OSTYPE'] = "cygwin"
  664. else:
  665. sh = os.path.basename(os.getenv('SHELL'))
  666. if windows and sh:
  667. sh = os.path.splitext(sh)[0]
  668. if sh == "ksh":
  669. shellname = "Korn Shell"
  670. elif sh == "csh":
  671. shellname = "C Shell"
  672. elif sh == "tcsh":
  673. shellname = "TC Shell"
  674. elif sh == "bash":
  675. shellname = "Bash Shell"
  676. elif sh == "sh":
  677. shellname = "Bourne Shell"
  678. elif sh == "zsh":
  679. shellname = "Z Shell"
  680. elif sh == "cmd":
  681. shellname = "Command Shell"
  682. else:
  683. shellname = "shell"
  684. if sh in ['csh', 'tcsh']:
  685. grass_env_file = os.path.join(grass_config_dir, 'cshrc')
  686. elif sh in ['bash', 'msh', 'cygwin', 'sh']:
  687. grass_env_file = os.path.join(grass_config_dir, 'bashrc')
  688. elif sh == 'zsh':
  689. grass_env_file = os.path.join(grass_config_dir, 'zshrc')
  690. elif sh == 'cmd':
  691. grass_env_file = os.path.join(grass_config_dir, 'env.bat')
  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_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()