grass.py 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447
  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-2013 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. path_prepend(gfile('etc', 'python'), 'PYTHONPATH')
  320. # set path for the GRASS man pages
  321. grass_man_path = os.path.join(gisbase, 'docs', 'man')
  322. addons_man_path = os.path.join(addon_base, 'docs', 'man')
  323. man_path = os.getenv('MANPATH')
  324. sys_man_path = None
  325. if man_path:
  326. path_prepend(addons_man_path, 'MANPATH')
  327. path_prepend(grass_man_path, 'MANPATH')
  328. else:
  329. try:
  330. nul = open(os.devnull, 'w')
  331. p = Popen(['manpath'], stdout=subprocess.PIPE, stderr=nul)
  332. nul.close()
  333. s = p.stdout.read()
  334. p.wait()
  335. sys_man_path = s.strip()
  336. except:
  337. pass
  338. if sys_man_path:
  339. os.environ['MANPATH'] = sys_man_path
  340. path_prepend(addons_man_path, 'MANPATH')
  341. path_prepend(grass_man_path, 'MANPATH')
  342. else:
  343. os.environ['MANPATH'] = addons_man_path
  344. path_prepend(grass_man_path, 'MANPATH')
  345. # Add .py (Python) to list of executable extensions to search for
  346. # in MS-Windows PATH
  347. if windows:
  348. path_append('.PY', 'PATHEXT')
  349. def find_exe(pgm):
  350. for dir in os.getenv('PATH').split(os.pathsep):
  351. path = os.path.join(dir, pgm)
  352. if os.access(path, os.X_OK):
  353. return path
  354. return None
  355. def set_defaults():
  356. # GRASS_PAGER
  357. if not os.getenv('GRASS_PAGER'):
  358. if find_exe("more"):
  359. pager = "more"
  360. elif find_exe("less"):
  361. pager = "less"
  362. elif windows:
  363. pager = "more"
  364. else:
  365. pager = "cat"
  366. os.environ['GRASS_PAGER'] = pager
  367. # GRASS_PYTHON
  368. if not os.getenv('GRASS_PYTHON'):
  369. if windows:
  370. os.environ['GRASS_PYTHON'] = "python.exe"
  371. else:
  372. os.environ['GRASS_PYTHON'] = "python"
  373. # GRASS_GNUPLOT
  374. if not os.getenv('GRASS_GNUPLOT'):
  375. os.environ['GRASS_GNUPLOT'] = "gnuplot -persist"
  376. # GRASS_PROJSHARE
  377. if not os.getenv('GRASS_PROJSHARE'):
  378. os.environ['GRASS_PROJSHARE'] = config_projshare
  379. def set_browser():
  380. # GRASS_HTML_BROWSER
  381. browser = os.getenv('GRASS_HTML_BROWSER')
  382. if not browser:
  383. if macosx:
  384. # OSX doesn't execute browsers from the shell PATH - route thru a
  385. # script
  386. browser = gfile('etc', "html_browser_mac.sh")
  387. os.environ['GRASS_HTML_BROWSER_MACOSX'] = "-b com.apple.helpviewer"
  388. if windows or cygwin:
  389. # MinGW startup moved to into init.bat
  390. browser = "explorer"
  391. else:
  392. # the usual suspects
  393. browsers = ["xdg-open", "htmlview", "konqueror", "mozilla",
  394. "mozilla-firefox", "firefox", "iceweasel", "opera",
  395. "netscape", "dillo", "lynx", "links", "w3c"]
  396. for b in browsers:
  397. if find_exe(b):
  398. browser = b
  399. break
  400. elif macosx:
  401. # OSX doesn't execute browsers from the shell PATH - route thru a
  402. # script
  403. os.environ['GRASS_HTML_BROWSER_MACOSX'] = "-b %s" % browser
  404. browser = gfile('etc', "html_browser_mac.sh")
  405. if not browser:
  406. warning(_("Searched for a web browser, but none found"))
  407. # even so we set konqueror to make lib/gis/parser.c happy:
  408. browser = "konqueror"
  409. os.environ['GRASS_HTML_BROWSER'] = browser
  410. def grass_intro():
  411. intro = _(r"""
  412. WELCOME TO GRASS %s
  413. 1) Have at your side all available GRASS GIS tutorials
  414. 2) When working on your location, the following materials
  415. are extremely useful:
  416. - A topographic map of your area
  417. - Current catalog of available computer maps
  418. 3) Check the GRASS GIS web pages for supporting mailing lists and more:
  419. http://grass.osgeo.org
  420. """) % grass_version
  421. sys.stderr.write(intro)
  422. sys.stderr.write("\n")
  423. sys.stderr.write(_("Hit RETURN to continue"))
  424. sys.stdin.readline()
  425. # for convenience, define pwd as GISDBASE:
  426. s = r"""GISDBASE: %s
  427. LOCATION_NAME: <UNKNOWN>
  428. MAPSET: <UNKNOWN>
  429. """ % os.getcwd()
  430. writefile(gisrc, s)
  431. def check_gui():
  432. global grass_gui, wxpython_base
  433. # Check if we are running X windows by checking the DISPLAY variable
  434. if os.getenv('DISPLAY') or windows or macosx:
  435. # Check if python is working properly
  436. if grass_gui in ('wxpython', 'gtext'):
  437. nul = open(os.devnull, 'w')
  438. p = Popen([os.environ['GRASS_PYTHON']], stdin=subprocess.PIPE,
  439. stdout=nul, stderr=nul)
  440. nul.close()
  441. p.stdin.write("variable=True")
  442. p.stdin.close()
  443. p.wait()
  444. if p.returncode == 0:
  445. # Set the wxpython base directory
  446. wxpython_base = gfile("etc", "gui", "wxpython")
  447. else:
  448. # Python was not found - switch to text interface mode
  449. warning(_("The python command does not work as expected!\n"
  450. "Please check your GRASS_PYTHON environment variable.\n"
  451. "Use the -help option for details.\n"
  452. "Switching to text based interface mode.\n\n"
  453. "Hit RETURN to continue.\n"))
  454. sys.stdin.readline()
  455. grass_gui = 'text'
  456. else:
  457. # Display a message if a graphical interface was expected
  458. if grass_gui != 'text':
  459. # Set the interface mode to text
  460. warning(_("It appears that the X Windows system is not active.\n"
  461. "A graphical based user interface is not supported.\n"
  462. "Switching to text based interface mode.\n\n"
  463. "Hit RETURN to continue"""))
  464. sys.stdin.readline()
  465. grass_gui = 'text'
  466. # Save the user interface variable in the grassrc file - choose a temporary
  467. # file name that should not match another file
  468. if os.access(gisrc, os.F_OK):
  469. kv = read_gisrc()
  470. kv['GUI'] = grass_gui
  471. write_gisrc(kv)
  472. def non_interactive(arg, geofile=None):
  473. global gisdbase, location_name, mapset, location
  474. # Try non-interactive startup
  475. l = None
  476. if arg == '-':
  477. if location:
  478. l = location
  479. else:
  480. l = arg
  481. if l:
  482. if l == '.':
  483. l = os.getcwd()
  484. elif not os.path.isabs(l):
  485. l = os.path.abspath(l)
  486. l, mapset = os.path.split(l)
  487. if not mapset:
  488. l, mapset = os.path.split(l)
  489. l, location_name = os.path.split(l)
  490. gisdbase = l
  491. if gisdbase and location_name and mapset:
  492. location = os.path.join(gisdbase, location_name, mapset)
  493. # check if 'location' is a valid GRASS location/mapset
  494. if not os.access(os.path.join(location, "WIND"), os.R_OK):
  495. if not create_new:
  496. # 'location' is not valid, check if 'location_name' is
  497. # a valid GRASS location
  498. if not os.path.exists(os.path.join(gisdbase, location_name)):
  499. fatal(_("Location <%s> doesn't exist") % os.path.join(gisdbase, location_name))
  500. elif 'PERMANENT' not in os.listdir(os.path.join(gisdbase, location_name)) or \
  501. not os.path.isdir(os.path.join(gisdbase, location_name, 'PERMANENT')) or \
  502. not os.path.isfile((os.path.join(gisdbase, location_name, 'PERMANENT',
  503. 'DEFAULT_WIND'))):
  504. fatal(_("ERROR: <%s> is not a valid GRASS location") % \
  505. os.path.join(gisdbase, location_name))
  506. else:
  507. fatal(_("Mapset <%s> doesn't exist in GRASS location <%s>. "
  508. "A new mapset can be created by '-c' switch.") % (mapset, location_name))
  509. else:
  510. # 'location' is not valid, the user wants to create
  511. # mapset on the fly
  512. if not os.access(os.path.join(gisdbase, location_name,
  513. "PERMANENT",
  514. "DEFAULT_WIND"), os.F_OK):
  515. # 'location_name' is not a valid GRASS location,
  516. # create new location and 'PERMANENT' mapset
  517. gisdbase = os.path.join(gisdbase, location_name)
  518. location_name = mapset
  519. mapset = "PERMANENT"
  520. if os.access(os.path.join(os.path.join(gisdbase,
  521. location_name,
  522. "PERMANENT",
  523. "DEFAULT_WIND")),
  524. os.F_OK):
  525. fatal(_("Failed to create new location. "
  526. "The location <%s> already exists." % location_name))
  527. if gfile('etc', 'python') not in sys.path:
  528. sys.path.append(gfile('etc', 'python'))
  529. from grass.script import core as grass
  530. try:
  531. if geofile and geofile.upper().find('EPSG:') > -1:
  532. # create location using EPSG code
  533. epsg = geofile.split(':', 1)[1]
  534. grass.create_location(gisdbase, location_name,
  535. epsg=epsg)
  536. else:
  537. # create location using georeferenced file
  538. grass.create_location(gisdbase, location_name,
  539. filename=geofile)
  540. except grass.ScriptError, e:
  541. fatal(e.value.strip('"').strip("'").replace('\\n',
  542. os.linesep))
  543. else:
  544. # 'location_name' is a valid GRASS location,
  545. # create new mapset
  546. os.mkdir(location)
  547. # copy PERMANENT/DEFAULT_WIND to <mapset>/WIND
  548. s = readfile(os.path.join(gisdbase, location_name,
  549. "PERMANENT", "DEFAULT_WIND"))
  550. writefile(os.path.join(location, "WIND"), s)
  551. message(_("Missing WIND file fixed"))
  552. if os.access(gisrc, os.R_OK):
  553. kv = read_gisrc()
  554. else:
  555. kv = {}
  556. kv['GISDBASE'] = gisdbase
  557. kv['LOCATION_NAME'] = location_name
  558. kv['MAPSET'] = mapset
  559. write_gisrc(kv)
  560. else:
  561. fatal(_("GISDBASE, LOCATION_NAME and MAPSET variables not set properly.\n"
  562. "Interactive startup needed."))
  563. def set_data():
  564. # User selects LOCATION and MAPSET if not set
  565. if not location:
  566. # Check for text interface
  567. if grass_gui == 'text':
  568. pass
  569. # Check for GUI
  570. elif grass_gui in ('gtext', 'wxpython'):
  571. gui_startup(grass_gui == 'gtext')
  572. else:
  573. # Shouldn't need this but you never know
  574. fatal(_("Invalid user interface specified - <%s>. "
  575. "Use the --help option to see valid interface names.") % grass_gui)
  576. def gui_startup(wscreen_only = False):
  577. if grass_gui in ('wxpython', 'gtext'):
  578. ret = call([os.getenv('GRASS_PYTHON'),
  579. gfile(wxpython_base, "gis_set.py")])
  580. if ret == 0:
  581. pass
  582. elif ret == 1:
  583. # The startup script printed an error message so wait
  584. # for user to read it
  585. message(_("Error in GUI startup. If necessary, please "
  586. "report this error to the GRASS developers.\n"
  587. "Switching to text mode now.\n\n"
  588. "Hit RETURN to continue..."))
  589. sys.stdin.readline()
  590. os.execlp(cmd_name, "-text")
  591. sys.exit(1)
  592. elif ret == 2:
  593. # User wants to exit from GRASS
  594. message(_("Received EXIT message from GUI.\nGRASS is not started. Bye."))
  595. sys.exit(0)
  596. else:
  597. fatal(_("Invalid return code from GUI startup script.\n"
  598. "Please advise GRASS developers of this error."))
  599. def load_gisrc():
  600. global gisdbase, location_name, mapset, location
  601. kv = read_gisrc()
  602. gisdbase = kv.get('GISDBASE')
  603. location_name = kv.get('LOCATION_NAME')
  604. mapset = kv.get('MAPSET')
  605. if not gisdbase or not location_name or not mapset:
  606. fatal(_("Error reading data path information from g.gisenv.\n"
  607. "GISDBASE=%(gisbase)s\n"
  608. "LOCATION_NAME=%(location)s\n"
  609. "MAPSET=%(mapset)s\n\n"
  610. "Check the <%s(file)> file." % \
  611. {'gisbase': gisdbase, 'location': location_name,
  612. 'mapset': mapset, 'file': gisrcrc}))
  613. location = os.path.join(gisdbase, location_name, mapset)
  614. # load environmental variables from grass_env_file
  615. def load_env():
  616. if not os.access(grass_env_file, os.R_OK):
  617. return
  618. for line in readfile(grass_env_file).split(os.linesep):
  619. try:
  620. k, v = map(lambda x: x.strip(), line.strip().split(' ', 1)[1].split('=', 1))
  621. except:
  622. continue
  623. os.environ[k] = v
  624. # Allow for mixed ISIS-GRASS Environment
  625. if os.getenv('ISISROOT'):
  626. isis = os.getenv('ISISROOT')
  627. os.environ['ISIS_LIB'] = isis + os.sep + "lib"
  628. os.environ['ISIS_3RDPARTY'] = isis + os.sep + "3rdParty" + os.sep + "lib"
  629. os.environ['QT_PLUGIN_PATH'] = isis + os.sep + "3rdParty" + os.sep + "plugins"
  630. #os.environ['ISIS3DATA'] = isis + "$ISIS3DATA"
  631. libpath = os.getenv('LD_LIBRARY_PATH', '')
  632. isislibpath = os.getenv('ISIS_LIB')
  633. isis3rdparty = os.getenv('ISIS_3RDPARTY')
  634. os.environ['LD_LIBRARY_PATH'] = libpath + os.pathsep + isislibpath + os.pathsep + isis3rdparty
  635. def set_language():
  636. # This function is used to override system default language and locale
  637. # Such override can be requested only from wxGUI
  638. # An override if user has provided correct environmental variables as
  639. # LC_MESSAGES or LANG is not necessary.
  640. # Unfortunately currently a working solution for Windows is lacking
  641. # thus it always on Vista and XP will print an error.
  642. # See discussion for Windows not following its own documentation and
  643. # not accepting ISO codes as valid locale identifiers http://bugs.python.org/issue10466
  644. import locale
  645. language = 'None' # Such string sometimes is present in wx file
  646. encoding = None
  647. # Override value is stored in wxGUI preferences file.
  648. # As it's the only thing required, we'll just grep it out.
  649. try:
  650. fd = open(os.path.join(grass_config_dir, 'wx'), 'r')
  651. except:
  652. # Even if there is no override, we still need to set locale.
  653. pass
  654. else:
  655. for line in fd:
  656. if re.search('^language', line):
  657. line = line.rstrip(' %s' % os.linesep)
  658. language = ''.join(line.split(';')[-1:])
  659. break
  660. fd.close()
  661. if language == 'None' or language == '' or not language:
  662. # Language override is disabled (system language specified)
  663. # As by default program runs with C locale, but users expect to
  664. # have their default locale, we'll just set default locale
  665. try:
  666. locale.setlocale(locale.LC_ALL, '')
  667. except locale.Error, e:
  668. # If we get here, system locale settings are terribly wrong
  669. # There is no point to continue as GRASS/Python will fail
  670. # in some other unpredictable way.
  671. print "System locale is not usable. It indicates misconfigured environment."
  672. print "Reported error message: %s" % e
  673. sys.exit("Fix system locale settings and then try again.")
  674. language, encoding = locale.getdefaultlocale()
  675. if not language:
  676. warning("Default locale settings are missing. GRASS running with C locale.")
  677. return
  678. else:
  679. warning("A language override has been requested. Trying to switch GRASS into '%s'..." % language)
  680. try:
  681. locale.setlocale(locale.LC_ALL, language)
  682. except locale.Error, e:
  683. try:
  684. # Locale lang.encoding might be missing. Let's try
  685. # UTF-8 encoding before giving up as on Linux systems
  686. # lang.UTF-8 locales are more common than legacy
  687. # ISO-8859 ones.
  688. encoding = 'UTF-8'
  689. normalized = locale.normalize('%s.%s' % (language, encoding))
  690. locale.setlocale(locale.LC_ALL, normalized)
  691. except locale.Error, e:
  692. # The last attempt...
  693. try:
  694. encoding = locale.getpreferredencoding()
  695. normalized = locale.normalize('%s.%s' % (language, encoding))
  696. locale.setlocale(locale.LC_ALL, normalized)
  697. except locale.Error, e:
  698. # If we got so far, attempts to set up language and locale have failed
  699. # on this system
  700. sys.stderr.write("Failed to enforce user specified language '%s' with error: '%s'\n" % (language, e))
  701. sys.stderr.write("A LANGUAGE environmental variable has been set.\nPart of messages will be displayed in the requested language.\n")
  702. # Even if setting locale will fail, let's set LANG in a hope,
  703. # that UI will use it GRASS texts will be in selected language,
  704. # system messages (i.e. OK, Cancel etc.) - in system default
  705. # language
  706. os.environ['LANGUAGE'] = language
  707. return
  708. # Set up environment for subprocesses
  709. os.environ['LANGUAGE'] = language
  710. os.environ['LANG'] = language
  711. if encoding:
  712. normalized = locale.normalize('%s.%s' % (language, encoding))
  713. else:
  714. normalized = language
  715. for lc in ('LC_CTYPE', 'LC_MESSAGES', 'LC_TIME', 'LC_COLLATE',
  716. 'LC_MONETARY', 'LC_PAPER', 'LC_NAME', 'LC_ADDRESS',
  717. 'LC_TELEPHONE', 'LC_MEASUREMENT', 'LC_IDENTIFICATION'):
  718. os.environ[lc] = normalized
  719. # Some code in GRASS might not like other decimal separators than .
  720. # Other potential sources for problems are: LC_TIME LC_CTYPE
  721. locale.setlocale(locale.LC_NUMERIC, 'C')
  722. os.environ['LC_NUMERIC'] = 'C'
  723. if os.getenv('LC_ALL'):
  724. del os.environ['LC_ALL'] # Remove LC_ALL to not override LC_NUMERIC
  725. # From now on enforce the new language
  726. if encoding:
  727. gettext.install('grasslibs', os.path.join(gisbase, 'locale'), codeset=encoding)
  728. else:
  729. gettext.install('grasslibs', os.path.join(gisbase, 'locale'), unicode=True)
  730. def check_lock():
  731. global lockfile
  732. if not os.path.exists(location):
  733. fatal(_("Path '%s' doesn't exist") % location)
  734. # Check for concurrent use
  735. lockfile = os.path.join(location, ".gislock")
  736. ret = call([gfile("etc", "lock"), lockfile, "%d" % os.getpid()])
  737. if ret == 0:
  738. msg = None
  739. elif ret == 2:
  740. msg = _("%(user)s is currently running GRASS in selected mapset (" \
  741. "file %(file)s found). Concurrent use not allowed." % {
  742. 'user': user, 'file': lockfile})
  743. else:
  744. msg = _("Unable to properly access '%s'.\n"
  745. "Please notify system personel.") % lockfile
  746. if msg:
  747. if grass_gui == "wxpython":
  748. call([os.getenv('GRASS_PYTHON'),
  749. os.path.join(wxpython_base, "gis_set_error.py"),
  750. 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. def show_info():
  851. sys.stderr.write(
  852. r"""
  853. %-41shttp://grass.osgeo.org
  854. %-41s%s (%s)
  855. %-41sg.manual -i
  856. %-41sg.version -c
  857. """ % (_("GRASS homepage:"),
  858. _("This version running through:"),
  859. shellname, os.getenv('SHELL'),
  860. _("Help is available with the command:"),
  861. _("See the licence terms with:")))
  862. if grass_gui == 'wxpython':
  863. message("%-41sg.gui wxpython" % _("If required, restart the GUI with:"))
  864. else:
  865. message("%-41sg.gui %s" % (_("Start the GUI with:"), default_gui))
  866. message("%-41sexit" % _("When ready to quit enter:"))
  867. message("")
  868. def csh_startup():
  869. global exit_val
  870. userhome = os.getenv('HOME') # save original home
  871. home = location
  872. os.environ['HOME'] = home
  873. cshrc = os.path.join(home, ".cshrc")
  874. tcshrc = os.path.join(home, ".tcshrc")
  875. try_remove(cshrc)
  876. try_remove(tcshrc)
  877. f = open(cshrc, 'w')
  878. f.write("set home = %s\n" % userhome)
  879. f.write("set history = 3000 savehist = 3000 noclobber ignoreeof\n")
  880. f.write("set histfile = %s\n" % os.path.join(os.getenv('HOME'),
  881. ".history"))
  882. f.write("set prompt = '\\\n")
  883. f.write("Mapset <%s> in Location <%s> \\\n" % (mapset, location_name))
  884. f.write("GRASS %s > '\n" % grass_version)
  885. f.write("set BOGUS=``;unset BOGUS\n")
  886. path = os.path.join(userhome, ".grass.cshrc") # left for backward compatibility
  887. if os.access(path, os.R_OK):
  888. f.write(readfile(path) + '\n')
  889. if os.access(grass_env_file, os.R_OK):
  890. f.write(readfile(grass_env_file) + '\n')
  891. mail_re = re.compile(r"^ *set *mail *= *")
  892. for filename in [".cshrc", ".tcshrc", ".login"]:
  893. path = os.path.join(userhome, filename)
  894. if os.access(path, os.R_OK):
  895. s = readfile(path)
  896. lines = s.splitlines()
  897. for l in lines:
  898. if mail_re.match(l):
  899. f.write(l)
  900. path = os.getenv('PATH').split(':')
  901. f.write("set path = ( %s ) \n" % ' '.join(path))
  902. f.close()
  903. writefile(tcshrc, readfile(cshrc))
  904. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  905. os.environ['HOME'] = userhome
  906. def bash_startup():
  907. global exit_val
  908. # save command history in mapset dir and remember more
  909. os.environ['HISTFILE'] = os.path.join(location, ".bash_history")
  910. if not os.getenv('HISTSIZE') and not os.getenv('HISTFILESIZE'):
  911. os.environ['HISTSIZE'] = "3000"
  912. # instead of changing $HOME, start bash with: --rcfile "$LOCATION/.bashrc" ?
  913. # if so, must care be taken to explicity call .grass.bashrc et al for
  914. # non-interactive bash batch jobs?
  915. userhome = os.getenv('HOME') # save original home
  916. home = location # save .bashrc in $LOCATION
  917. os.environ['HOME'] = home
  918. bashrc = os.path.join(home, ".bashrc")
  919. try_remove(bashrc)
  920. f = open(bashrc, 'w')
  921. f.write("test -r ~/.alias && . ~/.alias\n")
  922. if os.getenv('ISISROOT'):
  923. f.write("PS1='ISIS-GRASS %s (%s):\w > '\n" % (grass_version, location_name))
  924. else:
  925. f.write("PS1='GRASS %s (%s):\w > '\n" % (grass_version, location_name))
  926. f.write("PROMPT_COMMAND=\"'%s'\"\n" % os.path.join(gisbase, 'etc',
  927. 'prompt.py'))
  928. # read environmental variables
  929. path = os.path.join(userhome, ".grass.bashrc") # left for backward compatibility
  930. if os.access(path, os.R_OK):
  931. f.write(readfile(path) + '\n')
  932. if os.access(grass_env_file, os.R_OK):
  933. f.write(readfile(grass_env_file) + '\n')
  934. f.write("export PATH=\"%s\"\n" % os.getenv('PATH'))
  935. f.write("export HOME=\"%s\"\n" % userhome) # restore user home path
  936. f.close()
  937. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  938. os.environ['HOME'] = userhome
  939. def default_startup():
  940. global exit_val
  941. if windows:
  942. os.environ['PS1'] = "GRASS %s> " % (grass_version)
  943. # "$ETC/run" doesn't work at all???
  944. exit_val = subprocess.call([os.getenv('SHELL')])
  945. cleanup_dir(os.path.join(location, ".tmp")) # remove GUI session files from .tmp
  946. else:
  947. os.environ['PS1'] = "GRASS %s (%s):\w > " % (grass_version, location_name)
  948. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  949. if exit_val != 0:
  950. fatal(_("Failed to start shell '%s'") % os.getenv('SHELL'))
  951. def done_message():
  952. if batch_job and os.access(batch_job, os.X_OK):
  953. message(_("Batch job '%s' (defined in GRASS_BATCH_JOB variable) was executed.") % batch_job)
  954. message(_("Goodbye from GRASS GIS"))
  955. sys.exit(exit_val)
  956. else:
  957. message(_("Done."))
  958. message("")
  959. message(_("Goodbye from GRASS GIS"))
  960. message("")
  961. def clean_temp():
  962. message(_("Cleaning up temporary files..."))
  963. nul = open(os.devnull, 'w')
  964. call([gfile("etc", "clean_temp")], stdout=nul, stderr=nul)
  965. nul.close()
  966. def grep(string,list):
  967. expr = re.compile(string)
  968. return [elem for elem in list if expr.match(elem)]
  969. def print_params():
  970. plat = gfile(gisbase, 'include', 'Make', 'Platform.make')
  971. fileplat = open(plat)
  972. linesplat = fileplat.readlines()
  973. fileplat.close()
  974. params = sys.argv[2:]
  975. if not params:
  976. params = ['arch', 'build', 'compiler', 'path', 'revision']
  977. for arg in params:
  978. if arg == 'path':
  979. sys.stdout.write("%s\n" % gisbase)
  980. elif arg == 'arch':
  981. val = grep('ARCH',linesplat)
  982. sys.stdout.write("%s\n" % val[0].split('=')[1].strip())
  983. elif arg == 'build':
  984. build = os.path.join(gisbase,'include','grass','confparms.h')
  985. filebuild = open(build)
  986. val = filebuild.readline()
  987. filebuild.close()
  988. sys.stdout.write("%s\n" % val.strip().strip('"').strip())
  989. elif arg == 'compiler':
  990. val = grep('CC',linesplat)
  991. sys.stdout.write("%s\n" % val[0].split('=')[1].strip())
  992. elif arg == 'revision':
  993. rev = os.path.join(gisbase,'include','grass','gis.h')
  994. filerev = open(rev)
  995. linesrev = filerev.readlines()
  996. val = grep('#define GIS_H_VERSION', linesrev)
  997. filerev.close()
  998. sys.stdout.write("%s\n" % val[0].split(':')[1].rstrip('$"\n').strip())
  999. else:
  1000. message(_("Parameter <%s> not supported") % arg)
  1001. def get_username():
  1002. global user
  1003. if windows:
  1004. user = os.getenv('USERNAME')
  1005. if not user:
  1006. user = "user_name"
  1007. else:
  1008. user = os.getenv('USER')
  1009. if not user:
  1010. user = os.getenv('LOGNAME')
  1011. if not user:
  1012. try:
  1013. p = Popen(['whoami'], stdout = subprocess.PIPE)
  1014. s = p.stdout.read()
  1015. p.wait()
  1016. user = s.strip()
  1017. except:
  1018. pass
  1019. if not user:
  1020. user = "user_%d" % os.getuid()
  1021. def parse_cmdline():
  1022. global args, grass_gui, create_new
  1023. args = []
  1024. for i in sys.argv[1:]:
  1025. # Check if the user asked for the version
  1026. if i in ["-v", "--version"]:
  1027. message('\n' + readfile(gfile("etc", "license")))
  1028. sys.exit()
  1029. # Check if the user asked for help
  1030. elif i in ["help", "-h", "-help", "--help"]:
  1031. help_message()
  1032. sys.exit()
  1033. # Check if the -text flag was given
  1034. elif i in ["-text", "--text"]:
  1035. grass_gui = 'text'
  1036. # Check if the -gtext flag was given
  1037. elif i in ["-gtext", "--gtext"]:
  1038. grass_gui = 'gtext'
  1039. # Check if the -gui flag was given
  1040. elif i in ["-gui", "--gui"]:
  1041. grass_gui = default_gui
  1042. # Check if the -wxpython flag was given
  1043. elif i in ["-wxpython", "-wx", "--wxpython", "--wx"]:
  1044. grass_gui = 'wxpython'
  1045. # Check if the user wants to create a new mapset
  1046. elif i == "-c":
  1047. create_new = True
  1048. elif i == "--config":
  1049. print_params()
  1050. sys.exit()
  1051. else:
  1052. args.append(i)
  1053. ### MAIN script starts here
  1054. # Get the system name
  1055. windows = sys.platform == 'win32'
  1056. cygwin = "cygwin" in sys.platform
  1057. macosx = "darwin" in sys.platform
  1058. ### commented-out: broken winGRASS
  1059. # if 'GISBASE' in os.environ:
  1060. # sys.exit(_("ERROR: GRASS GIS is already running "
  1061. # "(environmental variable GISBASE found)"))
  1062. # Set GISBASE
  1063. os.environ['GISBASE'] = gisbase
  1064. # set HOME
  1065. if windows and not os.getenv('HOME'):
  1066. os.environ['HOME'] = os.path.join(os.getenv('HOMEDRIVE'),
  1067. os.getenv('HOMEPATH'))
  1068. # set SHELL
  1069. if windows:
  1070. if os.getenv('GRASS_SH'):
  1071. os.environ['SHELL'] = os.getenv('GRASS_SH')
  1072. if not os.getenv('SHELL'):
  1073. os.environ['SHELL'] = os.getenv('COMSPEC', 'cmd.exe')
  1074. atexit.register(cleanup)
  1075. # Set default GUI
  1076. default_gui = "wxpython"
  1077. # the following is only meant to be an internal variable for debugging this
  1078. # script. use 'g.gisenv set="DEBUG=[0-5]"' to turn GRASS debug mode on properly
  1079. grass_debug = os.getenv('GRASS_DEBUG')
  1080. # Set GRASS version number for R interface etc (must be an env_var for MS-Windows)
  1081. os.environ['GRASS_VERSION'] = grass_version
  1082. # Set the GIS_LOCK variable to current process id
  1083. gis_lock = str(os.getpid())
  1084. os.environ['GIS_LOCK'] = gis_lock
  1085. if not os.path.exists(grass_config_dir):
  1086. os.mkdir(grass_config_dir)
  1087. # Set the global grassrc file
  1088. batch_job = os.getenv('GRASS_BATCH_JOB')
  1089. if batch_job:
  1090. gisrcrc = os.path.join(grass_config_dir, "rc.%s" % platform.node())
  1091. if not os.access(gisrcrc, os.R_OK):
  1092. gisrcrc = os.path.join(grass_config_dir, "rc")
  1093. else:
  1094. gisrcrc = os.path.join(grass_config_dir, "rc")
  1095. # Set the username and working directory
  1096. get_username()
  1097. # Parse the command-line options
  1098. parse_cmdline()
  1099. # Set language
  1100. # This has to be called before any _() function call!
  1101. # Subsequent functions are using _() calls and
  1102. # thus must be called only after Language has been set.
  1103. set_language()
  1104. # Create the temporary directory and session grassrc file
  1105. create_tmp()
  1106. # Create the session grassrc file
  1107. create_gisrc()
  1108. # Set shell (needs to be called before load_env())
  1109. check_shell()
  1110. # Load environmental variables from the file
  1111. load_env()
  1112. # Ensure GUI is set
  1113. read_gui()
  1114. # Set PATH, PYTHONPATH
  1115. set_paths()
  1116. # Set LD_LIBRARY_PATH (etc) to find GRASS shared libraries
  1117. path_prepend(gfile("lib"), ld_library_path_var)
  1118. # Set GRASS_PAGER, GRASS_PYTHON, GRASS_GNUPLOT, GRASS_PROJSHARE
  1119. set_defaults()
  1120. # Set GRASS_HTML_BROWSER
  1121. set_browser()
  1122. #predefine monitor size for certain architectures
  1123. if os.getenv('HOSTTYPE') == 'arm':
  1124. # small monitor on ARM (iPAQ, zaurus... etc)
  1125. os.environ['GRASS_HEIGHT'] = "320"
  1126. os.environ['GRASS_WIDTH'] = "240"
  1127. # First time user - GISRC is defined in the GRASS script
  1128. if not os.access(gisrc, os.F_OK):
  1129. if grass_gui == 'text' and len(args) == 0:
  1130. fatal(_("Unable to start GRASS. You can:\n"
  1131. " - Launch GRASS with '-gui' switch (`grass71 -gui`)\n"
  1132. " - Create manually GISRC file (%s)\n"
  1133. " - Launch GRASS with path to "
  1134. "the location/mapset as an argument (`grass71 /path/to/location/mapset`)") % gisrcrc)
  1135. grass_intro()
  1136. else:
  1137. clean_temp()
  1138. message(_("Starting GRASS GIS..."))
  1139. # Check that the GUI works
  1140. check_gui()
  1141. # Parsing argument to get LOCATION
  1142. if not args:
  1143. # Try interactive startup
  1144. location = None
  1145. else:
  1146. if create_new:
  1147. if len(args) > 1:
  1148. non_interactive(args[1], args[0])
  1149. else:
  1150. non_interactive(args[0])
  1151. else:
  1152. non_interactive(args[0])
  1153. # User selects LOCATION and MAPSET if not set
  1154. set_data()
  1155. # Set GISDBASE, LOCATION_NAME, MAPSET, LOCATION from $GISRC
  1156. load_gisrc()
  1157. # Check .gislock file
  1158. check_lock()
  1159. # build user fontcap if specified but not present
  1160. make_fontcap()
  1161. # predefine default driver if DB connection not defined
  1162. # is this really needed?? Modules should call this when/if required.
  1163. if not os.access(os.path.join(location, "VAR"), os.F_OK):
  1164. call(['db.connect', '-c', '--quiet'])
  1165. check_batch_job()
  1166. if not batch_job:
  1167. start_gui()
  1168. clear_screen()
  1169. # Display the version and license info
  1170. if batch_job:
  1171. grass_gui = 'text'
  1172. clear_screen()
  1173. clean_temp()
  1174. try_remove(lockfile)
  1175. sys.exit(0)
  1176. else:
  1177. show_banner()
  1178. say_hello()
  1179. show_info()
  1180. if grass_gui == "wxpython":
  1181. message(_("Launching <%s> GUI in the background, please wait...") % grass_gui)
  1182. if sh in ['csh', 'tcsh']:
  1183. csh_startup()
  1184. elif sh in ['bash', 'msh', 'cygwin']:
  1185. bash_startup()
  1186. else:
  1187. default_startup()
  1188. clear_screen()
  1189. clean_env()
  1190. clean_temp()
  1191. try_remove(lockfile)
  1192. # Save GISRC
  1193. s = readfile(gisrc)
  1194. writefile(gisrcrc, s)
  1195. cleanup()
  1196. # After this point no more grass modules may be called
  1197. done_message()