grass.py 44 KB

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