grass.py 43 KB

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