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