grass.py 43 KB

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