gis_set.py 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  1. """!
  2. @package gis_set
  3. GRASS start-up screen.
  4. Initialization module for wxPython GRASS GUI.
  5. Location/mapset management (selection, creation, etc.).
  6. Classes:
  7. - gis_set::GRASSStartup
  8. - gis_set::GListBox
  9. - gis_set::StartUp
  10. (C) 2006-2013 by the GRASS Development Team
  11. This program is free software under the GNU General Public License
  12. (>=v2). Read the file COPYING that comes with GRASS for details.
  13. @author Michael Barton and Jachym Cepicky (original author)
  14. @author Martin Landa <landa.martin gmail.com> (various updates)
  15. """
  16. import os
  17. import sys
  18. import shutil
  19. import copy
  20. import platform
  21. import codecs
  22. import getpass
  23. ### i18N
  24. import gettext
  25. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  26. if __name__ == "__main__":
  27. sys.path.append(os.path.join(os.getenv('GISBASE'), 'etc', 'gui', 'wxpython'))
  28. from core import globalvar
  29. import wx
  30. import wx.lib.mixins.listctrl as listmix
  31. import wx.lib.scrolledpanel as scrolled
  32. from grass.script import core as grass
  33. from gui_core.ghelp import HelpFrame
  34. from core.gcmd import GMessage, GError, DecodeString, RunCommand, GWarning
  35. from core.utils import GetListOfLocations, GetListOfMapsets
  36. from location_wizard.dialogs import RegionDef
  37. from gui_core.dialogs import TextEntryDialog
  38. from gui_core.widgets import GenericValidator
  39. sys.stderr = codecs.getwriter('utf8')(sys.stderr)
  40. class GRASSStartup(wx.Frame):
  41. """!GRASS start-up screen"""
  42. def __init__(self, parent = None, id = wx.ID_ANY, style = wx.DEFAULT_FRAME_STYLE):
  43. #
  44. # GRASS variables
  45. #
  46. self.gisbase = os.getenv("GISBASE")
  47. self.grassrc = self._readGisRC()
  48. self.gisdbase = self.GetRCValue("GISDBASE")
  49. #
  50. # list of locations/mapsets
  51. #
  52. self.listOfLocations = []
  53. self.listOfMapsets = []
  54. self.listOfMapsetsSelectable = []
  55. wx.Frame.__init__(self, parent = parent, id = id, style = style)
  56. self.locale = wx.Locale(language = wx.LANGUAGE_DEFAULT)
  57. self.panel = scrolled.ScrolledPanel(parent = self, id = wx.ID_ANY)
  58. # i18N
  59. import gettext
  60. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  61. #
  62. # graphical elements
  63. #
  64. # image
  65. try:
  66. name = os.path.join(globalvar.ETCDIR, "gui", "images", "startup_banner.png")
  67. self.hbitmap = wx.StaticBitmap(self.panel, wx.ID_ANY,
  68. wx.Bitmap(name = name,
  69. type = wx.BITMAP_TYPE_PNG))
  70. except:
  71. self.hbitmap = wx.StaticBitmap(self.panel, wx.ID_ANY, wx.EmptyBitmap(530,150))
  72. # labels
  73. ### crashes when LOCATION doesn't exist
  74. versionFile = open(os.path.join(globalvar.ETCDIR, "VERSIONNUMBER"))
  75. grassVersion = versionFile.readline().split(' ')[0].rstrip('\n')
  76. versionFile.close()
  77. self.select_box = wx.StaticBox (parent = self.panel, id = wx.ID_ANY,
  78. label = " %s " % _("Choose project location and mapset"))
  79. self.manage_box = wx.StaticBox (parent = self.panel, id = wx.ID_ANY,
  80. label = " %s " % _("Manage"))
  81. self.lwelcome = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  82. label = _("Welcome to GRASS GIS %s\n"
  83. "The world's leading open source GIS") % grassVersion,
  84. style = wx.ALIGN_CENTRE)
  85. self.ltitle = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  86. label = _("Select an existing project location and mapset\n"
  87. "or define a new location"),
  88. style = wx.ALIGN_CENTRE)
  89. self.ldbase = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  90. label = _("GIS Data Directory:"))
  91. self.llocation = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  92. label = _("Project location\n(projection/coordinate system)"),
  93. style = wx.ALIGN_CENTRE)
  94. self.lmapset = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  95. label = _("Accessible mapsets\n(directories of GIS files)"),
  96. style = wx.ALIGN_CENTRE)
  97. self.lcreate = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  98. label = _("Create new mapset\nin selected location"),
  99. style = wx.ALIGN_CENTRE)
  100. self.ldefine = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  101. label = _("Define new location"),
  102. style = wx.ALIGN_CENTRE)
  103. self.lmanageloc = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  104. label = _("Rename/delete selected\nmapset or location"),
  105. style = wx.ALIGN_CENTRE)
  106. # buttons
  107. self.bstart = wx.Button(parent = self.panel, id = wx.ID_ANY,
  108. label = _("Start &GRASS"))
  109. self.bstart.SetDefault()
  110. self.bexit = wx.Button(parent = self.panel, id = wx.ID_EXIT)
  111. self.bstart.SetMinSize((180, self.bexit.GetSize()[1]))
  112. self.bhelp = wx.Button(parent = self.panel, id = wx.ID_HELP)
  113. self.bbrowse = wx.Button(parent = self.panel, id = wx.ID_ANY,
  114. label = _("&Browse"))
  115. self.bmapset = wx.Button(parent = self.panel, id = wx.ID_ANY,
  116. label = _("&Create mapset"))
  117. self.bwizard = wx.Button(parent = self.panel, id = wx.ID_ANY,
  118. label = _("&Location wizard"))
  119. self.bwizard.SetToolTipString(_("Start location wizard."
  120. " After location is created successfully,"
  121. " GRASS session is started."))
  122. self.manageloc = wx.Choice(parent = self.panel, id = wx.ID_ANY,
  123. choices = [_('Rename mapset'), _('Rename location'),
  124. _('Delete mapset'), _('Delete location')])
  125. self.manageloc.SetSelection(0)
  126. # textinputs
  127. self.tgisdbase = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY, value = "", size = (300, -1),
  128. style = wx.TE_PROCESS_ENTER)
  129. # Locations
  130. self.lblocations = GListBox(parent = self.panel,
  131. id = wx.ID_ANY, size = (180, 200),
  132. choices = self.listOfLocations)
  133. self.lblocations.SetColumnWidth(0, 180)
  134. # TODO: sort; but keep PERMANENT on top of list
  135. # Mapsets
  136. self.lbmapsets = GListBox(parent = self.panel,
  137. id = wx.ID_ANY, size = (180, 200),
  138. choices = self.listOfMapsets)
  139. self.lbmapsets.SetColumnWidth(0, 180)
  140. # layout & properties
  141. self._set_properties()
  142. self._do_layout()
  143. # events
  144. self.bbrowse.Bind(wx.EVT_BUTTON, self.OnBrowse)
  145. self.bstart.Bind(wx.EVT_BUTTON, self.OnStart)
  146. self.bexit.Bind(wx.EVT_BUTTON, self.OnExit)
  147. self.bhelp.Bind(wx.EVT_BUTTON, self.OnHelp)
  148. self.bmapset.Bind(wx.EVT_BUTTON, self.OnCreateMapset)
  149. self.bwizard.Bind(wx.EVT_BUTTON, self.OnWizard)
  150. self.manageloc.Bind(wx.EVT_CHOICE, self.OnManageLoc)
  151. self.lblocations.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectLocation)
  152. self.lbmapsets.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectMapset)
  153. self.lbmapsets.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnStart)
  154. self.tgisdbase.Bind(wx.EVT_TEXT_ENTER, self.OnSetDatabase)
  155. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  156. def _set_properties(self):
  157. """!Set frame properties"""
  158. self.SetTitle(_("Welcome to GRASS GIS"))
  159. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, "grass.ico"),
  160. wx.BITMAP_TYPE_ICO))
  161. self.lwelcome.SetForegroundColour(wx.Colour(35, 142, 35))
  162. self.lwelcome.SetFont(wx.Font(13, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
  163. self.bstart.SetForegroundColour(wx.Colour(35, 142, 35))
  164. self.bstart.SetToolTipString(_("Enter GRASS session"))
  165. self.bstart.Enable(False)
  166. self.bmapset.Enable(False)
  167. self.manageloc.Enable(False)
  168. # set database
  169. if not self.gisdbase:
  170. # sets an initial path for gisdbase if nothing in GISRC
  171. if os.path.isdir(os.getenv("HOME")):
  172. self.gisdbase = os.getenv("HOME")
  173. else:
  174. self.gisdbase = os.getcwd()
  175. try:
  176. self.tgisdbase.SetValue(self.gisdbase)
  177. except UnicodeDecodeError:
  178. wx.MessageBox(parent = self, caption = _("Error"),
  179. message = _("Unable to set GRASS database. "
  180. "Check your locale settings."),
  181. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  182. self.OnSetDatabase(None)
  183. location = self.GetRCValue("LOCATION_NAME")
  184. if location == "<UNKNOWN>":
  185. return
  186. if not os.path.isdir(os.path.join(self.gisdbase, location)):
  187. location = None
  188. # list of locations
  189. self.UpdateLocations(self.gisdbase)
  190. try:
  191. self.lblocations.SetSelection(self.listOfLocations.index(location),
  192. force = True)
  193. self.lblocations.EnsureVisible(self.listOfLocations.index(location))
  194. except ValueError:
  195. sys.stderr.write(_("ERROR: Location <%s> not found\n") % self.GetRCValue("LOCATION_NAME"))
  196. if len(self.listOfLocations) > 0:
  197. self.lblocations.SetSelection(0, force = True)
  198. self.lblocations.EnsureVisible(0)
  199. location = self.listOfLocations[0]
  200. else:
  201. return
  202. # list of mapsets
  203. self.UpdateMapsets(os.path.join(self.gisdbase, location))
  204. mapset = self.GetRCValue("MAPSET")
  205. if mapset:
  206. try:
  207. self.lbmapsets.SetSelection(self.listOfMapsets.index(mapset),
  208. force = True)
  209. self.lbmapsets.EnsureVisible(self.listOfMapsets.index(mapset))
  210. except ValueError:
  211. sys.stderr.write(_("ERROR: Mapset <%s> not found\n") % mapset)
  212. self.lbmapsets.SetSelection(0, force = True)
  213. self.lbmapsets.EnsureVisible(0)
  214. def _do_layout(self):
  215. sizer = wx.BoxSizer(wx.VERTICAL)
  216. dbase_sizer = wx.BoxSizer(wx.HORIZONTAL)
  217. location_sizer = wx.BoxSizer(wx.HORIZONTAL)
  218. select_boxsizer = wx.StaticBoxSizer(self.select_box, wx.VERTICAL)
  219. select_sizer = wx.FlexGridSizer(rows = 2, cols = 2, vgap = 4, hgap = 4)
  220. select_sizer.AddGrowableRow(1)
  221. select_sizer.AddGrowableCol(0)
  222. select_sizer.AddGrowableCol(1)
  223. manage_sizer = wx.StaticBoxSizer(self.manage_box, wx.VERTICAL)
  224. btns_sizer = wx.BoxSizer(wx.HORIZONTAL)
  225. # gis data directory
  226. dbase_sizer.Add(item = self.ldbase, proportion = 0,
  227. flag = wx.ALIGN_CENTER_VERTICAL |
  228. wx.ALIGN_CENTER_HORIZONTAL | wx.ALL,
  229. border = 3)
  230. dbase_sizer.Add(item = self.tgisdbase, proportion = 1,
  231. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  232. border = 3)
  233. dbase_sizer.Add(item = self.bbrowse, proportion = 0,
  234. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  235. border = 3)
  236. # select sizer
  237. select_sizer.Add(item = self.llocation, proportion = 0,
  238. flag = wx.ALIGN_CENTER_HORIZONTAL | wx.ALL,
  239. border = 3)
  240. select_sizer.Add(item = self.lmapset, proportion = 0,
  241. flag = wx.ALIGN_CENTER_HORIZONTAL | wx.ALL,
  242. border = 3)
  243. select_sizer.Add(item = self.lblocations, proportion = 1,
  244. flag = wx.EXPAND)
  245. select_sizer.Add(item = self.lbmapsets, proportion = 1,
  246. flag = wx.EXPAND)
  247. select_boxsizer.Add(item = select_sizer, proportion = 1,
  248. flag = wx.EXPAND)
  249. # define new location and mapset
  250. manage_sizer.Add(item = self.ldefine, proportion = 0,
  251. flag = wx.ALIGN_CENTER_HORIZONTAL | wx.ALL,
  252. border = 3)
  253. manage_sizer.Add(item = self.bwizard, proportion = 0,
  254. flag = wx.ALIGN_CENTER_HORIZONTAL | wx.BOTTOM,
  255. border = 5)
  256. manage_sizer.Add(item = self.lcreate, proportion = 0,
  257. flag = wx.ALIGN_CENTER_HORIZONTAL | wx.ALL,
  258. border = 3)
  259. manage_sizer.Add(item = self.bmapset, proportion = 0,
  260. flag = wx.ALIGN_CENTER_HORIZONTAL | wx.BOTTOM,
  261. border = 5)
  262. manage_sizer.Add(item = self.lmanageloc, proportion = 0,
  263. flag = wx.ALIGN_CENTER_HORIZONTAL | wx.ALL,
  264. border = 3)
  265. manage_sizer.Add(item = self.manageloc, proportion = 0,
  266. flag = wx.ALIGN_CENTER_HORIZONTAL | wx.BOTTOM,
  267. border = 5)
  268. # location sizer
  269. location_sizer.Add(item = select_boxsizer, proportion = 1,
  270. flag = wx.LEFT | wx.RIGHT | wx.EXPAND,
  271. border = 3)
  272. location_sizer.Add(item = manage_sizer, proportion = 0,
  273. flag = wx.RIGHT | wx.EXPAND,
  274. border = 3)
  275. # buttons
  276. btns_sizer.Add(item = self.bstart, proportion = 0,
  277. flag = wx.ALIGN_CENTER_HORIZONTAL |
  278. wx.ALIGN_CENTER_VERTICAL |
  279. wx.ALL,
  280. border = 5)
  281. btns_sizer.Add(item = self.bexit, proportion = 0,
  282. flag = wx.ALIGN_CENTER_HORIZONTAL |
  283. wx.ALIGN_CENTER_VERTICAL |
  284. wx.ALL,
  285. border = 5)
  286. btns_sizer.Add(item = self.bhelp, proportion = 0,
  287. flag = wx.ALIGN_CENTER_HORIZONTAL |
  288. wx.ALIGN_CENTER_VERTICAL |
  289. wx.ALL,
  290. border = 5)
  291. # main sizer
  292. sizer.Add(item = self.hbitmap,
  293. proportion = 0,
  294. flag = wx.ALIGN_CENTER_VERTICAL |
  295. wx.ALIGN_CENTER_HORIZONTAL |
  296. wx.ALL,
  297. border = 3) # image
  298. sizer.Add(item = self.lwelcome, # welcome message
  299. proportion = 0,
  300. flag = wx.ALIGN_CENTER_VERTICAL |
  301. wx.ALIGN_CENTER_HORIZONTAL |
  302. wx.BOTTOM,
  303. border = 5)
  304. sizer.Add(item = self.ltitle, # title
  305. proportion = 0,
  306. flag = wx.ALIGN_CENTER_VERTICAL |
  307. wx.ALIGN_CENTER_HORIZONTAL)
  308. sizer.Add(item = dbase_sizer, proportion = 0,
  309. flag = wx.ALIGN_CENTER_HORIZONTAL |
  310. wx.RIGHT | wx.LEFT | wx.EXPAND,
  311. border = 20) # GISDBASE setting
  312. sizer.Add(item = location_sizer, proportion = 1,
  313. flag = wx.RIGHT | wx.LEFT | wx.EXPAND,
  314. border = 1)
  315. sizer.Add(item = btns_sizer, proportion = 0,
  316. flag = wx.ALIGN_CENTER_VERTICAL |
  317. wx.ALIGN_CENTER_HORIZONTAL |
  318. wx.RIGHT | wx.LEFT,
  319. border = 1)
  320. self.panel.SetAutoLayout(True)
  321. self.panel.SetSizer(sizer)
  322. sizer.Fit(self.panel)
  323. sizer.SetSizeHints(self)
  324. self.Layout()
  325. def _readGisRC(self):
  326. """!Read variables from $HOME/.grass7/rc file
  327. """
  328. grassrc = {}
  329. gisrc = os.getenv("GISRC")
  330. if gisrc and os.path.isfile(gisrc):
  331. try:
  332. rc = open(gisrc, "r")
  333. for line in rc.readlines():
  334. try:
  335. key, val = line.split(":", 1)
  336. except ValueError, e:
  337. sys.stderr.write(_('Invalid line in GISRC file (%s):%s\n' % \
  338. (e, line)))
  339. grassrc[key.strip()] = DecodeString(val.strip())
  340. finally:
  341. rc.close()
  342. return grassrc
  343. def GetRCValue(self, value):
  344. """!Return GRASS variable (read from GISRC)
  345. """
  346. if self.grassrc.has_key(value):
  347. return self.grassrc[value]
  348. else:
  349. return None
  350. def OnWizard(self, event):
  351. """!Location wizard started"""
  352. from location_wizard.wizard import LocationWizard
  353. gWizard = LocationWizard(parent = self,
  354. grassdatabase = self.tgisdbase.GetValue())
  355. if gWizard.location != None:
  356. self.tgisdbase.SetValue(gWizard.grassdatabase)
  357. self.OnSetDatabase(None)
  358. self.UpdateMapsets(os.path.join(self.gisdbase, gWizard.location))
  359. self.lblocations.SetSelection(self.listOfLocations.index(gWizard.location))
  360. self.lbmapsets.SetSelection(0)
  361. self.SetLocation(self.gisdbase, gWizard.location, 'PERMANENT')
  362. if gWizard.georeffile:
  363. message = _("Do you want to import <%(name)s> to the newly created location? "
  364. "The location's default region will be set from this imported "
  365. "map.") % {'name': gWizard.georeffile}
  366. dlg = wx.MessageDialog(parent = self,
  367. message = message,
  368. caption = _("Import data?"),
  369. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  370. dlg.CenterOnScreen()
  371. if dlg.ShowModal() == wx.ID_YES:
  372. self.ImportFile(gWizard.georeffile)
  373. else:
  374. self.SetDefaultRegion(location = gWizard.location)
  375. dlg.Destroy()
  376. else:
  377. self.SetDefaultRegion(location = gWizard.location)
  378. dlg = TextEntryDialog(parent=self,
  379. message=_("Do you want to create new mapset?"),
  380. caption=_("Create new mapset"),
  381. defaultValue=self._getDefaultMapsetName(),
  382. validator=GenericValidator(grass.legal_name, self._nameValidationFailed),
  383. style=wx.OK | wx.CANCEL | wx.HELP)
  384. help = dlg.FindWindowById(wx.ID_HELP)
  385. help.Bind(wx.EVT_BUTTON, self.OnHelp)
  386. if dlg.ShowModal() == wx.ID_OK:
  387. mapsetName = dlg.GetValue()
  388. self.CreateNewMapset(mapsetName)
  389. def SetDefaultRegion(self, location):
  390. """!Asks to set default region."""
  391. caption = _("Location <%s> created") % location
  392. message = _("Do you want to set the default "
  393. "region extents and resolution now?")
  394. dlg = wx.MessageDialog(parent = self,
  395. message = "%(caption)s.\n\n%(extent)s" % ({'caption': caption,
  396. 'extent': message}),
  397. caption = caption,
  398. style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  399. dlg.CenterOnScreen()
  400. if dlg.ShowModal() == wx.ID_YES:
  401. dlg.Destroy()
  402. defineRegion = RegionDef(self, location = location)
  403. defineRegion.CenterOnScreen()
  404. defineRegion.ShowModal()
  405. defineRegion.Destroy()
  406. else:
  407. dlg.Destroy()
  408. def ImportFile(self, filePath):
  409. """!Tries to import file as vector or raster.
  410. If successfull sets default region from imported map.
  411. """
  412. mapName = os.path.splitext(os.path.basename(filePath))[0]
  413. vectors = RunCommand('v.in.ogr', dsn = filePath, flags = 'l',
  414. read = True)
  415. wx.BeginBusyCursor()
  416. wx.Yield()
  417. if mapName in vectors:
  418. # vector detected
  419. returncode, error = RunCommand('v.in.ogr', dsn = filePath, output = mapName,
  420. getErrorMsg = True)
  421. else:
  422. returncode, error = RunCommand('r.in.gdal', input = filePath, output = mapName,
  423. getErrorMsg = True)
  424. wx.EndBusyCursor()
  425. if returncode != 0:
  426. GError(parent = self,
  427. message = _("Import of <%(name)s> failed.\n"
  428. "Reason: %(msg)s") % ({'name': filePath, 'msg': error}))
  429. else:
  430. GMessage(message = _("Data file <%(name)s> imported successfully.") % {'name': filePath},
  431. parent = self)
  432. if not grass.find_file(element = 'cell', name = mapName)['fullname'] and \
  433. not grass.find_file(element = 'vector', name = mapName)['fullname']:
  434. GError(parent = self,
  435. message = _("Map <%s> not found.") % mapName)
  436. else:
  437. if mapName in vectors:
  438. args = {'vect' : mapName}
  439. else:
  440. args = {'rast' : mapName}
  441. RunCommand('g.region', flags = 's', parent = self, **args)
  442. def OnManageLoc(self, event):
  443. """!Location management choice control handler
  444. """
  445. sel = event.GetSelection()
  446. if sel == 0:
  447. self.RenameMapset()
  448. elif sel == 1:
  449. self.RenameLocation()
  450. elif sel == 2:
  451. self.DeleteMapset()
  452. elif sel == 3:
  453. self.DeleteLocation()
  454. event.Skip()
  455. def RenameMapset(self):
  456. """!Rename selected mapset
  457. """
  458. location = self.listOfLocations[self.lblocations.GetSelection()]
  459. mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
  460. if mapset == 'PERMANENT':
  461. GMessage(parent = self,
  462. message = _('Mapset <PERMANENT> is required for valid GRASS location.\n\n'
  463. 'This mapset cannot be renamed.'))
  464. return
  465. dlg = TextEntryDialog(parent = self,
  466. message = _('Current name: %s\n\nEnter new name:') % mapset,
  467. caption = _('Rename selected mapset'),
  468. validator = GenericValidator(grass.legal_name, self._nameValidationFailed))
  469. if dlg.ShowModal() == wx.ID_OK:
  470. newmapset = dlg.GetValue()
  471. if newmapset == mapset:
  472. dlg.Destroy()
  473. return
  474. if newmapset in self.listOfMapsets:
  475. wx.MessageBox(parent = self,
  476. caption = _('Message'),
  477. message = _('Unable to rename mapset.\n\n'
  478. 'Mapset <%s> already exists in location.') % newmapset,
  479. style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  480. else:
  481. try:
  482. os.rename(os.path.join(self.gisdbase, location, mapset),
  483. os.path.join(self.gisdbase, location, newmapset))
  484. self.OnSelectLocation(None)
  485. self.lbmapsets.SetSelection(self.listOfMapsets.index(newmapset))
  486. except StandardError, e:
  487. wx.MessageBox(parent = self,
  488. caption = _('Error'),
  489. message = _('Unable to rename mapset.\n\n%s') % e,
  490. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  491. dlg.Destroy()
  492. def RenameLocation(self):
  493. """!Rename selected location
  494. """
  495. location = self.listOfLocations[self.lblocations.GetSelection()]
  496. dlg = TextEntryDialog(parent = self,
  497. message = _('Current name: %s\n\nEnter new name:') % location,
  498. caption = _('Rename selected location'),
  499. validator = GenericValidator(grass.legal_name, self._nameValidationFailed))
  500. if dlg.ShowModal() == wx.ID_OK:
  501. newlocation = dlg.GetValue()
  502. if newlocation == location:
  503. dlg.Destroy()
  504. return
  505. if newlocation in self.listOfLocations:
  506. wx.MessageBox(parent = self,
  507. caption = _('Message'),
  508. message = _('Unable to rename location.\n\n'
  509. 'Location <%s> already exists in GRASS database.') % newlocation,
  510. style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  511. else:
  512. try:
  513. os.rename(os.path.join(self.gisdbase, location),
  514. os.path.join(self.gisdbase, newlocation))
  515. self.UpdateLocations(self.gisdbase)
  516. self.lblocations.SetSelection(self.listOfLocations.index(newlocation))
  517. self.UpdateMapsets(newlocation)
  518. except StandardError, e:
  519. wx.MessageBox(parent = self,
  520. caption = _('Error'),
  521. message = _('Unable to rename location.\n\n%s') % e,
  522. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  523. dlg.Destroy()
  524. def DeleteMapset(self):
  525. """!Delete selected mapset
  526. """
  527. location = self.listOfLocations[self.lblocations.GetSelection()]
  528. mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
  529. if mapset == 'PERMANENT':
  530. GMessage(parent = self,
  531. message = _('Mapset <PERMANENT> is required for valid GRASS location.\n\n'
  532. 'This mapset cannot be deleted.'))
  533. return
  534. dlg = wx.MessageDialog(parent = self, message = _("Do you want to continue with deleting mapset <%(mapset)s> "
  535. "from location <%(location)s>?\n\n"
  536. "ALL MAPS included in this mapset will be "
  537. "PERMANENTLY DELETED!") % {'mapset' : mapset,
  538. 'location' : location},
  539. caption = _("Delete selected mapset"),
  540. style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  541. if dlg.ShowModal() == wx.ID_YES:
  542. try:
  543. shutil.rmtree(os.path.join(self.gisdbase, location, mapset))
  544. self.OnSelectLocation(None)
  545. self.lbmapsets.SetSelection(0)
  546. except:
  547. wx.MessageBox(message = _('Unable to delete mapset'))
  548. dlg.Destroy()
  549. def DeleteLocation(self):
  550. """
  551. Delete selected location
  552. """
  553. location = self.listOfLocations[self.lblocations.GetSelection()]
  554. dlg = wx.MessageDialog(parent = self, message = _("Do you want to continue with deleting "
  555. "location <%s>?\n\n"
  556. "ALL MAPS included in this location will be "
  557. "PERMANENTLY DELETED!") % (location),
  558. caption = _("Delete selected location"),
  559. style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  560. if dlg.ShowModal() == wx.ID_YES:
  561. try:
  562. shutil.rmtree(os.path.join(self.gisdbase, location))
  563. self.UpdateLocations(self.gisdbase)
  564. self.lblocations.SetSelection(0)
  565. self.OnSelectLocation(None)
  566. self.lbmapsets.SetSelection(0)
  567. except:
  568. wx.MessageBox(message = _('Unable to delete location'))
  569. dlg.Destroy()
  570. def UpdateLocations(self, dbase):
  571. """!Update list of locations"""
  572. try:
  573. self.listOfLocations = GetListOfLocations(dbase)
  574. except UnicodeEncodeError:
  575. GError(parent = self,
  576. message = _("Unable to set GRASS database. "
  577. "Check your locale settings."))
  578. self.lblocations.Clear()
  579. self.lblocations.InsertItems(self.listOfLocations, 0)
  580. if len(self.listOfLocations) > 0:
  581. self.lblocations.SetSelection(0)
  582. else:
  583. self.lblocations.SetSelection(wx.NOT_FOUND)
  584. GWarning(_("No GRASS location found in '%s'.") % self.gisdbase,
  585. parent = self)
  586. return self.listOfLocations
  587. def UpdateMapsets(self, location):
  588. """!Update list of mapsets"""
  589. self.FormerMapsetSelection = wx.NOT_FOUND # for non-selectable item
  590. self.listOfMapsetsSelectable = list()
  591. self.listOfMapsets = GetListOfMapsets(self.gisdbase, location)
  592. self.lbmapsets.Clear()
  593. # disable mapset with denied permission
  594. locationName = os.path.basename(location)
  595. ret = RunCommand('g.mapset',
  596. read = True,
  597. flags = 'l',
  598. location = locationName,
  599. gisdbase = self.gisdbase)
  600. if ret:
  601. for line in ret.splitlines():
  602. self.listOfMapsetsSelectable += line.split(' ')
  603. else:
  604. RunCommand("g.gisenv",
  605. set = "GISDBASE=%s" % self.gisdbase)
  606. RunCommand("g.gisenv",
  607. set = "LOCATION_NAME=%s" % locationName)
  608. RunCommand("g.gisenv",
  609. set = "MAPSET=PERMANENT")
  610. # first run only
  611. self.listOfMapsetsSelectable = copy.copy(self.listOfMapsets)
  612. disabled = []
  613. idx = 0
  614. for mapset in self.listOfMapsets:
  615. if mapset not in self.listOfMapsetsSelectable or \
  616. os.path.isfile(os.path.join(self.gisdbase,
  617. locationName,
  618. mapset, ".gislock")):
  619. disabled.append(idx)
  620. idx += 1
  621. self.lbmapsets.InsertItems(self.listOfMapsets, 0, disabled = disabled)
  622. return self.listOfMapsets
  623. def OnSelectLocation(self, event):
  624. """!Location selected"""
  625. if event:
  626. self.lblocations.SetSelection(event.GetIndex())
  627. if self.lblocations.GetSelection() != wx.NOT_FOUND:
  628. self.UpdateMapsets(os.path.join(self.gisdbase,
  629. self.listOfLocations[self.lblocations.GetSelection()]))
  630. else:
  631. self.listOfMapsets = []
  632. disabled = []
  633. idx = 0
  634. try:
  635. locationName = self.listOfLocations[self.lblocations.GetSelection()]
  636. except IndexError:
  637. locationName = ''
  638. for mapset in self.listOfMapsets:
  639. if mapset not in self.listOfMapsetsSelectable or \
  640. os.path.isfile(os.path.join(self.gisdbase,
  641. locationName,
  642. mapset, ".gislock")):
  643. disabled.append(idx)
  644. idx += 1
  645. self.lbmapsets.Clear()
  646. self.lbmapsets.InsertItems(self.listOfMapsets, 0, disabled = disabled)
  647. if len(self.listOfMapsets) > 0:
  648. self.lbmapsets.SetSelection(0)
  649. if locationName:
  650. # enable start button when location and mapset is selected
  651. self.bstart.Enable()
  652. self.bmapset.Enable()
  653. self.manageloc.Enable()
  654. else:
  655. self.lbmapsets.SetSelection(wx.NOT_FOUND)
  656. self.bstart.Enable(False)
  657. self.bmapset.Enable(False)
  658. self.manageloc.Enable(False)
  659. def OnSelectMapset(self, event):
  660. """!Mapset selected"""
  661. self.lbmapsets.SetSelection(event.GetIndex())
  662. if event.GetText() not in self.listOfMapsetsSelectable:
  663. self.lbmapsets.SetSelection(self.FormerMapsetSelection)
  664. else:
  665. self.FormerMapsetSelection = event.GetIndex()
  666. event.Skip()
  667. def OnSetDatabase(self, event):
  668. """!Database set"""
  669. gisdbase = self.tgisdbase.GetValue()
  670. if not os.path.exists(gisdbase):
  671. GError(_("Path '%s' doesn't exist.") % gisdbase,
  672. parent = self)
  673. return
  674. self.gisdbase = self.tgisdbase.GetValue()
  675. self.UpdateLocations(self.gisdbase)
  676. self.OnSelectLocation(None)
  677. def OnBrowse(self, event):
  678. """'Browse' button clicked"""
  679. if not event:
  680. defaultPath = os.getenv('HOME')
  681. else:
  682. defaultPath = ""
  683. dlg = wx.DirDialog(parent = self, message = _("Choose GIS Data Directory"),
  684. defaultPath = defaultPath, style = wx.DD_DEFAULT_STYLE)
  685. if dlg.ShowModal() == wx.ID_OK:
  686. self.gisdbase = dlg.GetPath()
  687. self.tgisdbase.SetValue(self.gisdbase)
  688. self.OnSetDatabase(event)
  689. dlg.Destroy()
  690. def OnCreateMapset(self, event):
  691. """!Create new mapset"""
  692. dlg = TextEntryDialog(parent = self,
  693. message = _('Enter name for new mapset:'),
  694. caption = _('Create new mapset'),
  695. defaultValue = self._getDefaultMapsetName(),
  696. validator = GenericValidator(grass.legal_name, self._nameValidationFailed))
  697. if dlg.ShowModal() == wx.ID_OK:
  698. mapset = dlg.GetValue()
  699. return self.CreateNewMapset(mapset = mapset)
  700. else:
  701. return False
  702. def CreateNewMapset(self, mapset):
  703. if mapset in self.listOfMapsets:
  704. GMessage(parent = self,
  705. message = _("Mapset <%s> already exists.") % mapset)
  706. return False
  707. if mapset.lower() == 'ogr':
  708. dlg1 = wx.MessageDialog(parent = self,
  709. message = _("Mapset <%s> is reserved for direct "
  710. "read access to OGR layers. Please consider to use "
  711. "another name for your mapset.\n\n"
  712. "Are you really sure that you want to create this mapset?") % mapset,
  713. caption = _("Reserved mapset name"),
  714. style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  715. ret = dlg1.ShowModal()
  716. dlg1.Destroy()
  717. if ret == wx.ID_NO:
  718. dlg.Destroy()
  719. return False
  720. try:
  721. self.gisdbase = self.tgisdbase.GetValue()
  722. location = self.listOfLocations[self.lblocations.GetSelection()]
  723. os.mkdir(os.path.join(self.gisdbase, location, mapset))
  724. # copy WIND file and its permissions from PERMANENT and set permissions to u+rw,go+r
  725. shutil.copy(os.path.join(self.gisdbase, location, 'PERMANENT', 'WIND'),
  726. os.path.join(self.gisdbase, location, mapset))
  727. # os.chmod(os.path.join(database,location,mapset,'WIND'), 0644)
  728. self.OnSelectLocation(None)
  729. self.lbmapsets.SetSelection(self.listOfMapsets.index(mapset))
  730. self.bstart.SetFocus()
  731. return True
  732. except StandardError, e:
  733. GError(parent = self,
  734. message = _("Unable to create new mapset: %s") % e,
  735. showTraceback = False)
  736. return False
  737. def OnStart(self, event):
  738. """'Start GRASS' button clicked"""
  739. dbase = self.tgisdbase.GetValue()
  740. location = self.listOfLocations[self.lblocations.GetSelection()]
  741. mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
  742. lockfile = os.path.join(dbase, location, mapset, '.gislock')
  743. if os.path.isfile(lockfile):
  744. dlg = wx.MessageDialog(parent = self,
  745. message = _("GRASS is already running in selected mapset <%(mapset)s>\n"
  746. "(file %(lock)s found).\n\n"
  747. "Concurrent use not allowed.\n\n"
  748. "Do you want to try to remove .gislock (note that you "
  749. "need permission for this operation) and continue?") %
  750. { 'mapset' : mapset, 'lock' : lockfile },
  751. caption = _("Lock file found"),
  752. style = wx.YES_NO | wx.NO_DEFAULT |
  753. wx.ICON_QUESTION | wx.CENTRE)
  754. ret = dlg.ShowModal()
  755. dlg.Destroy()
  756. if ret == wx.ID_YES:
  757. dlg1 = wx.MessageDialog(parent = self,
  758. message = _("ARE YOU REALLY SURE?\n\n"
  759. "If you really are running another GRASS session doing this "
  760. "could corrupt your data. Have another look in the processor "
  761. "manager just to be sure..."),
  762. caption = _("Lock file found"),
  763. style = wx.YES_NO | wx.NO_DEFAULT |
  764. wx.ICON_QUESTION | wx.CENTRE)
  765. ret = dlg1.ShowModal()
  766. dlg1.Destroy()
  767. if ret == wx.ID_YES:
  768. try:
  769. os.remove(lockfile)
  770. except IOError, e:
  771. GError(_("Unable to remove '%(lock)s'.\n\n"
  772. "Details: %(reason)s") % { 'lock' : lockfile, 'reason' : e})
  773. else:
  774. return
  775. else:
  776. return
  777. self.SetLocation(dbase, location, mapset)
  778. self.ExitSuccessfully()
  779. def SetLocation(self, dbase, location, mapset):
  780. RunCommand("g.gisenv",
  781. set = "GISDBASE=%s" % dbase)
  782. RunCommand("g.gisenv",
  783. set = "LOCATION_NAME=%s" % location)
  784. RunCommand("g.gisenv",
  785. set = "MAPSET=%s" % mapset)
  786. def _getDefaultMapsetName(self):
  787. """!Returns default name for mapset."""
  788. try:
  789. defaultName = getpass.getuser()
  790. defaultName.encode('ascii') # raise error if not ascii (not valid mapset name)
  791. except: # whatever might go wrong
  792. defaultName = 'user'
  793. return defaultName
  794. def ExitSuccessfully(self):
  795. self.Destroy()
  796. sys.exit(0)
  797. def OnExit(self, event):
  798. """'Exit' button clicked"""
  799. self.Destroy()
  800. sys.exit(2)
  801. def OnHelp(self, event):
  802. """'Help' button clicked"""
  803. # help text in lib/init/helptext.html
  804. RunCommand('g.manual', entry = 'helptext')
  805. def OnCloseWindow(self, event):
  806. """!Close window event"""
  807. event.Skip()
  808. sys.exit(2)
  809. def _nameValidationFailed(self, ctrl):
  810. message = _("Name <%(name)s> is not a valid name for location or mapset. "
  811. "Please use only ASCII characters excluding %(chars)s "
  812. "and space.") % {'name': ctrl.GetValue(), 'chars': '/"\'@,=*~'}
  813. GError(parent=self, message=message, caption=_("Invalid name"))
  814. class GListBox(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin):
  815. """!Use wx.ListCtrl instead of wx.ListBox, different style for
  816. non-selectable items (e.g. mapsets with denied permission)"""
  817. def __init__(self, parent, id, size,
  818. choices, disabled = []):
  819. wx.ListCtrl.__init__(self, parent, id, size = size,
  820. style = wx.LC_REPORT | wx.LC_NO_HEADER | wx.LC_SINGLE_SEL |
  821. wx.BORDER_SUNKEN)
  822. listmix.ListCtrlAutoWidthMixin.__init__(self)
  823. self.InsertColumn(0, '')
  824. self.selected = wx.NOT_FOUND
  825. self._LoadData(choices, disabled)
  826. def _LoadData(self, choices, disabled = []):
  827. """!Load data into list
  828. @param choices list of item
  829. @param disabled list of indeces of non-selectable items
  830. """
  831. idx = 0
  832. for item in choices:
  833. index = self.InsertStringItem(sys.maxint, item)
  834. self.SetStringItem(index, 0, item)
  835. if idx in disabled:
  836. self.SetItemTextColour(idx, wx.Colour(150, 150, 150))
  837. idx += 1
  838. def Clear(self):
  839. self.DeleteAllItems()
  840. def InsertItems(self, choices, pos, disabled = []):
  841. self._LoadData(choices, disabled)
  842. def SetSelection(self, item, force = False):
  843. if item != wx.NOT_FOUND and \
  844. (platform.system() != 'Windows' or force):
  845. ### Windows -> FIXME
  846. self.SetItemState(item, wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED)
  847. self.selected = item
  848. def GetSelection(self):
  849. return self.selected
  850. class StartUp(wx.App):
  851. """!Start-up application"""
  852. def OnInit(self):
  853. if not globalvar.CheckWxVersion([2, 9]):
  854. wx.InitAllImageHandlers()
  855. StartUp = GRASSStartup()
  856. StartUp.CenterOnScreen()
  857. self.SetTopWindow(StartUp)
  858. StartUp.Show()
  859. if StartUp.GetRCValue("LOCATION_NAME") == "<UNKNOWN>":
  860. wx.MessageBox(parent = StartUp,
  861. caption = _('Starting GRASS for the first time'),
  862. message = _('GRASS needs a directory in which to store its data. '
  863. 'Create one now if you have not already done so. '
  864. 'A popular choice is "grassdata", located in '
  865. 'your home directory.'),
  866. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  867. StartUp.OnBrowse(None)
  868. return 1
  869. if __name__ == "__main__":
  870. if os.getenv("GISBASE") is None:
  871. sys.exit("Failed to start GUI, GRASS GIS is not running.")
  872. import gettext
  873. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  874. GRASSStartUp = StartUp(0)
  875. GRASSStartUp.MainLoop()