grass.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257
  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. 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. if sys.platform == 'win32':
  47. grass_config_dirname = "GRASS7"
  48. grass_config_dir = os.path.join(os.getenv('APPDATA'), grass_config_dirname)
  49. grass_env_file = os.path.join(grass_config_dir, 'env.bat')
  50. else:
  51. grass_config_dirname = ".grass7"
  52. grass_config_dir = os.path.join(os.getenv('HOME'), grass_config_dirname)
  53. grass_env_file = None # see check_shell()
  54. gisbase = os.path.normpath(gisbase)
  55. # i18N
  56. import gettext
  57. gettext.install('grasslibs', os.path.join(gisbase, 'locale'), unicode = True)
  58. tmpdir = None
  59. lockfile = None
  60. remove_lockfile = True
  61. location = None
  62. create_new = None
  63. grass_gui = None
  64. def warning(text):
  65. sys.stderr.write(_("WARNING") + ': ' + text + os.linesep)
  66. def try_remove(path):
  67. try:
  68. os.remove(path)
  69. except:
  70. pass
  71. def try_rmdir(path):
  72. try:
  73. os.rmdir(path)
  74. except:
  75. pass
  76. def clean_env():
  77. env_curr = read_gisrc()
  78. env_new = {}
  79. for k,v in env_curr.iteritems():
  80. if 'MONITOR' not in k:
  81. env_new[k] = v
  82. write_gisrc(env_new)
  83. def cleanup_dir(path):
  84. if not path:
  85. return
  86. for root, dirs, files in os.walk(path, topdown = False):
  87. for name in files:
  88. try_remove(os.path.join(root, name))
  89. for name in dirs:
  90. try_rmdir(os.path.join(root, name))
  91. def cleanup():
  92. tmpdir, lockfile, remove_lockfile
  93. # all exits after setting up tmp dirs (system/location) should
  94. # also tidy it up
  95. for tmpd in [tmpdir, os.path.join(location, ".tmp")]:
  96. cleanup_dir(tmpd)
  97. try_rmdir(tmpd)
  98. # remove lock-file if requested
  99. if lockfile and remove_lockfile:
  100. try_remove(lockfile)
  101. def fatal(msg):
  102. sys.exit(msg)
  103. def message(msg):
  104. sys.stderr.write(msg + "\n")
  105. sys.stderr.flush()
  106. def readfile(path):
  107. f = open(path, 'r')
  108. s = f.read()
  109. f.close()
  110. return s
  111. def writefile(path, s):
  112. f = open(path, 'w')
  113. f.write(s)
  114. f.close()
  115. def call(cmd, **kwargs):
  116. if windows:
  117. kwargs['shell'] = True
  118. return subprocess.call(cmd, **kwargs)
  119. def Popen(cmd, **kwargs):
  120. if windows:
  121. kwargs['shell'] = True
  122. return subprocess.Popen(cmd, **kwargs)
  123. def gfile(*args):
  124. return os.path.join(gisbase, *args)
  125. help_text = r"""
  126. %s:
  127. $CMD_NAME [-h | -help | --help] [-v | --version] [-c | -c geofile | -c EPSG:code]
  128. [-text | -gui] [--config param]
  129. [[[<GISDBASE>/]<LOCATION_NAME>/]<MAPSET>]
  130. %s:
  131. -h or -help or --help %s
  132. -v or --version %s
  133. -c %s
  134. -text %s
  135. %s
  136. -gui %s
  137. %s
  138. --config %s
  139. %s
  140. %s:
  141. GISDBASE %s
  142. LOCATION_NAME %s
  143. MAPSET %s
  144. GISDBASE/LOCATION_NAME/MAPSET %s
  145. %s:
  146. GRASS_GUI %s
  147. GRASS_WISH %s
  148. GRASS_HTML_BROWSER %s
  149. GRASS_ADDON_PATH %s
  150. GRASS_ADDON_BASE %s
  151. GRASS_BATCH_JOB %s
  152. GRASS_PYTHON %s
  153. """ % (_("Usage"),
  154. _("Flags"),
  155. _("print this help message"),
  156. _("show version information and exit"),
  157. _("create given database, location or mapset if it doesn't exist"),
  158. _("use text based interface"),
  159. _("and set as default"),
  160. _("use $DEFAULT_GUI graphical user interface"),
  161. _("and set as default"),
  162. _("print GRASS configuration parameters"),
  163. _("options: arch,build,compiler,path,revision"),
  164. _("Parameters"),
  165. _("initial database (path to GIS data)"),
  166. _("initial location"),
  167. _("initial mapset"),
  168. _("fully qualified initial mapset directory"),
  169. _("Environment variables relevant for startup"),
  170. _("select GUI (text, gui)"),
  171. _("set wish shell name to override 'wish'"),
  172. _("set html web browser for help pages"),
  173. _("set additional path(s) to local GRASS modules or user scripts"),
  174. _("set additional GISBASE for locally installed GRASS Addons"),
  175. _("shell script to be processed as batch job"),
  176. _("set python shell name to override 'python'"))
  177. def help_message():
  178. t = string.Template(help_text)
  179. s = t.substitute(CMD_NAME = cmd_name, DEFAULT_GUI = default_gui)
  180. sys.stderr.write(s)
  181. def create_tmp():
  182. global tmpdir
  183. ## use $TMPDIR if it exists, then $TEMP, otherwise /tmp
  184. tmp = os.getenv('TMPDIR')
  185. if not tmp:
  186. tmp = os.getenv('TEMP')
  187. if not tmp:
  188. tmp = tempfile.gettempdir()
  189. if not tmp:
  190. tmp = '/tmp'
  191. tmpdir = os.path.join(tmp, "grass7-%s-%s" % (user, gis_lock))
  192. try:
  193. os.mkdir(tmpdir, 0700)
  194. except:
  195. fatal(_("Unable to create temporary directory <%s>! Exiting.") % tmpdir)
  196. def create_gisrc():
  197. global gisrc, gisrcrc
  198. # Set the session grassrc file
  199. gisrc = os.path.join(tmpdir, "gisrc")
  200. os.environ['GISRC'] = gisrc
  201. # remove invalid GISRC file to avoid disturbing error messages:
  202. try:
  203. s = readfile(gisrcrc)
  204. if "UNKNOWN" in s:
  205. try_remove(gisrcrc)
  206. s = None
  207. except:
  208. s = None
  209. # Copy the global grassrc file to the session grassrc file
  210. if s:
  211. writefile(gisrc, s)
  212. def read_gisrc():
  213. kv = {}
  214. try:
  215. f = open(gisrc, 'r')
  216. except IOError:
  217. return kv
  218. for line in f:
  219. k, v = line.split(':', 1)
  220. kv[k.strip()] = v.strip()
  221. f.close()
  222. return kv
  223. def read_env_file(path):
  224. kv = {}
  225. f = open(path, 'r')
  226. for line in f:
  227. k, v = line.split(':', 1)
  228. kv[k.strip()] = v.strip()
  229. f.close()
  230. return kv
  231. def write_gisrc(kv):
  232. f = open(gisrc, 'w')
  233. for k, v in kv.iteritems():
  234. f.write("%s: %s\n" % (k, v))
  235. f.close()
  236. def read_gui():
  237. global grass_gui
  238. # At this point the GRASS user interface variable has been set from the
  239. # command line, been set from an external environment variable, or is
  240. # not set. So we check if it is not set
  241. if not grass_gui:
  242. # Check for a reference to the GRASS user interface in the grassrc file
  243. if os.access(gisrc, os.R_OK):
  244. kv = read_gisrc()
  245. if 'GRASS_GUI' in os.environ:
  246. grass_gui = os.environ['GRASS_GUI']
  247. elif 'GUI' in kv:
  248. grass_gui = kv['GUI']
  249. elif 'GRASS_GUI' in kv:
  250. # For backward compatibility (GRASS_GUI renamed to GUI)
  251. grass_gui = kv['GRASS_GUI']
  252. else:
  253. # Set the GRASS user interface to the default if needed
  254. grass_gui = default_gui
  255. if not grass_gui:
  256. grass_gui = default_gui
  257. if grass_gui == 'gui':
  258. grass_gui = default_gui
  259. # FIXME oldtcltk, gis.m, d.m no longer exist
  260. if grass_gui in ['d.m', 'gis.m', 'oldtcltk', 'tcltk']:
  261. warning(_("GUI <%s> not supported in this version") % grass_gui)
  262. grass_gui = default_gui
  263. def path_prepend(dir, var):
  264. path = os.getenv(var)
  265. if path:
  266. path = dir + os.pathsep + path
  267. else:
  268. path = dir
  269. os.environ[var] = path
  270. def path_append(dir, var):
  271. path = os.getenv(var)
  272. if path:
  273. path = path + os.pathsep + dir
  274. else:
  275. path = dir
  276. os.environ[var] = path
  277. def set_paths():
  278. # addons (path)
  279. addon_path = os.getenv('GRASS_ADDON_PATH')
  280. if addon_path:
  281. for path in addon_path.split(os.pathsep):
  282. path_prepend(addon_path, 'PATH')
  283. # addons (base)
  284. addon_base = os.getenv('GRASS_ADDON_BASE')
  285. if not addon_base:
  286. addon_base = os.path.join(grass_config_dir, 'addons')
  287. os.environ['GRASS_ADDON_BASE'] = addon_base
  288. path_prepend(os.path.join(addon_base, 'scripts'), 'PATH')
  289. path_prepend(os.path.join(addon_base, 'bin'), 'PATH')
  290. # standard installation
  291. path_prepend(gfile('scripts'), 'PATH')
  292. path_prepend(gfile('bin'), 'PATH')
  293. # Set PYTHONPATH to find GRASS Python modules
  294. path_prepend(gfile('etc', 'python'), 'PYTHONPATH')
  295. # set path for the GRASS man pages
  296. grass_man_path = os.path.join(gisbase, 'docs', 'man')
  297. addons_man_path = os.path.join(addon_base, 'docs', 'man')
  298. man_path = os.getenv('MANPATH')
  299. if man_path:
  300. path_prepend(addons_man_path, 'MANPATH')
  301. path_prepend(grass_man_path, 'MANPATH')
  302. else:
  303. try:
  304. nul = open(os.devnull, 'w')
  305. p = Popen(['manpath'], stdout = subprocess.PIPE, stderr = nul)
  306. nul.close()
  307. s = p.stdout.read()
  308. p.wait()
  309. sys_man_path = s.strip()
  310. except:
  311. pass
  312. if sys_man_path:
  313. os.environ['MANPATH'] = sys_man_path
  314. path_prepend(addons_man_path, 'MANPATH')
  315. path_prepend(grass_man_path, 'MANPATH')
  316. else:
  317. os.environ['MANPATH'] = addons_man_path
  318. path_prepend(grass_man_path, 'MANPATH')
  319. # Add .py (Python) to list of executable extensions to search for
  320. # in MS-Windows PATH
  321. if windows:
  322. path_append('.PY', 'PATHEXT')
  323. def find_exe(pgm):
  324. for dir in os.getenv('PATH').split(os.pathsep):
  325. path = os.path.join(dir, pgm)
  326. if os.access(path, os.X_OK):
  327. return path
  328. return None
  329. def set_defaults():
  330. # GRASS_PAGER
  331. if not os.getenv('GRASS_PAGER'):
  332. if find_exe("more"):
  333. pager = "more"
  334. elif find_exe("less"):
  335. pager = "less"
  336. elif windows:
  337. pager = "more"
  338. else:
  339. pager = "cat"
  340. os.environ['GRASS_PAGER'] = pager
  341. # GRASS_WISH
  342. if not os.getenv('GRASS_WISH'):
  343. os.environ['GRASS_WISH'] = "wish"
  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 sh == "ksh":
  668. shellname = "Korn Shell"
  669. elif sh == "csh":
  670. shellname = "C Shell"
  671. elif sh == "tcsh":
  672. shellname = "TC Shell"
  673. elif sh == "bash":
  674. shellname = "Bash Shell"
  675. elif sh == "sh":
  676. shellname = "Bourne Shell"
  677. else:
  678. shellname = "shell"
  679. if sh in ['csh', 'tcsh']:
  680. grass_env_file = os.path.join(grass_config_dir, 'cshrc')
  681. elif sh in ['bash', 'msh', 'cygwin']:
  682. grass_env_file = os.path.join(grass_config_dir, 'bashrc')
  683. # check for SHELL
  684. if not os.getenv('SHELL'):
  685. fatal(_("The SHELL variable is not set"))
  686. def check_batch_job():
  687. global batch_job
  688. # hack to process batch jobs:
  689. batch_job = os.getenv('GRASS_BATCH_JOB')
  690. if batch_job:
  691. # defined, but ...
  692. if not os.access(batch_job, os.F_OK):
  693. # wrong file
  694. fatal(_("Job file '%s' has been defined in "
  695. "the 'GRASS_BATCH_JOB' variable but not found. Exiting.\n\n"
  696. "Use 'unset GRASS_BATCH_JOB' to disable batch job processing.") % batch_job)
  697. elif not os.access(batch_job, os.X_OK):
  698. # right file, but ...
  699. fatal(_("Change file permission to 'executable' for '%s'") % batch_job)
  700. else:
  701. message(_("Executing '%s' ...") % batch_job)
  702. grass_gui = "text"
  703. shell = batch_job
  704. bj = Popen(shell, shell=True)
  705. bj.wait()
  706. message(_("Execution of '%s' finished.") % batch_job)
  707. def start_gui():
  708. # Start the chosen GUI but ignore text
  709. if grass_debug:
  710. message(_("GRASS GUI should be <%s>") % grass_gui)
  711. # Check for gui interface
  712. if grass_gui == "wxpython":
  713. Popen([os.getenv('GRASS_PYTHON'),
  714. gfile(wxpython_base, "wxgui.py")])
  715. def clear_screen():
  716. if windows:
  717. pass
  718. # TODO: uncomment when PDCurses works.
  719. # cls
  720. else:
  721. if not os.getenv('GRASS_BATCH_JOB') and not grass_debug:
  722. call(["tput", "clear"])
  723. def show_banner():
  724. sys.stderr.write(r"""
  725. __________ ___ __________ _______________
  726. / ____/ __ \/ | / ___/ ___/ / ____/ _/ ___/
  727. / / __/ /_/ / /| | \__ \\_ \ / / __ / / \__ \
  728. / /_/ / _, _/ ___ |___/ /__/ / / /_/ // / ___/ /
  729. \____/_/ |_/_/ |_/____/____/ \____/___//____/
  730. """)
  731. def say_hello():
  732. sys.stderr.write(_("Welcome to GRASS %s") % grass_version)
  733. def show_info():
  734. sys.stderr.write(
  735. r"""
  736. %-41shttp://grass.osgeo.org
  737. %-41s%s (%s)
  738. %-41sg.manual -i
  739. %-41sg.version -c
  740. """ % (_("GRASS homepage:"),
  741. _("This version running through:"),
  742. shellname, os.getenv('SHELL'),
  743. _("Help is available with the command:"),
  744. _("See the licence terms with:")))
  745. if grass_gui == 'wxpython':
  746. message("%-41sg.gui wxpython" % _("If required, restart the GUI with:"))
  747. else:
  748. message("%-41sg.gui %s" % (_("Start the GUI with:"), default_gui))
  749. message("%-41sexit" % _("When ready to quit enter:"))
  750. message("")
  751. def csh_startup():
  752. global exit_val
  753. userhome = os.getenv('HOME') # save original home
  754. home = location
  755. os.environ['HOME'] = home
  756. cshrc = os.path.join(home, ".cshrc")
  757. tcshrc = os.path.join(home, ".tcshrc")
  758. try_remove(cshrc)
  759. try_remove(tcshrc)
  760. f = open(cshrc, 'w')
  761. f.write("set home = %s\n" % userhome)
  762. f.write("set history = 3000 savehist = 3000 noclobber ignoreeof\n")
  763. f.write("set histfile = %s\n" % os.path.join(os.getenv('HOME'), ".history"))
  764. f.write("set prompt = '\\\n")
  765. f.write("Mapset <%s> in Location <%s> \\\n" % (mapset, location_name))
  766. f.write("GRASS %s > '\n" % grass_version)
  767. f.write("set BOGUS=``;unset BOGUS\n")
  768. path = os.path.join(userhome, ".grass.cshrc") # left for backward compatibility
  769. if os.access(path, os.R_OK):
  770. f.write(readfile(path) + '\n')
  771. if os.access(grass_env_file, os.R_OK):
  772. f.write(readfile(grass_env_file) + '\n')
  773. mail_re = re.compile(r"^ *set *mail *= *")
  774. for filename in [".cshrc", ".tcshrc", ".login"]:
  775. path = os.path.join(userhome, filename)
  776. if os.access(path, os.R_OK):
  777. s = readfile(path)
  778. lines = s.splitlines()
  779. for l in lines:
  780. if mail_re.match(l):
  781. f.write(l)
  782. path = os.getenv('PATH').split(':')
  783. f.write("set path = ( %s ) \n" % ' '.join(path))
  784. f.close()
  785. writefile(tcshrc, readfile(cshrc))
  786. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  787. os.environ['HOME'] = userhome
  788. def bash_startup():
  789. global exit_val
  790. # save command history in mapset dir and remember more
  791. os.environ['HISTFILE'] = os.path.join(location, ".bash_history")
  792. if not os.getenv('HISTSIZE') and not os.getenv('HISTFILESIZE'):
  793. os.environ['HISTSIZE'] = "3000"
  794. # instead of changing $HOME, start bash with: --rcfile "$LOCATION/.bashrc" ?
  795. # if so, must care be taken to explicity call .grass.bashrc et al for
  796. # non-interactive bash batch jobs?
  797. userhome = os.getenv('HOME') # save original home
  798. home = location # save .bashrc in $LOCATION
  799. os.environ['HOME'] = home
  800. bashrc = os.path.join(home, ".bashrc")
  801. try_remove(bashrc)
  802. f = open(bashrc, 'w')
  803. f.write("test -r ~/.alias && . ~/.alias\n")
  804. f.write("PS1='GRASS %s (%s):\w > '\n" % (grass_version, location_name))
  805. f.write("PROMPT_COMMAND=\"'%s'\"\n" % os.path.join(gisbase, 'etc', 'prompt.py'))
  806. # read environmental variables
  807. path = os.path.join(userhome, ".grass.bashrc") # left for backward compatibility
  808. if os.access(path, os.R_OK):
  809. f.write(readfile(path) + '\n')
  810. if os.access(grass_env_file, os.R_OK):
  811. f.write(readfile(grass_env_file) + '\n')
  812. f.write("export PATH=\"%s\"\n" % os.getenv('PATH'))
  813. f.write("export HOME=\"%s\"\n" % userhome) # restore user home path
  814. f.close()
  815. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  816. os.environ['HOME'] = userhome
  817. def default_startup():
  818. global exit_val
  819. if windows:
  820. os.environ['PS1'] = "GRASS %s> " % (grass_version)
  821. # "$ETC/run" doesn't work at all???
  822. exit_val = subprocess.call([os.getenv('SHELL')])
  823. cleanup_dir(os.path.join(location, ".tmp")) # remove GUI session files from .tmp
  824. else:
  825. os.environ['PS1'] = "GRASS %s (%s):\w > " % (grass_version, location_name)
  826. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  827. if exit_val != 0:
  828. fatal(_("Failed to start shell '%s'") % os.getenv('SHELL'))
  829. def done_message():
  830. if batch_job and os.access(batch_job, os.X_OK):
  831. message(_("Batch job '%s' (defined in GRASS_BATCH_JOB variable) was executed.") % batch_job)
  832. message(_("Goodbye from GRASS GIS"))
  833. sys.exit(exit_val)
  834. else:
  835. message(_("Done."))
  836. message("")
  837. message(_("Goodbye from GRASS GIS"))
  838. message("")
  839. def clean_temp():
  840. message(_("Cleaning up temporary files..."))
  841. nul = open(os.devnull, 'w')
  842. call([gfile("etc", "clean_temp")], stdout = nul, stderr = nul)
  843. nul.close()
  844. def grep(string,list):
  845. expr = re.compile(string)
  846. return [elem for elem in list if expr.match(elem)]
  847. def print_params():
  848. plat = gfile(gisbase, 'include', 'Make', 'Platform.make')
  849. fileplat = open(plat)
  850. linesplat = fileplat.readlines()
  851. fileplat.close()
  852. params = sys.argv[2:]
  853. if not params:
  854. params = ['arch', 'build', 'compiler', 'path', 'revision']
  855. for arg in params:
  856. if arg == 'path':
  857. sys.stdout.write("%s\n" % gisbase)
  858. elif arg == 'arch':
  859. val = grep('ARCH',linesplat)
  860. sys.stdout.write("%s\n" % val[0].split('=')[1].strip())
  861. elif arg == 'build':
  862. build = os.path.join(gisbase,'include','grass','confparms.h')
  863. filebuild = open(build)
  864. val = filebuild.readline()
  865. filebuild.close()
  866. sys.stdout.write("%s\n" % val.strip().strip('"').strip())
  867. elif arg == 'compiler':
  868. val = grep('CC',linesplat)
  869. sys.stdout.write("%s\n" % val[0].split('=')[1].strip())
  870. elif arg == 'revision':
  871. rev = os.path.join(gisbase,'include','grass','gis.h')
  872. filerev = open(rev)
  873. linesrev = filerev.readlines()
  874. val = grep('#define GIS_H_VERSION', linesrev)
  875. filerev.close()
  876. sys.stdout.write("%s\n" % val[0].split(':')[1].rstrip('$"\n').strip())
  877. else:
  878. message(_("Parameter <%s> not supported") % arg)
  879. def get_username():
  880. global user
  881. if windows:
  882. user = os.getenv('USERNAME')
  883. if not user:
  884. user = "user_name"
  885. else:
  886. user = os.getenv('USER')
  887. if not user:
  888. user = os.getenv('LOGNAME')
  889. if not user:
  890. try:
  891. p = Popen(['whoami'], stdout = subprocess.PIPE)
  892. s = p.stdout.read()
  893. p.wait()
  894. user = s.strip()
  895. except:
  896. pass
  897. if not user:
  898. user = "user_%d" % os.getuid()
  899. def parse_cmdline():
  900. global args, grass_gui, create_new
  901. args = []
  902. for i in sys.argv[1:]:
  903. # Check if the user asked for the version
  904. if i in ["-v", "--version"]:
  905. message('\n' + readfile(gfile("etc", "license")))
  906. sys.exit()
  907. # Check if the user asked for help
  908. elif i in ["help", "-h", "-help", "--help"]:
  909. help_message()
  910. sys.exit()
  911. # Check if the -text flag was given
  912. elif i in ["-text", "--text"]:
  913. grass_gui = 'text'
  914. # Check if the -gui flag was given
  915. elif i in ["-gui", "--gui"]:
  916. grass_gui = default_gui
  917. # Check if the -wxpython flag was given
  918. elif i in ["-wxpython", "-wx", "--wxpython", "--wx"]:
  919. grass_gui = 'wxpython'
  920. # Check if the user wants to create a new mapset
  921. elif i == "-c":
  922. create_new = True
  923. elif i == "--config":
  924. print_params()
  925. sys.exit()
  926. else:
  927. args.append(i)
  928. ### MAIN script starts here
  929. # Get the system name
  930. windows = sys.platform == 'win32'
  931. cygwin = "cygwin" in sys.platform
  932. macosx = "darwin" in sys.platform
  933. # Set GISBASE
  934. os.environ['GISBASE'] = gisbase
  935. # set HOME
  936. if windows and not os.getenv('HOME'):
  937. os.environ['HOME'] = os.path.join(os.getenv('HOMEDRIVE'), os.getenv('HOMEPATH'))
  938. # set SHELL
  939. if windows:
  940. if os.getenv('GRASS_SH'):
  941. os.environ['SHELL'] = os.getenv('GRASS_SH')
  942. if not os.getenv('SHELL'):
  943. os.environ['SHELL'] = os.getenv('COMSPEC', 'cmd.exe')
  944. atexit.register(cleanup)
  945. # Set default GUI
  946. default_gui = "wxpython"
  947. # the following is only meant to be an internal variable for debugging this script.
  948. # use 'g.gisenv set="DEBUG=[0-5]"' to turn GRASS debug mode on properly.
  949. grass_debug = os.getenv('GRASS_DEBUG')
  950. # Set GRASS version number for R interface etc (must be an env_var for MS-Windows)
  951. os.environ['GRASS_VERSION'] = grass_version
  952. # Set the GIS_LOCK variable to current process id
  953. gis_lock = str(os.getpid())
  954. os.environ['GIS_LOCK'] = gis_lock
  955. # Set the global grassrc file
  956. batch_job = os.getenv('GRASS_BATCH_JOB')
  957. if batch_job:
  958. gisrcrc = os.path.join(grass_config_dir, "rc.%s" % platform.node())
  959. if not os.access(gisrcrc, os.R_OK):
  960. gisrcrc = os.path.join(grass_config_dir, "rc")
  961. else:
  962. gisrcrc = os.path.join(grass_config_dir, "rc")
  963. # Set the username and working directory
  964. get_username()
  965. # Parse the command-line options
  966. parse_cmdline()
  967. # Create the temporary directory and session grassrc file
  968. create_tmp()
  969. # Create the session grassrc file
  970. create_gisrc()
  971. # Set shell (needs to be called before load_env())
  972. check_shell()
  973. # Load environmental variables from the file
  974. load_env()
  975. # Ensure GUI is set
  976. read_gui()
  977. # Set PATH, PYTHONPATH
  978. set_paths()
  979. # Set LD_LIBRARY_PATH (etc) to find GRASS shared libraries
  980. path_prepend(gfile("lib"), ld_library_path_var)
  981. # Set GRASS_PAGER, GRASS_WISH, GRASS_PYTHON, GRASS_GNUPLOT, GRASS_PROJSHARE
  982. set_defaults()
  983. # Set GRASS_HTML_BROWSER
  984. set_browser()
  985. #predefine monitor size for certain architectures
  986. if os.getenv('HOSTTYPE') == 'arm':
  987. # small monitor on ARM (iPAQ, zaurus... etc)
  988. os.environ['GRASS_HEIGHT'] = "320"
  989. os.environ['GRASS_WIDTH'] = "240"
  990. # First time user - GISRC is defined in the GRASS script
  991. if not os.access(gisrc, os.F_OK):
  992. if grass_gui == 'text' and len(args) == 0:
  993. fatal(_("Unable to start GRASS. You can:\n"
  994. " - Launch GRASS with '-gui' switch (`grass70 -gui`)\n"
  995. " - Create manually GISRC file (%s)\n"
  996. " - Launch GRASS with path to "
  997. "the location/mapset as an argument (`grass70 /path/to/location/mapset`)") % gisrcrc)
  998. grass_intro()
  999. else:
  1000. clean_temp()
  1001. message(_("Starting GRASS GIS..."))
  1002. # Check that the GUI works
  1003. check_gui()
  1004. # Parsing argument to get LOCATION
  1005. if not args:
  1006. # Try interactive startup
  1007. location = None
  1008. else:
  1009. if create_new:
  1010. if len(args) > 1:
  1011. non_interactive(args[1], args[0])
  1012. else:
  1013. non_interactive(args[0])
  1014. else:
  1015. non_interactive(args[0])
  1016. # Set language
  1017. set_language()
  1018. # User selects LOCATION and MAPSET if not set
  1019. set_data()
  1020. # Set GISDBASE, LOCATION_NAME, MAPSET, LOCATION from $GISRC
  1021. load_gisrc()
  1022. # Check .gislock file
  1023. check_lock()
  1024. # build user fontcap if specified but not present
  1025. make_fontcap()
  1026. # predefine default driver if DB connection not defined
  1027. # is this really needed?? Modules should call this when/if required.
  1028. if not os.access(os.path.join(location, "VAR"), os.F_OK):
  1029. call(['db.connect', '-c', '--quiet'])
  1030. check_batch_job()
  1031. if not batch_job:
  1032. start_gui()
  1033. clear_screen()
  1034. # Display the version and license info
  1035. if batch_job:
  1036. say_hello()
  1037. grass_gui = 'text'
  1038. clear_screen()
  1039. clean_temp()
  1040. try_remove(lockfile)
  1041. sys.exit(0)
  1042. else:
  1043. show_banner()
  1044. say_hello()
  1045. show_info()
  1046. if grass_gui == "wxpython":
  1047. message(_("Launching <%s> GUI in the background, please wait...") % grass_gui)
  1048. if sh in ['csh', 'tcsh']:
  1049. csh_startup()
  1050. elif sh in ['bash', 'msh', 'cygwin']:
  1051. bash_startup()
  1052. else:
  1053. default_startup()
  1054. clear_screen()
  1055. clean_env()
  1056. clean_temp()
  1057. try_remove(lockfile)
  1058. # Save GISRC
  1059. s = readfile(gisrc)
  1060. if not os.path.exists(grass_config_dir):
  1061. os.mkdir(grass_config_dir)
  1062. writefile(gisrcrc, s)
  1063. cleanup()
  1064. # After this point no more grass modules may be called
  1065. done_message()