grass.py 46 KB

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