gis_set.py 43 KB

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