grass.py 40 KB

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