gis_set.py 44 KB

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