grass.py 39 KB

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