ii2t_gis_set.py 44 KB

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