gis_set.py 44 KB

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