grass.py 43 KB

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