gis_set.py 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  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. # i18n is taken care of in the grass library code.
  21. # So we need to import it before any of the GUI code.
  22. from core import globalvar
  23. import wx
  24. import wx.lib.mixins.listctrl as listmix
  25. from core.gcmd import GMessage, GError, RunCommand
  26. from core.utils import GetListOfLocations, GetListOfMapsets
  27. from startup.utils import (
  28. get_lockfile_if_present, get_possible_database_path,
  29. create_database_directory)
  30. from startup.guiutils import (SetSessionMapset,
  31. create_mapset_interactively,
  32. rename_mapset_interactively,
  33. rename_location_interactively,
  34. delete_mapset_interactively,
  35. delete_location_interactively)
  36. import startup.guiutils as sgui
  37. from location_wizard.dialogs import RegionDef
  38. from gui_core.widgets import StaticWrapText
  39. from gui_core.wrap import Button, ListCtrl, StaticText, StaticBox, \
  40. TextCtrl, BitmapFromImage
  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, 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 = StaticWrapText(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.OnRenameLocation)
  200. self.delete_location_button.Bind(wx.EVT_BUTTON, self.OnDeleteLocation)
  201. self.download_location_button.Bind(wx.EVT_BUTTON, self.OnDownloadLocation)
  202. self.rename_mapset_button.Bind(wx.EVT_BUTTON, self.OnRenameMapset)
  203. self.delete_mapset_button.Bind(wx.EVT_BUTTON, self.OnDeleteMapset)
  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>" or location is None:
  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.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.RIGHT | wx.LEFT | wx.TOP | wx.EXPAND,
  379. border=3) # GISDBASE setting
  380. # warning/error message
  381. sizer.Add(self.lmessage,
  382. proportion=0,
  383. flag=wx.ALIGN_LEFT | wx.ALL | wx.EXPAND, border=5)
  384. sizer.Add(location_mapset_sizer, proportion=1,
  385. flag=wx.RIGHT | wx.LEFT | wx.EXPAND,
  386. border=1)
  387. sizer.Add(btns_sizer, proportion=0,
  388. flag=wx.ALIGN_CENTER_VERTICAL |
  389. wx.ALIGN_CENTER_HORIZONTAL |
  390. wx.RIGHT | wx.LEFT,
  391. border=3)
  392. self.panel.SetAutoLayout(True)
  393. self.panel.SetSizer(sizer)
  394. sizer.Fit(self.panel)
  395. sizer.SetSizeHints(self)
  396. self.Layout()
  397. def _showWarning(self, text):
  398. """Displays a warning, hint or info message to the user.
  399. This function can be used for all kinds of messages except for
  400. error messages.
  401. .. note::
  402. There is no cleaning procedure. You should call _hideMessage when
  403. you know that there is everything correct now.
  404. """
  405. self.lmessage.SetLabel(text)
  406. self.sizer.Layout()
  407. def _showError(self, text):
  408. """Displays a error message to the user.
  409. This function should be used only when something serious and unexpected
  410. happens, otherwise _showWarning should be used.
  411. .. note::
  412. There is no cleaning procedure. You should call _hideMessage when
  413. you know that there is everything correct now.
  414. """
  415. self.lmessage.SetLabel(_("Error: {text}").format(text=text))
  416. self.sizer.Layout()
  417. def _hideMessage(self):
  418. """Clears/hides the error message."""
  419. # we do no hide widget
  420. # because we do not want the dialog to change the size
  421. self.lmessage.SetLabel("")
  422. self.sizer.Layout()
  423. def GetRCValue(self, value):
  424. """Return GRASS variable (read from GISRC)
  425. """
  426. if value in self.grassrc:
  427. return self.grassrc[value]
  428. else:
  429. return None
  430. def SuggestDatabase(self):
  431. """Suggest (set) possible GRASS Database value"""
  432. # only if nothing is set (<UNKNOWN> comes from init script)
  433. if self.GetRCValue("LOCATION_NAME") != "<UNKNOWN>":
  434. return
  435. path = get_possible_database_path()
  436. # If nothing found, try to create GRASS directory
  437. if path is None:
  438. path = create_database_directory()
  439. if path:
  440. try:
  441. self.tgisdbase.SetValue(path)
  442. except UnicodeDecodeError:
  443. # restore previous state
  444. # wizard gives error in this case, we just ignore
  445. path = None
  446. self.tgisdbase.SetValue(self.gisdbase)
  447. # if we still have path
  448. if path:
  449. self.gisdbase = path
  450. self.OnSetDatabase(None)
  451. else:
  452. # nothing found
  453. # TODO: should it be warning, hint or message?
  454. self._showWarning(_(
  455. 'GRASS needs a directory (GRASS database) '
  456. 'in which to store its data. '
  457. 'Create one now if you have not already done so. '
  458. 'A popular choice is "grassdata", located in '
  459. 'your home directory. '
  460. 'Press Browse button to select the directory.'))
  461. def OnWizard(self, event):
  462. """Location wizard started"""
  463. from location_wizard.wizard import LocationWizard
  464. gWizard = LocationWizard(parent=self,
  465. grassdatabase=self.tgisdbase.GetValue())
  466. if gWizard.location is not None:
  467. self.tgisdbase.SetValue(gWizard.grassdatabase)
  468. self.OnSetDatabase(None)
  469. self.UpdateMapsets(os.path.join(self.gisdbase, gWizard.location))
  470. self.lblocations.SetSelection(
  471. self.listOfLocations.index(
  472. gWizard.location))
  473. self.lbmapsets.SetSelection(0)
  474. self.SetLocation(self.gisdbase, gWizard.location, 'PERMANENT')
  475. if gWizard.georeffile:
  476. message = _("Do you want to import <%(name)s> to the newly created location?") % {
  477. 'name': gWizard.georeffile}
  478. dlg = wx.MessageDialog(parent=self, message=message, caption=_(
  479. "Import data?"), style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  480. dlg.CenterOnParent()
  481. if dlg.ShowModal() == wx.ID_YES:
  482. self.ImportFile(gWizard.georeffile)
  483. dlg.Destroy()
  484. if gWizard.default_region:
  485. defineRegion = RegionDef(self, location=gWizard.location)
  486. defineRegion.CenterOnParent()
  487. defineRegion.ShowModal()
  488. defineRegion.Destroy()
  489. if gWizard.user_mapset:
  490. self.OnCreateMapset(event)
  491. def ImportFile(self, filePath):
  492. """Tries to import file as vector or raster.
  493. If successfull sets default region from imported map.
  494. """
  495. RunCommand('db.connect', flags='c')
  496. mapName = os.path.splitext(os.path.basename(filePath))[0]
  497. vectors = RunCommand('v.in.ogr', input=filePath, flags='l',
  498. read=True)
  499. wx.BeginBusyCursor()
  500. wx.GetApp().Yield()
  501. if vectors:
  502. # vector detected
  503. returncode, error = RunCommand(
  504. 'v.in.ogr', input=filePath, output=mapName, flags='e',
  505. getErrorMsg=True)
  506. else:
  507. returncode, error = RunCommand(
  508. 'r.in.gdal', input=filePath, output=mapName, flags='e',
  509. getErrorMsg=True)
  510. wx.EndBusyCursor()
  511. if returncode != 0:
  512. GError(
  513. parent=self,
  514. message=_(
  515. "Import of <%(name)s> failed.\n"
  516. "Reason: %(msg)s") % ({
  517. 'name': filePath,
  518. 'msg': error}))
  519. else:
  520. GMessage(
  521. message=_(
  522. "Data file <%(name)s> imported successfully. "
  523. "The location's default region was set from this imported map.") % {
  524. 'name': filePath},
  525. parent=self)
  526. # the event can be refactored out by using lambda in bind
  527. def OnRenameMapset(self, event):
  528. """Rename selected mapset
  529. """
  530. location = self.listOfLocations[self.lblocations.GetSelection()]
  531. mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
  532. try:
  533. newmapset = rename_mapset_interactively(self, self.gisdbase,
  534. location, mapset)
  535. if newmapset:
  536. self.OnSelectLocation(None)
  537. self.lbmapsets.SetSelection(
  538. self.listOfMapsets.index(newmapset))
  539. except Exception as e:
  540. GError(parent=self,
  541. message=_("Unable to rename mapset: %s") % e,
  542. showTraceback=False)
  543. def OnRenameLocation(self, event):
  544. """Rename selected location
  545. """
  546. location = self.listOfLocations[self.lblocations.GetSelection()]
  547. try:
  548. newlocation = rename_location_interactively(self, self.gisdbase,
  549. location)
  550. if newlocation:
  551. self.UpdateLocations(self.gisdbase)
  552. self.lblocations.SetSelection(
  553. self.listOfLocations.index(newlocation))
  554. self.UpdateMapsets(newlocation)
  555. except Exception as e:
  556. GError(parent=self,
  557. message=_("Unable to rename location: %s") % e,
  558. showTraceback=False)
  559. def OnDeleteMapset(self, event):
  560. """
  561. Delete selected mapset
  562. """
  563. location = self.listOfLocations[self.lblocations.GetSelection()]
  564. mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
  565. try:
  566. if (delete_mapset_interactively(self, self.gisdbase,
  567. location, mapset)):
  568. self.OnSelectLocation(None)
  569. self.lbmapsets.SetSelection(0)
  570. except Exception as e:
  571. GError(parent=self,
  572. message=_("Unable to delete mapset: %s") % e,
  573. showTraceback=False)
  574. def OnDeleteLocation(self, event):
  575. """
  576. Delete selected location
  577. """
  578. location = self.listOfLocations[self.lblocations.GetSelection()]
  579. try:
  580. if (delete_location_interactively(self, self.gisdbase, location)):
  581. self.UpdateLocations(self.gisdbase)
  582. self.lblocations.SetSelection(0)
  583. self.OnSelectLocation(None)
  584. self.lbmapsets.SetSelection(0)
  585. except Exception as e:
  586. GError(parent=self,
  587. message=_("Unable to delete location: %s") % e,
  588. showTraceback=False)
  589. def OnDownloadLocation(self, event):
  590. """Download location online"""
  591. from startup.locdownload import LocationDownloadDialog
  592. loc_download = LocationDownloadDialog(parent=self, database=self.gisdbase)
  593. loc_download.ShowModal()
  594. location = loc_download.GetLocation()
  595. if location:
  596. # get the new location to the list
  597. self.UpdateLocations(self.gisdbase)
  598. # seems to be used in similar context
  599. self.UpdateMapsets(os.path.join(self.gisdbase, location))
  600. self.lblocations.SetSelection(
  601. self.listOfLocations.index(location))
  602. # wizard does this as well, not sure if needed
  603. self.SetLocation(self.gisdbase, location, 'PERMANENT')
  604. # seems to be used in similar context
  605. self.OnSelectLocation(None)
  606. loc_download.Destroy()
  607. def UpdateLocations(self, dbase):
  608. """Update list of locations"""
  609. try:
  610. self.listOfLocations = GetListOfLocations(dbase)
  611. except (UnicodeEncodeError, UnicodeDecodeError) as e:
  612. GError(parent=self,
  613. message=_("Unicode error detected. "
  614. "Check your locale settings. Details: {0}").format(e),
  615. showTraceback=False)
  616. self.lblocations.Clear()
  617. self.lblocations.InsertItems(self.listOfLocations, 0)
  618. if len(self.listOfLocations) > 0:
  619. self._hideMessage()
  620. self.lblocations.SetSelection(0)
  621. else:
  622. self.lblocations.SetSelection(wx.NOT_FOUND)
  623. self._showWarning(_("No GRASS Location found in '%s'."
  624. " Create a new Location or choose different"
  625. " GRASS database directory.")
  626. % self.gisdbase)
  627. return self.listOfLocations
  628. def UpdateMapsets(self, location):
  629. """Update list of mapsets"""
  630. self.FormerMapsetSelection = wx.NOT_FOUND # for non-selectable item
  631. self.listOfMapsetsSelectable = list()
  632. self.listOfMapsets = GetListOfMapsets(self.gisdbase, location)
  633. self.lbmapsets.Clear()
  634. # disable mapset with denied permission
  635. locationName = os.path.basename(location)
  636. ret = RunCommand('g.mapset',
  637. read=True,
  638. flags='l',
  639. location=locationName,
  640. gisdbase=self.gisdbase)
  641. if ret:
  642. for line in ret.splitlines():
  643. self.listOfMapsetsSelectable += line.split(' ')
  644. else:
  645. self.SetLocation(self.gisdbase, locationName, "PERMANENT")
  646. # first run only
  647. self.listOfMapsetsSelectable = copy.copy(self.listOfMapsets)
  648. disabled = []
  649. idx = 0
  650. for mapset in self.listOfMapsets:
  651. if mapset not in self.listOfMapsetsSelectable or \
  652. get_lockfile_if_present(self.gisdbase,
  653. locationName, mapset):
  654. disabled.append(idx)
  655. idx += 1
  656. self.lbmapsets.InsertItems(self.listOfMapsets, 0, disabled=disabled)
  657. return self.listOfMapsets
  658. def OnSelectLocation(self, event):
  659. """Location selected"""
  660. if event:
  661. self.lblocations.SetSelection(event.GetIndex())
  662. if self.lblocations.GetSelection() != wx.NOT_FOUND:
  663. self.UpdateMapsets(
  664. os.path.join(
  665. self.gisdbase,
  666. self.listOfLocations[
  667. self.lblocations.GetSelection()]))
  668. else:
  669. self.listOfMapsets = []
  670. disabled = []
  671. idx = 0
  672. try:
  673. locationName = self.listOfLocations[
  674. self.lblocations.GetSelection()]
  675. except IndexError:
  676. locationName = ''
  677. for mapset in self.listOfMapsets:
  678. if mapset not in self.listOfMapsetsSelectable or \
  679. get_lockfile_if_present(self.gisdbase,
  680. locationName, mapset):
  681. disabled.append(idx)
  682. idx += 1
  683. self.lbmapsets.Clear()
  684. self.lbmapsets.InsertItems(self.listOfMapsets, 0, disabled=disabled)
  685. if len(self.listOfMapsets) > 0:
  686. self.lbmapsets.SetSelection(0)
  687. if locationName:
  688. # enable start button when location and mapset is selected
  689. self.bstart.Enable()
  690. self.bstart.SetFocus()
  691. self.bmapset.Enable()
  692. # replacing disabled choice, perhaps just mapset needed
  693. self.rename_location_button.Enable()
  694. self.delete_location_button.Enable()
  695. self.rename_mapset_button.Enable()
  696. self.delete_mapset_button.Enable()
  697. else:
  698. self.lbmapsets.SetSelection(wx.NOT_FOUND)
  699. self.bstart.Enable(False)
  700. self.bmapset.Enable(False)
  701. # this all was originally a choice, perhaps just mapset needed
  702. self.rename_location_button.Enable(False)
  703. self.delete_location_button.Enable(False)
  704. self.rename_mapset_button.Enable(False)
  705. self.delete_mapset_button.Enable(False)
  706. def OnSelectMapset(self, event):
  707. """Mapset selected"""
  708. self.lbmapsets.SetSelection(event.GetIndex())
  709. if event.GetText() not in self.listOfMapsetsSelectable:
  710. self.lbmapsets.SetSelection(self.FormerMapsetSelection)
  711. else:
  712. self.FormerMapsetSelection = event.GetIndex()
  713. event.Skip()
  714. def OnSetDatabase(self, event):
  715. """Database set"""
  716. gisdbase = self.tgisdbase.GetValue()
  717. self._hideMessage()
  718. if not os.path.exists(gisdbase):
  719. self._showError(_("Path '%s' doesn't exist.") % gisdbase)
  720. return
  721. self.gisdbase = self.tgisdbase.GetValue()
  722. self.UpdateLocations(self.gisdbase)
  723. self.OnSelectLocation(None)
  724. def OnBrowse(self, event):
  725. """'Browse' button clicked"""
  726. if not event:
  727. defaultPath = os.getenv('HOME')
  728. else:
  729. defaultPath = ""
  730. dlg = wx.DirDialog(parent=self, message=_("Choose GIS Data Directory"),
  731. defaultPath=defaultPath, style=wx.DD_DEFAULT_STYLE)
  732. if dlg.ShowModal() == wx.ID_OK:
  733. self.gisdbase = dlg.GetPath()
  734. self.tgisdbase.SetValue(self.gisdbase)
  735. self.OnSetDatabase(event)
  736. dlg.Destroy()
  737. def OnCreateMapset(self, event):
  738. """Create new mapset"""
  739. gisdbase = self.tgisdbase.GetValue()
  740. location = self.listOfLocations[self.lblocations.GetSelection()]
  741. try:
  742. mapset = create_mapset_interactively(self, gisdbase, location)
  743. if mapset:
  744. self.OnSelectLocation(None)
  745. self.lbmapsets.SetSelection(self.listOfMapsets.index(mapset))
  746. self.bstart.SetFocus()
  747. except Exception as e:
  748. GError(parent=self,
  749. message=_("Unable to create new mapset: %s") % e,
  750. showTraceback=False)
  751. def OnStart(self, event):
  752. """'Start GRASS' button clicked"""
  753. dbase = self.tgisdbase.GetValue()
  754. location = self.listOfLocations[self.lblocations.GetSelection()]
  755. mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
  756. lockfile = get_lockfile_if_present(dbase, location, mapset)
  757. if lockfile:
  758. dlg = wx.MessageDialog(
  759. parent=self,
  760. message=_(
  761. "GRASS is already running in selected mapset <%(mapset)s>\n"
  762. "(file %(lock)s found).\n\n"
  763. "Concurrent use not allowed.\n\n"
  764. "Do you want to try to remove .gislock (note that you "
  765. "need permission for this operation) and continue?") %
  766. {'mapset': mapset, 'lock': lockfile},
  767. caption=_("Lock file found"),
  768. style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
  769. ret = dlg.ShowModal()
  770. dlg.Destroy()
  771. if ret == wx.ID_YES:
  772. dlg1 = wx.MessageDialog(
  773. parent=self,
  774. message=_(
  775. "ARE YOU REALLY SURE?\n\n"
  776. "If you really are running another GRASS session doing this "
  777. "could corrupt your data. Have another look in the processor "
  778. "manager just to be sure..."),
  779. caption=_("Lock file found"),
  780. style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
  781. ret = dlg1.ShowModal()
  782. dlg1.Destroy()
  783. if ret == wx.ID_YES:
  784. try:
  785. os.remove(lockfile)
  786. except IOError as e:
  787. GError(_("Unable to remove '%(lock)s'.\n\n"
  788. "Details: %(reason)s") % {'lock': lockfile, 'reason': e})
  789. else:
  790. return
  791. else:
  792. return
  793. self.SetLocation(dbase, location, mapset)
  794. self.ExitSuccessfully()
  795. def SetLocation(self, dbase, location, mapset):
  796. SetSessionMapset(dbase, location, mapset)
  797. def ExitSuccessfully(self):
  798. self.Destroy()
  799. sys.exit(self.exit_success)
  800. def OnExit(self, event):
  801. """'Exit' button clicked"""
  802. self.Destroy()
  803. sys.exit(self.exit_user_requested)
  804. def OnHelp(self, event):
  805. """'Help' button clicked"""
  806. # help text in lib/init/helptext.html
  807. RunCommand('g.manual', entry='helptext')
  808. def OnCloseWindow(self, event):
  809. """Close window event"""
  810. event.Skip()
  811. sys.exit(self.exit_user_requested)
  812. class GListBox(ListCtrl, listmix.ListCtrlAutoWidthMixin):
  813. """Use wx.ListCtrl instead of wx.ListBox, different style for
  814. non-selectable items (e.g. mapsets with denied permission)"""
  815. def __init__(self, parent, id, size,
  816. choices, disabled=[]):
  817. ListCtrl.__init__(
  818. self, parent, id, size=size, style=wx.LC_REPORT | wx.LC_NO_HEADER |
  819. wx.LC_SINGLE_SEL | wx.BORDER_SUNKEN)
  820. listmix.ListCtrlAutoWidthMixin.__init__(self)
  821. self.InsertColumn(0, '')
  822. self.selected = wx.NOT_FOUND
  823. self._LoadData(choices, disabled)
  824. def _LoadData(self, choices, disabled=[]):
  825. """Load data into list
  826. :param choices: list of item
  827. :param disabled: list of indices of non-selectable items
  828. """
  829. idx = 0
  830. count = self.GetItemCount()
  831. for item in choices:
  832. index = self.InsertItem(count + idx, item)
  833. self.SetItem(index, 0, item)
  834. if idx in disabled:
  835. self.SetItemTextColour(idx, wx.Colour(150, 150, 150))
  836. idx += 1
  837. def Clear(self):
  838. self.DeleteAllItems()
  839. def InsertItems(self, choices, pos, disabled=[]):
  840. self._LoadData(choices, disabled)
  841. def SetSelection(self, item, force=False):
  842. if item != wx.NOT_FOUND and \
  843. (platform.system() != 'Windows' or force):
  844. # Windows -> FIXME
  845. self.SetItemState(
  846. item,
  847. wx.LIST_STATE_SELECTED,
  848. wx.LIST_STATE_SELECTED)
  849. self.selected = item
  850. def GetSelection(self):
  851. return self.selected
  852. class StartUp(wx.App):
  853. """Start-up application"""
  854. def OnInit(self):
  855. StartUp = GRASSStartup()
  856. StartUp.CenterOnScreen()
  857. self.SetTopWindow(StartUp)
  858. StartUp.Show()
  859. StartUp.SuggestDatabase()
  860. return 1
  861. if __name__ == "__main__":
  862. if os.getenv("GISBASE") is None:
  863. sys.exit("Failed to start GUI, GRASS GIS is not running.")
  864. GRASSStartUp = StartUp(0)
  865. GRASSStartUp.MainLoop()