grass.py 44 KB

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