gis_set.py 46 KB

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