grass.py 40 KB

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