gis_set.py 44 KB

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