gis_set.py 47 KB

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