gis_set.py 44 KB

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