gis_set.py 43 KB

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