gis_set.py 46 KB

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