grass.py 47 KB

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