grass.py 45 KB

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