gis_set.py 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  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 " % _("Select GRASS GIS data directory"))
  86. self.location_box = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
  87. label=" %s " % _("Select GRASS Location"))
  88. self.mapset_box = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
  89. label=" %s " % _("Select GRASS Mapset"))
  90. # no message at the beginning
  91. self.lmessage = StaticWrapText(
  92. parent=self.panel, id=wx.ID_ANY,
  93. label=("This is a placeholer text to workaround layout issues."
  94. " Without this (long) text the widgets will not align"
  95. " when a message is shown."
  96. " This text is not translatable and users should never"
  97. " see it because it will be replaced by nothing or a real"
  98. " message after initial checks. If you are an user"
  99. " and you see this text, it is probably some minor issue."
  100. " Please, contact GRASS developers to tell them about it."))
  101. # It is not clear if all wx versions supports color, so try-except.
  102. # The color itself may not be correct for all platforms/system settings
  103. # but in http://xoomer.virgilio.it/infinity77/wxPython/Widgets/wx.SystemSettings.html
  104. # there is no 'warning' color.
  105. try:
  106. self.lmessage.SetForegroundColour(wx.Colour(255, 0, 0))
  107. except AttributeError:
  108. pass
  109. self.gisdbase_panel = wx.Panel(parent=self.panel)
  110. self.location_panel = wx.Panel(parent=self.panel)
  111. self.mapset_panel = wx.Panel(parent=self.panel)
  112. self.ldbase = wx.StaticText(
  113. parent=self.gisdbase_panel, id=wx.ID_ANY,
  114. label=_("GRASS GIS data directory contains Locations."))
  115. self.llocation = StaticWrapText(
  116. parent=self.location_panel, id=wx.ID_ANY,
  117. label=_("All data in one Location is in the same "
  118. " coordinate reference system (projection)."
  119. " One Location can be one project."
  120. " Location contains Mapsets."),
  121. style=wx.ALIGN_LEFT)
  122. self.lmapset = StaticWrapText(
  123. parent=self.mapset_panel, id=wx.ID_ANY,
  124. label=_("Mapset contains GIS data related"
  125. " to one project, task within one project,"
  126. " subregion or user."),
  127. style=wx.ALIGN_LEFT)
  128. try:
  129. for label in [self.ldbase, self.llocation, self.lmapset]:
  130. label.SetForegroundColour(
  131. wx.SystemSettings_GetColour(wx.SYS_COLOUR_GRAYTEXT))
  132. except AttributeError:
  133. # for explanation of try-except see above
  134. pass
  135. # buttons
  136. self.bstart = wx.Button(parent = self.panel, id = wx.ID_ANY,
  137. label = _("Start &GRASS session"))
  138. self.bstart.SetDefault()
  139. self.bexit = wx.Button(parent = self.panel, id = wx.ID_EXIT)
  140. self.bstart.SetMinSize((180, self.bexit.GetSize()[1]))
  141. self.bhelp = wx.Button(parent = self.panel, id = wx.ID_HELP)
  142. self.bbrowse = wx.Button(parent = self.gisdbase_panel, id = wx.ID_ANY,
  143. label = _("&Browse"))
  144. self.bmapset = wx.Button(parent = self.mapset_panel, id = wx.ID_ANY,
  145. label = _("&New"))
  146. self.bwizard = wx.Button(parent = self.location_panel, id = wx.ID_ANY,
  147. label = _("N&ew"))
  148. self.bwizard.SetToolTipString(_("Create a new location using location wizard."
  149. " After location is created successfully,"
  150. " GRASS session is started."))
  151. self.rename_location_button = wx.Button(parent=self.location_panel, id=wx.ID_ANY,
  152. label=_("Ren&ame"))
  153. self.rename_location_button.SetToolTipString(_("Rename selected location"))
  154. self.delete_location_button = wx.Button(parent=self.location_panel, id=wx.ID_ANY,
  155. label=_("De&lete"))
  156. self.delete_location_button.SetToolTipString(_("Delete selected location"))
  157. self.rename_mapset_button = wx.Button(parent=self.mapset_panel, id=wx.ID_ANY,
  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. label=_("&Delete"))
  162. self.delete_mapset_button.SetToolTipString(_("Delete selected mapset"))
  163. # textinputs
  164. self.tgisdbase = wx.TextCtrl(parent = self.gisdbase_panel, id = wx.ID_ANY, value = "", size = (300, -1),
  165. style = wx.TE_PROCESS_ENTER)
  166. # Locations
  167. self.lblocations = GListBox(parent = self.location_panel,
  168. id = wx.ID_ANY, size = (180, 200),
  169. choices = self.listOfLocations)
  170. self.lblocations.SetColumnWidth(0, 180)
  171. # TODO: sort; but keep PERMANENT on top of list
  172. # Mapsets
  173. self.lbmapsets = GListBox(parent = self.mapset_panel,
  174. id = wx.ID_ANY, size = (180, 200),
  175. choices = self.listOfMapsets)
  176. self.lbmapsets.SetColumnWidth(0, 180)
  177. # layout & properties, first do layout so everything is created
  178. self._do_layout()
  179. self._set_properties(grassVersion, grassRevisionStr)
  180. # events
  181. self.bbrowse.Bind(wx.EVT_BUTTON, self.OnBrowse)
  182. self.bstart.Bind(wx.EVT_BUTTON, self.OnStart)
  183. self.bexit.Bind(wx.EVT_BUTTON, self.OnExit)
  184. self.bhelp.Bind(wx.EVT_BUTTON, self.OnHelp)
  185. self.bmapset.Bind(wx.EVT_BUTTON, self.OnCreateMapset)
  186. self.bwizard.Bind(wx.EVT_BUTTON, self.OnWizard)
  187. self.rename_location_button.Bind(wx.EVT_BUTTON, self.RenameLocation)
  188. self.delete_location_button.Bind(wx.EVT_BUTTON, self.DeleteLocation)
  189. self.rename_mapset_button.Bind(wx.EVT_BUTTON, self.RenameMapset)
  190. self.delete_mapset_button.Bind(wx.EVT_BUTTON, self.DeleteMapset)
  191. self.lblocations.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectLocation)
  192. self.lbmapsets.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectMapset)
  193. self.lbmapsets.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnStart)
  194. self.tgisdbase.Bind(wx.EVT_TEXT_ENTER, self.OnSetDatabase)
  195. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  196. def _set_properties(self, version, revision):
  197. """Set frame properties"""
  198. self.SetTitle(_("GRASS GIS %s startup%s") % (version, revision))
  199. self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, "grass.ico"),
  200. wx.BITMAP_TYPE_ICO))
  201. self.bstart.SetForegroundColour(wx.Colour(35, 142, 35))
  202. self.bstart.SetToolTipString(_("Enter GRASS session"))
  203. self.bstart.Enable(False)
  204. self.bmapset.Enable(False)
  205. # this all was originally a choice, perhaps just mapset needed
  206. self.rename_location_button.Enable(False)
  207. self.delete_location_button.Enable(False)
  208. self.rename_mapset_button.Enable(False)
  209. self.delete_mapset_button.Enable(False)
  210. # set database
  211. if not self.gisdbase:
  212. # sets an initial path for gisdbase if nothing in GISRC
  213. if os.path.isdir(os.getenv("HOME")):
  214. self.gisdbase = os.getenv("HOME")
  215. else:
  216. self.gisdbase = os.getcwd()
  217. try:
  218. self.tgisdbase.SetValue(self.gisdbase)
  219. except UnicodeDecodeError:
  220. wx.MessageBox(parent = self, caption = _("Error"),
  221. message = _("Unable to set GRASS database. "
  222. "Check your locale settings."),
  223. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  224. self.OnSetDatabase(None)
  225. location = self.GetRCValue("LOCATION_NAME")
  226. if location == "<UNKNOWN>":
  227. return
  228. if not os.path.isdir(os.path.join(self.gisdbase, location)):
  229. location = None
  230. # list of locations
  231. self.UpdateLocations(self.gisdbase)
  232. try:
  233. self.lblocations.SetSelection(self.listOfLocations.index(location),
  234. force = True)
  235. self.lblocations.EnsureVisible(self.listOfLocations.index(location))
  236. except ValueError:
  237. sys.stderr.write(_("ERROR: Location <%s> not found\n") % self.GetRCValue("LOCATION_NAME"))
  238. if len(self.listOfLocations) > 0:
  239. self.lblocations.SetSelection(0, force = True)
  240. self.lblocations.EnsureVisible(0)
  241. location = self.listOfLocations[0]
  242. else:
  243. return
  244. # list of mapsets
  245. self.UpdateMapsets(os.path.join(self.gisdbase, location))
  246. mapset = self.GetRCValue("MAPSET")
  247. if mapset:
  248. try:
  249. self.lbmapsets.SetSelection(self.listOfMapsets.index(mapset),
  250. force = True)
  251. self.lbmapsets.EnsureVisible(self.listOfMapsets.index(mapset))
  252. except ValueError:
  253. sys.stderr.write(_("ERROR: Mapset <%s> not found\n") % mapset)
  254. self.lbmapsets.SetSelection(0, force = True)
  255. self.lbmapsets.EnsureVisible(0)
  256. def _do_layout(self):
  257. sizer = wx.BoxSizer(wx.VERTICAL)
  258. self.sizer = sizer # for the layout call after changing message
  259. dbase_sizer = wx.BoxSizer(wx.HORIZONTAL)
  260. location_mapset_sizer = wx.BoxSizer(wx.HORIZONTAL)
  261. gisdbase_panel_sizer = wx.BoxSizer(wx.VERTICAL)
  262. gisdbase_boxsizer = wx.StaticBoxSizer(self.gisdbase_box, wx.VERTICAL)
  263. btns_sizer = wx.BoxSizer(wx.HORIZONTAL)
  264. self.gisdbase_panel.SetSizer(gisdbase_panel_sizer)
  265. # gis data directory
  266. gisdbase_boxsizer.Add(item=self.gisdbase_panel, proportion=1,
  267. flag=wx.EXPAND | wx.ALL,
  268. border=3)
  269. gisdbase_panel_sizer.Add(item=dbase_sizer, proportion=1,
  270. flag=wx.EXPAND | wx.ALL,
  271. border=3)
  272. gisdbase_panel_sizer.Add(item=self.ldbase, proportion=0,
  273. flag=wx.EXPAND | wx.ALL,
  274. border=3)
  275. dbase_sizer.Add(item = self.tgisdbase, proportion = 1,
  276. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  277. border = 3)
  278. dbase_sizer.Add(item = self.bbrowse, proportion = 0,
  279. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  280. border = 3)
  281. gisdbase_panel_sizer.Fit(self.gisdbase_panel)
  282. # location and mapset lists
  283. def layout_list_box(box, panel, list_box, buttons, description):
  284. panel_sizer = wx.BoxSizer(wx.VERTICAL)
  285. main_sizer = wx.BoxSizer(wx.HORIZONTAL)
  286. box_sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  287. buttons_sizer = wx.BoxSizer(wx.VERTICAL)
  288. panel.SetSizer(panel_sizer)
  289. panel_sizer.Fit(panel)
  290. main_sizer.Add(item=list_box, proportion=1,
  291. flag=wx.EXPAND | wx.ALL,
  292. border=3)
  293. main_sizer.Add(item=buttons_sizer, proportion=0,
  294. flag=wx.ALIGN_CENTER_HORIZONTAL | wx.ALL,
  295. border=3)
  296. for button in buttons:
  297. buttons_sizer.Add(item=button, proportion=0,
  298. flag=wx.EXPAND | wx.ALL,
  299. border=3)
  300. box_sizer.Add(item=panel, proportion=1,
  301. flag=wx.EXPAND | wx.ALL,
  302. border=3)
  303. panel_sizer.Add(item=main_sizer, proportion=1,
  304. flag=wx.EXPAND | wx.ALL,
  305. border=3)
  306. panel_sizer.Add(item=description, proportion=0,
  307. flag=wx.EXPAND | wx.ALL,
  308. border=3)
  309. return box_sizer
  310. location_boxsizer = layout_list_box(
  311. box=self.location_box,
  312. panel=self.location_panel,
  313. list_box=self.lblocations,
  314. buttons=[self.bwizard, self.rename_location_button,
  315. self.delete_location_button],
  316. description=self.llocation)
  317. mapset_boxsizer = layout_list_box(
  318. box=self.mapset_box,
  319. panel=self.mapset_panel,
  320. list_box=self.lbmapsets,
  321. buttons=[self.bmapset, self.rename_mapset_button,
  322. self.delete_mapset_button],
  323. description=self.lmapset)
  324. # location and mapset sizer
  325. location_mapset_sizer.Add(item=location_boxsizer, proportion=1,
  326. flag = wx.LEFT | wx.RIGHT | wx.EXPAND,
  327. border = 3)
  328. location_mapset_sizer.Add(item=mapset_boxsizer, proportion=1,
  329. flag = wx.RIGHT | wx.EXPAND,
  330. border = 3)
  331. # buttons
  332. btns_sizer.Add(item = self.bstart, proportion = 0,
  333. flag = wx.ALIGN_CENTER_HORIZONTAL |
  334. wx.ALIGN_CENTER_VERTICAL |
  335. wx.ALL,
  336. border = 5)
  337. btns_sizer.Add(item = self.bexit, proportion = 0,
  338. flag = wx.ALIGN_CENTER_HORIZONTAL |
  339. wx.ALIGN_CENTER_VERTICAL |
  340. wx.ALL,
  341. border = 5)
  342. btns_sizer.Add(item = self.bhelp, proportion = 0,
  343. flag = wx.ALIGN_CENTER_HORIZONTAL |
  344. wx.ALIGN_CENTER_VERTICAL |
  345. wx.ALL,
  346. border = 5)
  347. # main sizer
  348. sizer.Add(item = self.hbitmap,
  349. proportion = 0,
  350. flag = wx.ALIGN_CENTER_VERTICAL |
  351. wx.ALIGN_CENTER_HORIZONTAL |
  352. wx.ALL,
  353. border = 3) # image
  354. sizer.Add(item=gisdbase_boxsizer, proportion=0,
  355. flag = wx.ALIGN_CENTER_HORIZONTAL |
  356. wx.RIGHT | wx.LEFT | wx.TOP | wx.EXPAND,
  357. border=3) # GISDBASE setting
  358. # warning/error message
  359. sizer.Add(item=self.lmessage,
  360. proportion=0,
  361. flag=wx.ALIGN_CENTER_VERTICAL |
  362. wx.ALIGN_LEFT | wx.ALL | wx.EXPAND, border=8)
  363. sizer.Add(item=location_mapset_sizer, proportion=1,
  364. flag = wx.RIGHT | wx.LEFT | wx.EXPAND,
  365. border = 1)
  366. sizer.Add(item = btns_sizer, proportion = 0,
  367. flag = wx.ALIGN_CENTER_VERTICAL |
  368. wx.ALIGN_CENTER_HORIZONTAL |
  369. wx.RIGHT | wx.LEFT,
  370. border = 1)
  371. self.panel.SetAutoLayout(True)
  372. self.panel.SetSizer(sizer)
  373. sizer.Fit(self.panel)
  374. sizer.SetSizeHints(self)
  375. self.Layout()
  376. def _readGisRC(self):
  377. """Read variables from $HOME/.grass7/rc file
  378. """
  379. grassrc = {}
  380. gisrc = os.getenv("GISRC")
  381. if gisrc and os.path.isfile(gisrc):
  382. try:
  383. rc = open(gisrc, "r")
  384. for line in rc.readlines():
  385. try:
  386. key, val = line.split(":", 1)
  387. except ValueError as e:
  388. sys.stderr.write(_('Invalid line in GISRC file (%s):%s\n' % \
  389. (e, line)))
  390. grassrc[key.strip()] = DecodeString(val.strip())
  391. finally:
  392. rc.close()
  393. return grassrc
  394. def _showWarning(self, text):
  395. """Displays a warning message to the user.
  396. There is no cleaning procedure. You should call _hideMessage when
  397. you know that there is everything correct now.
  398. """
  399. self.lmessage.SetLabel(_("Warning: ") + text)
  400. self.sizer.Layout()
  401. def _showError(self, text):
  402. """Displays a error message to the user.
  403. There is no cleaning procedure. You should call _hideMessage when
  404. you know that there is everything correct now.
  405. """
  406. self.lmessage.SetLabel(_("Error: ") + text)
  407. self.sizer.Layout()
  408. def _hideMessage(self):
  409. """Clears/hides the error message."""
  410. # we do no hide widget
  411. # because we do not want the dialog to change the size
  412. self.lmessage.SetLabel("")
  413. self.sizer.Layout()
  414. def GetRCValue(self, value):
  415. """Return GRASS variable (read from GISRC)
  416. """
  417. if self.grassrc.has_key(value):
  418. return self.grassrc[value]
  419. else:
  420. return None
  421. def OnWizard(self, event):
  422. """Location wizard started"""
  423. from location_wizard.wizard import LocationWizard
  424. gWizard = LocationWizard(parent = self,
  425. grassdatabase = self.tgisdbase.GetValue())
  426. if gWizard.location != None:
  427. self.tgisdbase.SetValue(gWizard.grassdatabase)
  428. self.OnSetDatabase(None)
  429. self.UpdateMapsets(os.path.join(self.gisdbase, gWizard.location))
  430. self.lblocations.SetSelection(self.listOfLocations.index(gWizard.location))
  431. self.lbmapsets.SetSelection(0)
  432. self.SetLocation(self.gisdbase, gWizard.location, 'PERMANENT')
  433. if gWizard.georeffile:
  434. message = _("Do you want to import <%(name)s> to the newly created location? "
  435. "The location's default region will be set from this imported "
  436. "map.") % {'name': gWizard.georeffile}
  437. dlg = wx.MessageDialog(parent = self,
  438. message = message,
  439. caption = _("Import data?"),
  440. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  441. dlg.CenterOnScreen()
  442. if dlg.ShowModal() == wx.ID_YES:
  443. self.ImportFile(gWizard.georeffile)
  444. else:
  445. self.SetDefaultRegion(location = gWizard.location)
  446. dlg.Destroy()
  447. else:
  448. self.SetDefaultRegion(location = gWizard.location)
  449. dlg = TextEntryDialog(parent=self,
  450. message=_("Do you want to create new mapset?"),
  451. caption=_("Create new mapset"),
  452. defaultValue=self._getDefaultMapsetName(),
  453. validator=GenericValidator(grass.legal_name, self._nameValidationFailed),
  454. style=wx.OK | wx.CANCEL | wx.HELP)
  455. help = dlg.FindWindowById(wx.ID_HELP)
  456. help.Bind(wx.EVT_BUTTON, self.OnHelp)
  457. if dlg.ShowModal() == wx.ID_OK:
  458. mapsetName = dlg.GetValue()
  459. self.CreateNewMapset(mapsetName)
  460. def SetDefaultRegion(self, location):
  461. """Asks to set default region."""
  462. caption = _("Location <%s> created") % location
  463. message = _("Do you want to set the default "
  464. "region extents and resolution now?")
  465. dlg = wx.MessageDialog(parent = self,
  466. message = "%(caption)s.\n\n%(extent)s" % ({'caption': caption,
  467. 'extent': message}),
  468. caption = caption,
  469. style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  470. dlg.CenterOnScreen()
  471. if dlg.ShowModal() == wx.ID_YES:
  472. dlg.Destroy()
  473. defineRegion = RegionDef(self, location = location)
  474. defineRegion.CenterOnScreen()
  475. defineRegion.ShowModal()
  476. defineRegion.Destroy()
  477. else:
  478. dlg.Destroy()
  479. def ImportFile(self, filePath):
  480. """Tries to import file as vector or raster.
  481. If successfull sets default region from imported map.
  482. """
  483. RunCommand('db.connect', flags='c')
  484. mapName = os.path.splitext(os.path.basename(filePath))[0]
  485. vectors = RunCommand('v.in.ogr', input = filePath, flags = 'l',
  486. read = True)
  487. wx.BeginBusyCursor()
  488. wx.Yield()
  489. if mapName in vectors:
  490. # vector detected
  491. returncode, error = RunCommand('v.in.ogr', input = filePath, output = mapName,
  492. getErrorMsg = True)
  493. else:
  494. returncode, error = RunCommand('r.in.gdal', input = filePath, output = mapName,
  495. getErrorMsg = True)
  496. wx.EndBusyCursor()
  497. if returncode != 0:
  498. GError(parent = self,
  499. message = _("Import of <%(name)s> failed.\n"
  500. "Reason: %(msg)s") % ({'name': filePath, 'msg': error}))
  501. else:
  502. GMessage(message = _("Data file <%(name)s> imported successfully.") % {'name': filePath},
  503. parent = self)
  504. if not grass.find_file(element = 'cell', name = mapName)['fullname'] and \
  505. not grass.find_file(element = 'vector', name = mapName)['fullname']:
  506. GError(parent = self,
  507. message = _("Map <%s> not found.") % mapName)
  508. else:
  509. if mapName in vectors:
  510. args = {'vector' : mapName}
  511. else:
  512. args = {'raster' : mapName}
  513. RunCommand('g.region', flags = 's', parent = self, **args)
  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. % 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 indeces 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 in which to store its data. '
  935. 'Create one now if you have not already done so. '
  936. 'A popular choice is "grassdata", located in '
  937. 'your home directory. '
  938. 'Press Browse button to select the directory.'))
  939. return 1
  940. if __name__ == "__main__":
  941. if os.getenv("GISBASE") is None:
  942. sys.exit("Failed to start GUI, GRASS GIS is not running.")
  943. GRASSStartUp = StartUp(0)
  944. GRASSStartUp.MainLoop()