grass.py 40 KB

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