grass.py 47 KB

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