gis_set.py 45 KB

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