gis_set.py 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  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. dlg = wx.MessageDialog(parent = self,
  392. message = _("Do you want to set the default "
  393. "region extents and resolution now?"),
  394. caption = _("Location <%s> created") % location,
  395. style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  396. dlg.CenterOnScreen()
  397. if dlg.ShowModal() == wx.ID_YES:
  398. dlg.Destroy()
  399. defineRegion = RegionDef(self, location = location)
  400. defineRegion.CenterOnScreen()
  401. defineRegion.ShowModal()
  402. defineRegion.Destroy()
  403. else:
  404. dlg.Destroy()
  405. def ImportFile(self, filePath):
  406. """!Tries to import file as vector or raster.
  407. If successfull sets default region from imported map.
  408. """
  409. mapName = os.path.splitext(os.path.basename(filePath))[0]
  410. vectors = RunCommand('v.in.ogr', dsn = filePath, flags = 'l',
  411. read = True)
  412. wx.BeginBusyCursor()
  413. wx.Yield()
  414. if mapName in vectors:
  415. # vector detected
  416. returncode, error = RunCommand('v.in.ogr', dsn = filePath, output = mapName,
  417. getErrorMsg = True)
  418. else:
  419. returncode, error = RunCommand('r.in.gdal', input = filePath, output = mapName,
  420. getErrorMsg = True)
  421. wx.EndBusyCursor()
  422. if returncode != 0:
  423. GError(parent = self,
  424. message = _("Import of <%(name)s> failed.\n"
  425. "Reason: %(msg)s") % ({'name': filePath, 'msg': error}))
  426. else:
  427. GMessage(message = _("Data file <%(name)s> imported successfully.") % {'name': filePath},
  428. parent = self)
  429. if not grass.find_file(element = 'cell', name = mapName)['fullname'] and \
  430. not grass.find_file(element = 'vector', name = mapName)['fullname']:
  431. GError(parent = self,
  432. message = _("Map <%s> not found.") % mapName)
  433. else:
  434. if mapName in vectors:
  435. args = {'vect' : mapName}
  436. else:
  437. args = {'rast' : mapName}
  438. RunCommand('g.region', flags = 's', parent = self, **args)
  439. def OnManageLoc(self, event):
  440. """!Location management choice control handler
  441. """
  442. sel = event.GetSelection()
  443. if sel == 0:
  444. self.RenameMapset()
  445. elif sel == 1:
  446. self.RenameLocation()
  447. elif sel == 2:
  448. self.DeleteMapset()
  449. elif sel == 3:
  450. self.DeleteLocation()
  451. event.Skip()
  452. def RenameMapset(self):
  453. """!Rename selected mapset
  454. """
  455. location = self.listOfLocations[self.lblocations.GetSelection()]
  456. mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
  457. if mapset == 'PERMANENT':
  458. GMessage(parent = self,
  459. message = _('Mapset <PERMANENT> is required for valid GRASS location.\n\n'
  460. 'This mapset cannot be renamed.'))
  461. return
  462. dlg = TextEntryDialog(parent = self,
  463. message = _('Current name: %s\n\nEnter new name:') % mapset,
  464. caption = _('Rename selected mapset'),
  465. validator = GenericValidator(grass.legal_name, self._nameValidationFailed))
  466. if dlg.ShowModal() == wx.ID_OK:
  467. newmapset = dlg.GetValue()
  468. if newmapset == mapset:
  469. dlg.Destroy()
  470. return
  471. if newmapset in self.listOfMapsets:
  472. wx.MessageBox(parent = self,
  473. caption = _('Message'),
  474. message = _('Unable to rename mapset.\n\n'
  475. 'Mapset <%s> already exists in location.') % newmapset,
  476. style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  477. else:
  478. try:
  479. os.rename(os.path.join(self.gisdbase, location, mapset),
  480. os.path.join(self.gisdbase, location, newmapset))
  481. self.OnSelectLocation(None)
  482. self.lbmapsets.SetSelection(self.listOfMapsets.index(newmapset))
  483. except StandardError, e:
  484. wx.MessageBox(parent = self,
  485. caption = _('Error'),
  486. message = _('Unable to rename mapset.\n\n%s') % e,
  487. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  488. dlg.Destroy()
  489. def RenameLocation(self):
  490. """!Rename selected location
  491. """
  492. location = self.listOfLocations[self.lblocations.GetSelection()]
  493. dlg = TextEntryDialog(parent = self,
  494. message = _('Current name: %s\n\nEnter new name:') % location,
  495. caption = _('Rename selected location'),
  496. validator = GenericValidator(grass.legal_name, self._nameValidationFailed))
  497. if dlg.ShowModal() == wx.ID_OK:
  498. newlocation = dlg.GetValue()
  499. if newlocation == location:
  500. dlg.Destroy()
  501. return
  502. if newlocation in self.listOfLocations:
  503. wx.MessageBox(parent = self,
  504. caption = _('Message'),
  505. message = _('Unable to rename location.\n\n'
  506. 'Location <%s> already exists in GRASS database.') % newlocation,
  507. style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  508. else:
  509. try:
  510. os.rename(os.path.join(self.gisdbase, location),
  511. os.path.join(self.gisdbase, newlocation))
  512. self.UpdateLocations(self.gisdbase)
  513. self.lblocations.SetSelection(self.listOfLocations.index(newlocation))
  514. self.UpdateMapsets(newlocation)
  515. except StandardError, e:
  516. wx.MessageBox(parent = self,
  517. caption = _('Error'),
  518. message = _('Unable to rename location.\n\n%s') % e,
  519. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  520. dlg.Destroy()
  521. def DeleteMapset(self):
  522. """!Delete selected mapset
  523. """
  524. location = self.listOfLocations[self.lblocations.GetSelection()]
  525. mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
  526. if mapset == 'PERMANENT':
  527. GMessage(parent = self,
  528. message = _('Mapset <PERMANENT> is required for valid GRASS location.\n\n'
  529. 'This mapset cannot be deleted.'))
  530. return
  531. dlg = wx.MessageDialog(parent = self, message = _("Do you want to continue with deleting mapset <%(mapset)s> "
  532. "from location <%(location)s>?\n\n"
  533. "ALL MAPS included in this mapset will be "
  534. "PERMANENTLY DELETED!") % {'mapset' : mapset,
  535. 'location' : location},
  536. caption = _("Delete selected mapset"),
  537. style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  538. if dlg.ShowModal() == wx.ID_YES:
  539. try:
  540. shutil.rmtree(os.path.join(self.gisdbase, location, mapset))
  541. self.OnSelectLocation(None)
  542. self.lbmapsets.SetSelection(0)
  543. except:
  544. wx.MessageBox(message = _('Unable to delete mapset'))
  545. dlg.Destroy()
  546. def DeleteLocation(self):
  547. """
  548. Delete selected location
  549. """
  550. location = self.listOfLocations[self.lblocations.GetSelection()]
  551. dlg = wx.MessageDialog(parent = self, message = _("Do you want to continue with deleting "
  552. "location <%s>?\n\n"
  553. "ALL MAPS included in this location will be "
  554. "PERMANENTLY DELETED!") % (location),
  555. caption = _("Delete selected location"),
  556. style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  557. if dlg.ShowModal() == wx.ID_YES:
  558. try:
  559. shutil.rmtree(os.path.join(self.gisdbase, location))
  560. self.UpdateLocations(self.gisdbase)
  561. self.lblocations.SetSelection(0)
  562. self.OnSelectLocation(None)
  563. self.lbmapsets.SetSelection(0)
  564. except:
  565. wx.MessageBox(message = _('Unable to delete location'))
  566. dlg.Destroy()
  567. def UpdateLocations(self, dbase):
  568. """!Update list of locations"""
  569. try:
  570. self.listOfLocations = GetListOfLocations(dbase)
  571. except UnicodeEncodeError:
  572. GError(parent = self,
  573. message = _("Unable to set GRASS database. "
  574. "Check your locale settings."))
  575. self.lblocations.Clear()
  576. self.lblocations.InsertItems(self.listOfLocations, 0)
  577. if len(self.listOfLocations) > 0:
  578. self.lblocations.SetSelection(0)
  579. else:
  580. self.lblocations.SetSelection(wx.NOT_FOUND)
  581. GWarning(_("No GRASS location found in '%s'.") % self.gisdbase,
  582. parent = self)
  583. return self.listOfLocations
  584. def UpdateMapsets(self, location):
  585. """!Update list of mapsets"""
  586. self.FormerMapsetSelection = wx.NOT_FOUND # for non-selectable item
  587. self.listOfMapsetsSelectable = list()
  588. self.listOfMapsets = GetListOfMapsets(self.gisdbase, location)
  589. self.lbmapsets.Clear()
  590. # disable mapset with denied permission
  591. locationName = os.path.basename(location)
  592. ret = RunCommand('g.mapset',
  593. read = True,
  594. flags = 'l',
  595. location = locationName,
  596. gisdbase = self.gisdbase)
  597. if ret:
  598. for line in ret.splitlines():
  599. self.listOfMapsetsSelectable += line.split(' ')
  600. else:
  601. RunCommand("g.gisenv",
  602. set = "GISDBASE=%s" % self.gisdbase)
  603. RunCommand("g.gisenv",
  604. set = "LOCATION_NAME=%s" % locationName)
  605. RunCommand("g.gisenv",
  606. set = "MAPSET=PERMANENT")
  607. # first run only
  608. self.listOfMapsetsSelectable = copy.copy(self.listOfMapsets)
  609. disabled = []
  610. idx = 0
  611. for mapset in self.listOfMapsets:
  612. if mapset not in self.listOfMapsetsSelectable or \
  613. os.path.isfile(os.path.join(self.gisdbase,
  614. locationName,
  615. mapset, ".gislock")):
  616. disabled.append(idx)
  617. idx += 1
  618. self.lbmapsets.InsertItems(self.listOfMapsets, 0, disabled = disabled)
  619. return self.listOfMapsets
  620. def OnSelectLocation(self, event):
  621. """!Location selected"""
  622. if event:
  623. self.lblocations.SetSelection(event.GetIndex())
  624. if self.lblocations.GetSelection() != wx.NOT_FOUND:
  625. self.UpdateMapsets(os.path.join(self.gisdbase,
  626. self.listOfLocations[self.lblocations.GetSelection()]))
  627. else:
  628. self.listOfMapsets = []
  629. disabled = []
  630. idx = 0
  631. try:
  632. locationName = self.listOfLocations[self.lblocations.GetSelection()]
  633. except IndexError:
  634. locationName = ''
  635. for mapset in self.listOfMapsets:
  636. if mapset not in self.listOfMapsetsSelectable or \
  637. os.path.isfile(os.path.join(self.gisdbase,
  638. locationName,
  639. mapset, ".gislock")):
  640. disabled.append(idx)
  641. idx += 1
  642. self.lbmapsets.Clear()
  643. self.lbmapsets.InsertItems(self.listOfMapsets, 0, disabled = disabled)
  644. if len(self.listOfMapsets) > 0:
  645. self.lbmapsets.SetSelection(0)
  646. if locationName:
  647. # enable start button when location and mapset is selected
  648. self.bstart.Enable()
  649. self.bmapset.Enable()
  650. self.manageloc.Enable()
  651. else:
  652. self.lbmapsets.SetSelection(wx.NOT_FOUND)
  653. self.bstart.Enable(False)
  654. self.bmapset.Enable(False)
  655. self.manageloc.Enable(False)
  656. def OnSelectMapset(self, event):
  657. """!Mapset selected"""
  658. self.lbmapsets.SetSelection(event.GetIndex())
  659. if event.GetText() not in self.listOfMapsetsSelectable:
  660. self.lbmapsets.SetSelection(self.FormerMapsetSelection)
  661. else:
  662. self.FormerMapsetSelection = event.GetIndex()
  663. event.Skip()
  664. def OnSetDatabase(self, event):
  665. """!Database set"""
  666. gisdbase = self.tgisdbase.GetValue()
  667. if not os.path.exists(gisdbase):
  668. GError(_("Path '%s' doesn't exist.") % gisdbase,
  669. parent = self)
  670. return
  671. self.gisdbase = self.tgisdbase.GetValue()
  672. self.UpdateLocations(self.gisdbase)
  673. self.OnSelectLocation(None)
  674. def OnBrowse(self, event):
  675. """'Browse' button clicked"""
  676. if not event:
  677. defaultPath = os.getenv('HOME')
  678. else:
  679. defaultPath = ""
  680. dlg = wx.DirDialog(parent = self, message = _("Choose GIS Data Directory"),
  681. defaultPath = defaultPath, style = wx.DD_DEFAULT_STYLE)
  682. if dlg.ShowModal() == wx.ID_OK:
  683. self.gisdbase = dlg.GetPath()
  684. self.tgisdbase.SetValue(self.gisdbase)
  685. self.OnSetDatabase(event)
  686. dlg.Destroy()
  687. def OnCreateMapset(self, event):
  688. """!Create new mapset"""
  689. dlg = TextEntryDialog(parent = self,
  690. message = _('Enter name for new mapset:'),
  691. caption = _('Create new mapset'),
  692. defaultValue = self._getDefaultMapsetName(),
  693. validator = GenericValidator(grass.legal_name, self._nameValidationFailed))
  694. if dlg.ShowModal() == wx.ID_OK:
  695. mapset = dlg.GetValue()
  696. return self.CreateNewMapset(mapset = mapset)
  697. else:
  698. return False
  699. def CreateNewMapset(self, mapset):
  700. if mapset in self.listOfMapsets:
  701. GMessage(parent = self,
  702. message = _("Mapset <%s> already exists.") % mapset)
  703. return False
  704. if mapset.lower() == 'ogr':
  705. dlg1 = wx.MessageDialog(parent = self,
  706. message = _("Mapset <%s> is reserved for direct "
  707. "read access to OGR layers. Please consider to use "
  708. "another name for your mapset.\n\n"
  709. "Are you really sure that you want to create this mapset?") % mapset,
  710. caption = _("Reserved mapset name"),
  711. style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  712. ret = dlg1.ShowModal()
  713. dlg1.Destroy()
  714. if ret == wx.ID_NO:
  715. dlg.Destroy()
  716. return False
  717. try:
  718. self.gisdbase = self.tgisdbase.GetValue()
  719. location = self.listOfLocations[self.lblocations.GetSelection()]
  720. os.mkdir(os.path.join(self.gisdbase, location, mapset))
  721. # copy WIND file and its permissions from PERMANENT and set permissions to u+rw,go+r
  722. shutil.copy(os.path.join(self.gisdbase, location, 'PERMANENT', 'WIND'),
  723. os.path.join(self.gisdbase, location, mapset))
  724. # os.chmod(os.path.join(database,location,mapset,'WIND'), 0644)
  725. self.OnSelectLocation(None)
  726. self.lbmapsets.SetSelection(self.listOfMapsets.index(mapset))
  727. self.bstart.SetFocus()
  728. return True
  729. except StandardError, e:
  730. GError(parent = self,
  731. message = _("Unable to create new mapset: %s") % e,
  732. showTraceback = False)
  733. return False
  734. def OnStart(self, event):
  735. """'Start GRASS' button clicked"""
  736. dbase = self.tgisdbase.GetValue()
  737. location = self.listOfLocations[self.lblocations.GetSelection()]
  738. mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
  739. lockfile = os.path.join(dbase, location, mapset, '.gislock')
  740. if os.path.isfile(lockfile):
  741. dlg = wx.MessageDialog(parent = self,
  742. message = _("GRASS is already running in selected mapset <%(mapset)s>\n"
  743. "(file %(lock)s found).\n\n"
  744. "Concurrent use not allowed.\n\n"
  745. "Do you want to try to remove .gislock (note that you "
  746. "need permission for this operation) and continue?") %
  747. { 'mapset' : mapset, 'lock' : lockfile },
  748. caption = _("Lock file found"),
  749. style = wx.YES_NO | wx.NO_DEFAULT |
  750. wx.ICON_QUESTION | wx.CENTRE)
  751. ret = dlg.ShowModal()
  752. dlg.Destroy()
  753. if ret == wx.ID_YES:
  754. dlg1 = wx.MessageDialog(parent = self,
  755. message = _("ARE YOU REALLY SURE?\n\n"
  756. "If you really are running another GRASS session doing this "
  757. "could corrupt your data. Have another look in the processor "
  758. "manager just to be sure..."),
  759. caption = _("Lock file found"),
  760. style = wx.YES_NO | wx.NO_DEFAULT |
  761. wx.ICON_QUESTION | wx.CENTRE)
  762. ret = dlg1.ShowModal()
  763. dlg1.Destroy()
  764. if ret == wx.ID_YES:
  765. try:
  766. os.remove(lockfile)
  767. except IOError, e:
  768. GError(_("Unable to remove '%(lock)s'.\n\n"
  769. "Details: %(reason)s") % { 'lock' : lockfile, 'reason' : e})
  770. else:
  771. return
  772. else:
  773. return
  774. self.SetLocation(dbase, location, mapset)
  775. self.ExitSuccessfully()
  776. def SetLocation(self, dbase, location, mapset):
  777. RunCommand("g.gisenv",
  778. set = "GISDBASE=%s" % dbase)
  779. RunCommand("g.gisenv",
  780. set = "LOCATION_NAME=%s" % location)
  781. RunCommand("g.gisenv",
  782. set = "MAPSET=%s" % mapset)
  783. def _getDefaultMapsetName(self):
  784. """!Returns default name for mapset."""
  785. try:
  786. defaultName = getpass.getuser()
  787. defaultName.encode('ascii') # raise error if not ascii (not valid mapset name)
  788. except: # whatever might go wrong
  789. defaultName = 'user'
  790. return defaultName
  791. def ExitSuccessfully(self):
  792. self.Destroy()
  793. sys.exit(0)
  794. def OnExit(self, event):
  795. """'Exit' button clicked"""
  796. self.Destroy()
  797. sys.exit(2)
  798. def OnHelp(self, event):
  799. """'Help' button clicked"""
  800. # help text in lib/init/helptext.html
  801. RunCommand('g.manual', entry = 'helptext')
  802. def OnCloseWindow(self, event):
  803. """!Close window event"""
  804. event.Skip()
  805. sys.exit(2)
  806. def _nameValidationFailed(self, ctrl):
  807. message = _("Name <%(name)s> is not a valid name for location or mapset. "
  808. "Please use only ASCII characters excluding %(chars)s "
  809. "and space.") % {'name': ctrl.GetValue(), 'chars': '/"\'@,=*~'}
  810. GError(parent=self, message=message, caption=_("Invalid name"))
  811. class GListBox(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin):
  812. """!Use wx.ListCtrl instead of wx.ListBox, different style for
  813. non-selectable items (e.g. mapsets with denied permission)"""
  814. def __init__(self, parent, id, size,
  815. choices, disabled = []):
  816. wx.ListCtrl.__init__(self, parent, id, size = size,
  817. style = wx.LC_REPORT | wx.LC_NO_HEADER | wx.LC_SINGLE_SEL |
  818. wx.BORDER_SUNKEN)
  819. listmix.ListCtrlAutoWidthMixin.__init__(self)
  820. self.InsertColumn(0, '')
  821. self.selected = wx.NOT_FOUND
  822. self._LoadData(choices, disabled)
  823. def _LoadData(self, choices, disabled = []):
  824. """!Load data into list
  825. @param choices list of item
  826. @param disabled list of indeces of non-selectable items
  827. """
  828. idx = 0
  829. for item in choices:
  830. index = self.InsertStringItem(sys.maxint, item)
  831. self.SetStringItem(index, 0, item)
  832. if idx in disabled:
  833. self.SetItemTextColour(idx, wx.Colour(150, 150, 150))
  834. idx += 1
  835. def Clear(self):
  836. self.DeleteAllItems()
  837. def InsertItems(self, choices, pos, disabled = []):
  838. self._LoadData(choices, disabled)
  839. def SetSelection(self, item, force = False):
  840. if item != wx.NOT_FOUND and \
  841. (platform.system() != 'Windows' or force):
  842. ### Windows -> FIXME
  843. self.SetItemState(item, wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED)
  844. self.selected = item
  845. def GetSelection(self):
  846. return self.selected
  847. class StartUp(wx.App):
  848. """!Start-up application"""
  849. def OnInit(self):
  850. if not globalvar.CheckWxVersion([2, 9]):
  851. wx.InitAllImageHandlers()
  852. StartUp = GRASSStartup()
  853. StartUp.CenterOnScreen()
  854. self.SetTopWindow(StartUp)
  855. StartUp.Show()
  856. if StartUp.GetRCValue("LOCATION_NAME") == "<UNKNOWN>":
  857. wx.MessageBox(parent = StartUp,
  858. caption = _('Starting GRASS for the first time'),
  859. message = _('GRASS needs a directory in which to store its data. '
  860. 'Create one now if you have not already done so. '
  861. 'A popular choice is "grassdata", located in '
  862. 'your home directory.'),
  863. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  864. StartUp.OnBrowse(None)
  865. return 1
  866. if __name__ == "__main__":
  867. if os.getenv("GISBASE") is None:
  868. sys.exit("Failed to start GUI, GRASS GIS is not running.")
  869. import gettext
  870. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  871. GRASSStartUp = StartUp(0)
  872. GRASSStartUp.MainLoop()