ii2t_gis_set.py 44 KB

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