grass.py 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385
  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 tutorials
  409. 2) When working on your location, the following materials
  410. are extremely useful:
  411. - A topo map of your area
  412. - Current catalog of available computer maps
  413. 3) Check the GRASS webpages for feedback mailinglists and more:
  414. http://grass.osgeo.org
  415. http://www.grass-gis.org
  416. """ % grass_version
  417. sys.stderr.write(intro)
  418. sys.stderr.write("\n")
  419. sys.stderr.write(_("Hit RETURN to continue"))
  420. sys.stdin.readline()
  421. # for convenience, define pwd as GISDBASE:
  422. s = r"""GISDBASE: %s
  423. LOCATION_NAME: <UNKNOWN>
  424. MAPSET: <UNKNOWN>
  425. """ % os.getcwd()
  426. writefile(gisrc, s)
  427. def check_gui():
  428. global grass_gui, wxpython_base
  429. # Check if we are running X windows by checking the DISPLAY variable
  430. if os.getenv('DISPLAY') or windows or macosx:
  431. # Check if python is working properly
  432. if grass_gui == 'wxpython':
  433. nul = open(os.devnull, 'w')
  434. p = Popen([os.environ['GRASS_PYTHON']], stdin=subprocess.PIPE,
  435. stdout=nul, stderr=nul)
  436. nul.close()
  437. p.stdin.write("variable=True")
  438. p.stdin.close()
  439. p.wait()
  440. if p.returncode == 0:
  441. # Set the wxpython base directory
  442. wxpython_base = gfile("etc", "gui", "wxpython")
  443. else:
  444. # Python was not found - switch to text interface mode
  445. warning(_("The python command does not work as expected!\n"
  446. "Please check your GRASS_PYTHON environment variable.\n"
  447. "Use the -help option for details.\n"
  448. "Switching to text based interface mode.\n\n"
  449. "Hit RETURN to continue.\n"))
  450. sys.stdin.readline()
  451. grass_gui = 'text'
  452. else:
  453. # Display a message if a graphical interface was expected
  454. if grass_gui != 'text':
  455. # Set the interface mode to text
  456. warning(_("It appears that the X Windows system is not active.\n"
  457. "A graphical based user interface is not supported.\n"
  458. "Switching to text based interface mode.\n\n"
  459. "Hit RETURN to continue"""))
  460. sys.stdin.readline()
  461. grass_gui = 'text'
  462. # Save the user interface variable in the grassrc file - choose a temporary
  463. # file name that should not match another file
  464. if os.access(gisrc, os.F_OK):
  465. kv = read_gisrc()
  466. kv['GUI'] = grass_gui
  467. write_gisrc(kv)
  468. def non_interactive(arg, geofile=None):
  469. global gisdbase, location_name, mapset, location
  470. # Try non-interactive startup
  471. l = None
  472. if arg == '-':
  473. if location:
  474. l = location
  475. else:
  476. l = arg
  477. if l:
  478. if l == '.':
  479. l = os.getcwd()
  480. elif not os.path.isabs(l):
  481. l = os.path.abspath(l)
  482. l, mapset = os.path.split(l)
  483. if not mapset:
  484. l, mapset = os.path.split(l)
  485. l, location_name = os.path.split(l)
  486. gisdbase = l
  487. if gisdbase and location_name and mapset:
  488. location = os.path.join(gisdbase, location_name, mapset)
  489. # check if 'location_name' is a valid GRASS location
  490. if not os.access(os.path.join(location, "WIND"), os.R_OK):
  491. # 'location' is not a valid GRASS mapset, check if
  492. # 'location_name' is a valid GRASS location
  493. if not os.path.exists(os.path.join(gisdbase, location_name)):
  494. fatal(_("Location <%s> doesn't exist") % os.path.join(gisdbase, location_name))
  495. elif 'PERMANENT' not in os.listdir(os.path.join(gisdbase, location_name)) or \
  496. not os.path.isdir(os.path.join(gisdbase, location_name, 'PERMANENT')) or \
  497. not os.path.isfile((os.path.join(gisdbase, location_name, 'PERMANENT',
  498. 'DEFAULT_WIND'))):
  499. fatal(_("<%s> is not a valid GRASS location") % \
  500. os.path.join(gisdbase, location_name))
  501. else:
  502. # 'location_name' is a valid GRASS location, the user
  503. # wants to create mapset on the fly
  504. if create_new:
  505. if not os.access(os.path.join(os.path.join(gisdbase,
  506. location_name,
  507. "PERMANENT",
  508. "DEFAULT_WIND")),
  509. os.F_OK):
  510. # create new location
  511. gisdbase = os.path.join(gisdbase, location_name)
  512. location_name = mapset
  513. mapset = "PERMANENT"
  514. if os.access(os.path.join(os.path.join(gisdbase,
  515. location_name,
  516. "PERMANENT",
  517. "DEFAULT_WIND")),
  518. os.F_OK):
  519. fatal(_("Failed to create new location. The " \
  520. "location <%s> already exists." % location_name))
  521. if gfile('etc', 'python') not in sys.path:
  522. sys.path.append(gfile('etc', 'python'))
  523. from grass.script import core as grass
  524. try:
  525. if geofile and geofile.find('EPSG:') > -1:
  526. epsg = geofile.split(':', 1)[1]
  527. grass.create_location(gisdbase, location_name,
  528. epsg=epsg)
  529. else:
  530. grass.create_location(gisdbase, location_name,
  531. filename=geofile)
  532. except grass.ScriptError, e:
  533. fatal(e.value.strip('"').strip("'").replace('\\n',
  534. os.linesep))
  535. else:
  536. # create new mapset
  537. os.mkdir(location)
  538. # copy PERMANENT/DEFAULT_WIND to <mapset>/WIND
  539. s = readfile(os.path.join(gisdbase, location_name,
  540. "PERMANENT", "DEFAULT_WIND"))
  541. writefile(os.path.join(location, "WIND"), s)
  542. message(_("Missing WIND file fixed"))
  543. else:
  544. fatal(_("Mapset <%s> doesn't exist in GRASS location <%s>. "
  545. "A new mapset can be created by '-c' switch.") % (mapset, location_name))
  546. if os.access(gisrc, os.R_OK):
  547. kv = read_gisrc()
  548. else:
  549. kv = {}
  550. kv['GISDBASE'] = gisdbase
  551. kv['LOCATION_NAME'] = location_name
  552. kv['MAPSET'] = mapset
  553. write_gisrc(kv)
  554. else:
  555. fatal(_("GISDBASE, LOCATION_NAME and MAPSET variables not set properly"
  556. ".\nInteractive startup needed."))
  557. def set_data():
  558. # User selects LOCATION and MAPSET if not set
  559. if not location:
  560. # Check for text interface
  561. if grass_gui == 'text':
  562. pass
  563. # Check for GUI
  564. elif grass_gui == 'wxpython':
  565. gui_startup()
  566. else:
  567. # Shouldn't need this but you never know
  568. fatal(_("Invalid user interface specified - <%s>.\n"
  569. "Use the --help option to see valid interface names.") % grass_gui)
  570. def gui_startup():
  571. if grass_gui == 'wxpython':
  572. thetest = call([os.getenv('GRASS_PYTHON'),
  573. gfile(wxpython_base, "gis_set.py")])
  574. if thetest == 0:
  575. pass
  576. elif thetest == 1:
  577. # The startup script printed an error message so wait
  578. # for user to read it
  579. message(_("Error in GUI startup. If necessary, please "
  580. "report this error to the GRASS developers.\n"
  581. "Switching to text mode now.\n\n"
  582. "Hit RETURN to continue..."))
  583. sys.stdin.readline()
  584. os.execlp(cmd_name, "-text")
  585. sys.exit(1)
  586. elif thetest == 2:
  587. # User wants to exit from GRASS
  588. message(_("Received EXIT message from GUI.\nGRASS is not started. Bye."))
  589. sys.exit(0)
  590. else:
  591. fatal(_("Invalid return code from GUI startup script.\n"
  592. "Please advise GRASS developers of this error."))
  593. def load_gisrc():
  594. global gisdbase, location_name, mapset, location
  595. kv = read_gisrc()
  596. gisdbase = kv.get('GISDBASE')
  597. location_name = kv.get('LOCATION_NAME')
  598. mapset = kv.get('MAPSET')
  599. if not gisdbase or not location_name or not mapset:
  600. fatal(_("Error reading data path information from g.gisenv.\n"
  601. "GISDBASE=%(gisbase)s\n"
  602. "LOCATION_NAME=%(location)s\n"
  603. "MAPSET=%(mapset)s\n\n"
  604. "Check the <%s(file)> file." % \
  605. {'gisbase': gisdbase, 'location': location_name,
  606. 'mapset': mapset, 'file': gisrcrc}))
  607. location = os.path.join(gisdbase, location_name, mapset)
  608. # load environmental variables from grass_env_file
  609. def load_env():
  610. if not os.access(grass_env_file, os.R_OK):
  611. return
  612. for line in readfile(grass_env_file).split(os.linesep):
  613. try:
  614. k, v = map(lambda x: x.strip(), line.strip().split(' ', 1)[1].split('=', 1))
  615. except:
  616. continue
  617. os.environ[k] = v
  618. # Allow for mixed ISIS-GRASS Environment
  619. if os.getenv('ISISROOT'):
  620. isis = os.getenv('ISISROOT')
  621. os.environ['ISIS_LIB'] = isis + os.sep + "lib"
  622. os.environ['ISIS_3RDPARTY'] = isis + os.sep + "3rdParty" + os.sep + "lib"
  623. os.environ['QT_PLUGIN_PATH'] = isis + os.sep + "3rdParty" + os.sep + "plugins"
  624. #os.environ['ISIS3DATA'] = isis + "$ISIS3DATA"
  625. libpath = os.getenv('LD_LIBRARY_PATH', '')
  626. isislibpath = os.getenv('ISIS_LIB')
  627. isis3rdparty = os.getenv('ISIS_3RDPARTY')
  628. os.environ['LD_LIBRARY_PATH'] = libpath + os.pathsep + isislibpath + os.pathsep + isis3rdparty
  629. def set_language():
  630. import locale
  631. language = os.getenv('LANG')
  632. if not language:
  633. return
  634. language = language.split('.')[0] # Split off ignored .encoding part if present
  635. orig_language = language
  636. try:
  637. locale.setlocale(locale.LC_ALL, language)
  638. except locale.Error, e:
  639. if sys.platform != 'win32': # Don't try on Windows, it will probably not work
  640. # sys.stderr.write("Failed to set LC_ALL to %s (%s)\n" % (language, e))
  641. try:
  642. # Locale lang.encoding might be missing. Let's try
  643. # UTF-8 encoding before giving up as on Linux systems
  644. # lang.UTF-8 locales are more common than legacy
  645. # ISO-8859 ones.
  646. language = locale.normalize('%s.UTF-8' % (language))
  647. locale.setlocale(locale.LC_ALL, language)
  648. except locale.Error, e:
  649. # If we got so far, provided locale is not supported
  650. # on this system
  651. sys.stderr.write("Failed to set LC_ALL to %s (%s)\n" % (language, e))
  652. ### locale.getdefaultlocale() is probably related to gettext?
  653. # try:
  654. # default_locale = locale.getdefaultlocale()
  655. # except:
  656. # default_locale = None
  657. # if default_locale and default_locale[0]:
  658. # language = default_locale[0]
  659. # else:
  660. language = 'C'
  661. # Set up environment for subprocesses
  662. for lc in ('LC_CTYPE', 'LC_MESSAGES', 'LC_TIME', 'LC_COLLATE',
  663. 'LC_MONETARY', 'LC_PAPER', 'LC_NAME', 'LC_ADDRESS',
  664. 'LC_TELEPHONE', 'LC_MEASUREMENT', 'LC_IDENTIFICATION'):
  665. os.environ[lc] = language
  666. # Some code in GRASS might not like other decimal separators than .
  667. # Other potential sources for problems are: LC_TIME LC_CTYPE
  668. locale.setlocale(locale.LC_NUMERIC, 'C')
  669. os.environ['LC_NUMERIC'] = 'C'
  670. if os.getenv('LC_ALL'):
  671. del os.environ['LC_ALL'] # Remove LC_ALL to not override LC_NUMERIC
  672. # Even if setting locale has failed, let's set LANG in a hope,
  673. # that UI will use it GRASS texts will be in selected language,
  674. # system messages (i.e. OK, Cancel etc.) - in system default
  675. # language
  676. os.environ['LANGUAGE'] = orig_language
  677. os.environ['LANG'] = orig_language
  678. # Calling gettext.install twice seems to allow to see also
  679. # localized startup messages Black magic ;)
  680. gettext.install('grasslibs', os.path.join(gisbase, 'locale'), unicode=True)
  681. def check_lock():
  682. global lockfile
  683. if not os.path.exists(location):
  684. fatal(_("Path '%s' doesn't exist") % location)
  685. # Check for concurrent use
  686. lockfile = os.path.join(location, ".gislock")
  687. ret = call([gfile("etc", "lock"), lockfile, "%d" % os.getpid()])
  688. if ret == 0:
  689. msg = None
  690. elif ret == 2:
  691. msg = _("%(user)s is currently running GRASS in selected mapset (" \
  692. "file %(file)s found). Concurrent use not allowed." % {
  693. 'user': user, 'file': lockfile})
  694. else:
  695. msg = _("Unable to properly access '%s'.\n"
  696. "Please notify system personel.") % lockfile
  697. if msg:
  698. if grass_gui == "wxpython":
  699. thetest = call([os.getenv('GRASS_PYTHON'),
  700. os.path.join(wxpython_base, "gis_set_error.py"),
  701. msg])
  702. else:
  703. global remove_lockfile
  704. remove_lockfile = False
  705. fatal(msg)
  706. def make_fontcap():
  707. fc = os.getenv('GRASS_FONT_CAP')
  708. if fc and not os.access(fc, os.R_OK):
  709. message(_("Building user fontcap..."))
  710. call(["g.mkfontcap"])
  711. def check_shell():
  712. global sh, shellname, grass_env_file
  713. # cygwin has many problems with the shell setup
  714. # below, so i hardcoded everything here.
  715. if os.getenv('CYGWIN'):
  716. sh = "cygwin"
  717. shellname = "GNU Bash (Cygwin)"
  718. os.environ['SHELL'] = "/usr/bin/bash.exe"
  719. os.environ['OSTYPE'] = "cygwin"
  720. else:
  721. sh = os.path.basename(os.getenv('SHELL'))
  722. if windows and sh:
  723. sh = os.path.splitext(sh)[0]
  724. if sh == "ksh":
  725. shellname = "Korn Shell"
  726. elif sh == "csh":
  727. shellname = "C Shell"
  728. elif sh == "tcsh":
  729. shellname = "TC Shell"
  730. elif sh == "bash":
  731. shellname = "Bash Shell"
  732. elif sh == "sh":
  733. shellname = "Bourne Shell"
  734. elif sh == "zsh":
  735. shellname = "Z Shell"
  736. elif sh == "cmd":
  737. shellname = "Command Shell"
  738. else:
  739. shellname = "shell"
  740. if sh in ['csh', 'tcsh']:
  741. grass_env_file = os.path.join(grass_config_dir, 'cshrc')
  742. elif sh in ['bash', 'msh', 'cygwin', 'sh']:
  743. grass_env_file = os.path.join(grass_config_dir, 'bashrc')
  744. elif sh == 'zsh':
  745. grass_env_file = os.path.join(grass_config_dir, 'zshrc')
  746. elif sh == 'cmd':
  747. grass_env_file = os.path.join(grass_config_dir, 'env.bat')
  748. else:
  749. grass_env_file = os.path.join(grass_config_dir, 'bashrc')
  750. warning(_("Unsupported shell <%(sh)s>: %(env)s") % {'sh': sh,
  751. 'env': grass_env_file})
  752. # check for SHELL
  753. if not os.getenv('SHELL'):
  754. fatal(_("The SHELL variable is not set"))
  755. def check_batch_job():
  756. global batch_job
  757. # hack to process batch jobs:
  758. batch_job = os.getenv('GRASS_BATCH_JOB')
  759. if batch_job:
  760. # defined, but ...
  761. if not os.access(batch_job, os.F_OK):
  762. # wrong file
  763. fatal(_("Job file '%s' has been defined in "
  764. "the 'GRASS_BATCH_JOB' variable but not found. Exiting.\n\n"
  765. "Use 'unset GRASS_BATCH_JOB' to disable batch job processing.") % batch_job)
  766. elif not os.access(batch_job, os.X_OK):
  767. # right file, but ...
  768. fatal(_("Change file permission to 'executable' for '%s'") % batch_job)
  769. else:
  770. message(_("Executing '%s' ...") % batch_job)
  771. grass_gui = "text"
  772. shell = batch_job
  773. bj = Popen(shell, shell=True)
  774. bj.wait()
  775. message(_("Execution of '%s' finished.") % batch_job)
  776. def start_gui():
  777. # Start the chosen GUI but ignore text
  778. if grass_debug:
  779. message(_("GRASS GUI should be <%s>") % grass_gui)
  780. # Check for gui interface
  781. if grass_gui == "wxpython":
  782. Popen([os.getenv('GRASS_PYTHON'), gfile(wxpython_base, "wxgui.py")])
  783. def clear_screen():
  784. if windows:
  785. pass
  786. # TODO: uncomment when PDCurses works.
  787. # cls
  788. else:
  789. if not os.getenv('GRASS_BATCH_JOB') and not grass_debug:
  790. call(["tput", "clear"])
  791. def show_banner():
  792. sys.stderr.write(r"""
  793. __________ ___ __________ _______________
  794. / ____/ __ \/ | / ___/ ___/ / ____/ _/ ___/
  795. / / __/ /_/ / /| | \__ \\_ \ / / __ / / \__ \
  796. / /_/ / _, _/ ___ |___/ /__/ / / /_/ // / ___/ /
  797. \____/_/ |_/_/ |_/____/____/ \____/___//____/
  798. """)
  799. def say_hello():
  800. sys.stderr.write(_("Welcome to GRASS %s") % grass_version)
  801. def show_info():
  802. sys.stderr.write(
  803. r"""
  804. %-41shttp://grass.osgeo.org
  805. %-41s%s (%s)
  806. %-41sg.manual -i
  807. %-41sg.version -c
  808. """ % (_("GRASS homepage:"),
  809. _("This version running through:"),
  810. shellname, os.getenv('SHELL'),
  811. _("Help is available with the command:"),
  812. _("See the licence terms with:")))
  813. if grass_gui == 'wxpython':
  814. message("%-41sg.gui wxpython" % _("If required, restart the GUI with:"))
  815. else:
  816. message("%-41sg.gui %s" % (_("Start the GUI with:"), default_gui))
  817. message("%-41sexit" % _("When ready to quit enter:"))
  818. message("")
  819. def csh_startup():
  820. global exit_val
  821. userhome = os.getenv('HOME') # save original home
  822. home = location
  823. os.environ['HOME'] = home
  824. cshrc = os.path.join(home, ".cshrc")
  825. tcshrc = os.path.join(home, ".tcshrc")
  826. try_remove(cshrc)
  827. try_remove(tcshrc)
  828. f = open(cshrc, 'w')
  829. f.write("set home = %s\n" % userhome)
  830. f.write("set history = 3000 savehist = 3000 noclobber ignoreeof\n")
  831. f.write("set histfile = %s\n" % os.path.join(os.getenv('HOME'),
  832. ".history"))
  833. f.write("set prompt = '\\\n")
  834. f.write("Mapset <%s> in Location <%s> \\\n" % (mapset, location_name))
  835. f.write("GRASS %s > '\n" % grass_version)
  836. f.write("set BOGUS=``;unset BOGUS\n")
  837. path = os.path.join(userhome, ".grass.cshrc") # left for backward compatibility
  838. if os.access(path, os.R_OK):
  839. f.write(readfile(path) + '\n')
  840. if os.access(grass_env_file, os.R_OK):
  841. f.write(readfile(grass_env_file) + '\n')
  842. mail_re = re.compile(r"^ *set *mail *= *")
  843. for filename in [".cshrc", ".tcshrc", ".login"]:
  844. path = os.path.join(userhome, filename)
  845. if os.access(path, os.R_OK):
  846. s = readfile(path)
  847. lines = s.splitlines()
  848. for l in lines:
  849. if mail_re.match(l):
  850. f.write(l)
  851. path = os.getenv('PATH').split(':')
  852. f.write("set path = ( %s ) \n" % ' '.join(path))
  853. f.close()
  854. writefile(tcshrc, readfile(cshrc))
  855. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  856. os.environ['HOME'] = userhome
  857. def bash_startup():
  858. global exit_val
  859. # save command history in mapset dir and remember more
  860. os.environ['HISTFILE'] = os.path.join(location, ".bash_history")
  861. if not os.getenv('HISTSIZE') and not os.getenv('HISTFILESIZE'):
  862. os.environ['HISTSIZE'] = "3000"
  863. # instead of changing $HOME, start bash with: --rcfile "$LOCATION/.bashrc" ?
  864. # if so, must care be taken to explicity call .grass.bashrc et al for
  865. # non-interactive bash batch jobs?
  866. userhome = os.getenv('HOME') # save original home
  867. home = location # save .bashrc in $LOCATION
  868. os.environ['HOME'] = home
  869. bashrc = os.path.join(home, ".bashrc")
  870. try_remove(bashrc)
  871. f = open(bashrc, 'w')
  872. f.write("test -r ~/.alias && . ~/.alias\n")
  873. if os.getenv('ISISROOT'):
  874. f.write("PS1='ISIS-GRASS %s (%s):\w > '\n" % (grass_version, location_name))
  875. else:
  876. f.write("PS1='GRASS %s (%s):\w > '\n" % (grass_version, location_name))
  877. f.write("PROMPT_COMMAND=\"'%s'\"\n" % os.path.join(gisbase, 'etc',
  878. 'prompt.py'))
  879. # read environmental variables
  880. path = os.path.join(userhome, ".grass.bashrc") # left for backward compatibility
  881. if os.access(path, os.R_OK):
  882. f.write(readfile(path) + '\n')
  883. if os.access(grass_env_file, os.R_OK):
  884. f.write(readfile(grass_env_file) + '\n')
  885. f.write("export PATH=\"%s\"\n" % os.getenv('PATH'))
  886. f.write("export HOME=\"%s\"\n" % userhome) # restore user home path
  887. f.close()
  888. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  889. os.environ['HOME'] = userhome
  890. def default_startup():
  891. global exit_val
  892. if windows:
  893. os.environ['PS1'] = "GRASS %s> " % (grass_version)
  894. # "$ETC/run" doesn't work at all???
  895. exit_val = subprocess.call([os.getenv('SHELL')])
  896. cleanup_dir(os.path.join(location, ".tmp")) # remove GUI session files from .tmp
  897. else:
  898. os.environ['PS1'] = "GRASS %s (%s):\w > " % (grass_version, location_name)
  899. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  900. if exit_val != 0:
  901. fatal(_("Failed to start shell '%s'") % os.getenv('SHELL'))
  902. def done_message():
  903. if batch_job and os.access(batch_job, os.X_OK):
  904. message(_("Batch job '%s' (defined in GRASS_BATCH_JOB variable) was executed.") % batch_job)
  905. message(_("Goodbye from GRASS GIS"))
  906. sys.exit(exit_val)
  907. else:
  908. message(_("Done."))
  909. message("")
  910. message(_("Goodbye from GRASS GIS"))
  911. message("")
  912. def clean_temp():
  913. message(_("Cleaning up temporary files..."))
  914. nul = open(os.devnull, 'w')
  915. call([gfile("etc", "clean_temp")], stdout=nul, stderr=nul)
  916. nul.close()
  917. def grep(string,list):
  918. expr = re.compile(string)
  919. return [elem for elem in list if expr.match(elem)]
  920. def print_params():
  921. plat = gfile(gisbase, 'include', 'Make', 'Platform.make')
  922. fileplat = open(plat)
  923. linesplat = fileplat.readlines()
  924. fileplat.close()
  925. params = sys.argv[2:]
  926. if not params:
  927. params = ['arch', 'build', 'compiler', 'path', 'revision']
  928. for arg in params:
  929. if arg == 'path':
  930. sys.stdout.write("%s\n" % gisbase)
  931. elif arg == 'arch':
  932. val = grep('ARCH',linesplat)
  933. sys.stdout.write("%s\n" % val[0].split('=')[1].strip())
  934. elif arg == 'build':
  935. build = os.path.join(gisbase,'include','grass','confparms.h')
  936. filebuild = open(build)
  937. val = filebuild.readline()
  938. filebuild.close()
  939. sys.stdout.write("%s\n" % val.strip().strip('"').strip())
  940. elif arg == 'compiler':
  941. val = grep('CC',linesplat)
  942. sys.stdout.write("%s\n" % val[0].split('=')[1].strip())
  943. elif arg == 'revision':
  944. rev = os.path.join(gisbase,'include','grass','gis.h')
  945. filerev = open(rev)
  946. linesrev = filerev.readlines()
  947. val = grep('#define GIS_H_VERSION', linesrev)
  948. filerev.close()
  949. sys.stdout.write("%s\n" % val[0].split(':')[1].rstrip('$"\n').strip())
  950. else:
  951. message(_("Parameter <%s> not supported") % arg)
  952. def get_username():
  953. global user
  954. if windows:
  955. user = os.getenv('USERNAME')
  956. if not user:
  957. user = "user_name"
  958. else:
  959. user = os.getenv('USER')
  960. if not user:
  961. user = os.getenv('LOGNAME')
  962. if not user:
  963. try:
  964. p = Popen(['whoami'], stdout = subprocess.PIPE)
  965. s = p.stdout.read()
  966. p.wait()
  967. user = s.strip()
  968. except:
  969. pass
  970. if not user:
  971. user = "user_%d" % os.getuid()
  972. def parse_cmdline():
  973. global args, grass_gui, create_new
  974. args = []
  975. for i in sys.argv[1:]:
  976. # Check if the user asked for the version
  977. if i in ["-v", "--version"]:
  978. message('\n' + readfile(gfile("etc", "license")))
  979. sys.exit()
  980. # Check if the user asked for help
  981. elif i in ["help", "-h", "-help", "--help"]:
  982. help_message()
  983. sys.exit()
  984. # Check if the -text flag was given
  985. elif i in ["-text", "--text"]:
  986. grass_gui = 'text'
  987. # Check if the -gui flag was given
  988. elif i in ["-gui", "--gui"]:
  989. grass_gui = default_gui
  990. # Check if the -wxpython flag was given
  991. elif i in ["-wxpython", "-wx", "--wxpython", "--wx"]:
  992. grass_gui = 'wxpython'
  993. # Check if the user wants to create a new mapset
  994. elif i == "-c":
  995. create_new = True
  996. elif i == "--config":
  997. print_params()
  998. sys.exit()
  999. else:
  1000. args.append(i)
  1001. ### MAIN script starts here
  1002. # Get the system name
  1003. windows = sys.platform == 'win32'
  1004. cygwin = "cygwin" in sys.platform
  1005. macosx = "darwin" in sys.platform
  1006. # Set GISBASE
  1007. os.environ['GISBASE'] = gisbase
  1008. # set HOME
  1009. if windows and not os.getenv('HOME'):
  1010. os.environ['HOME'] = os.path.join(os.getenv('HOMEDRIVE'),
  1011. os.getenv('HOMEPATH'))
  1012. # set SHELL
  1013. if windows:
  1014. if os.getenv('GRASS_SH'):
  1015. os.environ['SHELL'] = os.getenv('GRASS_SH')
  1016. if not os.getenv('SHELL'):
  1017. os.environ['SHELL'] = os.getenv('COMSPEC', 'cmd.exe')
  1018. atexit.register(cleanup)
  1019. # Set default GUI
  1020. default_gui = "wxpython"
  1021. # the following is only meant to be an internal variable for debugging this
  1022. # script. use 'g.gisenv set="DEBUG=[0-5]"' to turn GRASS debug mode on properly
  1023. grass_debug = os.getenv('GRASS_DEBUG')
  1024. # Set GRASS version number for R interface etc (must be an env_var for MS-Windows)
  1025. os.environ['GRASS_VERSION'] = grass_version
  1026. # Set the GIS_LOCK variable to current process id
  1027. gis_lock = str(os.getpid())
  1028. os.environ['GIS_LOCK'] = gis_lock
  1029. # Set the global grassrc file
  1030. batch_job = os.getenv('GRASS_BATCH_JOB')
  1031. if batch_job:
  1032. gisrcrc = os.path.join(grass_config_dir, "rc.%s" % platform.node())
  1033. if not os.access(gisrcrc, os.R_OK):
  1034. gisrcrc = os.path.join(grass_config_dir, "rc")
  1035. else:
  1036. gisrcrc = os.path.join(grass_config_dir, "rc")
  1037. # Set the username and working directory
  1038. get_username()
  1039. # Parse the command-line options
  1040. parse_cmdline()
  1041. # Create the temporary directory and session grassrc file
  1042. create_tmp()
  1043. # Create the session grassrc file
  1044. create_gisrc()
  1045. # Set shell (needs to be called before load_env())
  1046. check_shell()
  1047. # Load environmental variables from the file
  1048. load_env()
  1049. # Ensure GUI is set
  1050. read_gui()
  1051. # Set PATH, PYTHONPATH
  1052. set_paths()
  1053. # Set LD_LIBRARY_PATH (etc) to find GRASS shared libraries
  1054. path_prepend(gfile("lib"), ld_library_path_var)
  1055. # Set GRASS_PAGER, GRASS_PYTHON, GRASS_GNUPLOT, GRASS_PROJSHARE
  1056. set_defaults()
  1057. # Set GRASS_HTML_BROWSER
  1058. set_browser()
  1059. #predefine monitor size for certain architectures
  1060. if os.getenv('HOSTTYPE') == 'arm':
  1061. # small monitor on ARM (iPAQ, zaurus... etc)
  1062. os.environ['GRASS_HEIGHT'] = "320"
  1063. os.environ['GRASS_WIDTH'] = "240"
  1064. # First time user - GISRC is defined in the GRASS script
  1065. if not os.access(gisrc, os.F_OK):
  1066. if grass_gui == 'text' and len(args) == 0:
  1067. fatal(_("Unable to start GRASS. You can:\n"
  1068. " - Launch GRASS with '-gui' switch (`grass70 -gui`)\n"
  1069. " - Create manually GISRC file (%s)\n"
  1070. " - Launch GRASS with path to "
  1071. "the location/mapset as an argument (`grass70 /path/to/location/mapset`)") % gisrcrc)
  1072. grass_intro()
  1073. else:
  1074. clean_temp()
  1075. message(_("Starting GRASS GIS..."))
  1076. # Check that the GUI works
  1077. check_gui()
  1078. # Parsing argument to get LOCATION
  1079. if not args:
  1080. # Try interactive startup
  1081. location = None
  1082. else:
  1083. if create_new:
  1084. if len(args) > 1:
  1085. non_interactive(args[1], args[0])
  1086. else:
  1087. non_interactive(args[0])
  1088. else:
  1089. non_interactive(args[0])
  1090. # Set language
  1091. set_language()
  1092. # User selects LOCATION and MAPSET if not set
  1093. set_data()
  1094. # Set GISDBASE, LOCATION_NAME, MAPSET, LOCATION from $GISRC
  1095. load_gisrc()
  1096. # Check .gislock file
  1097. check_lock()
  1098. # build user fontcap if specified but not present
  1099. make_fontcap()
  1100. # predefine default driver if DB connection not defined
  1101. # is this really needed?? Modules should call this when/if required.
  1102. if not os.access(os.path.join(location, "VAR"), os.F_OK):
  1103. call(['db.connect', '-c', '--quiet'])
  1104. check_batch_job()
  1105. if not batch_job:
  1106. start_gui()
  1107. clear_screen()
  1108. # Display the version and license info
  1109. if batch_job:
  1110. say_hello()
  1111. grass_gui = 'text'
  1112. clear_screen()
  1113. clean_temp()
  1114. try_remove(lockfile)
  1115. sys.exit(0)
  1116. else:
  1117. show_banner()
  1118. say_hello()
  1119. show_info()
  1120. if grass_gui == "wxpython":
  1121. message(_("Launching <%s> GUI in the background, please wait...") % grass_gui)
  1122. if sh in ['csh', 'tcsh']:
  1123. csh_startup()
  1124. elif sh in ['bash', 'msh', 'cygwin']:
  1125. bash_startup()
  1126. else:
  1127. default_startup()
  1128. clear_screen()
  1129. clean_env()
  1130. clean_temp()
  1131. try_remove(lockfile)
  1132. # Save GISRC
  1133. s = readfile(gisrc)
  1134. if not os.path.exists(grass_config_dir):
  1135. os.mkdir(grass_config_dir)
  1136. writefile(gisrcrc, s)
  1137. cleanup()
  1138. # After this point no more grass modules may be called
  1139. done_message()