grass.py 40 KB

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