gis_set.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  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-2012 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. ### i18N
  23. import gettext
  24. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  25. if __name__ == "__main__":
  26. sys.path.append(os.path.join(os.getenv('GISBASE'), 'etc', 'gui', 'wxpython'))
  27. from core import globalvar
  28. import wx
  29. import wx.lib.mixins.listctrl as listmix
  30. import wx.lib.scrolledpanel as scrolled
  31. from grass.script import core as grass
  32. from gui_core.ghelp import HelpFrame
  33. from core.gcmd import GMessage, GError, DecodeString, RunCommand, GWarning
  34. from core.utils import GetListOfLocations, GetListOfMapsets
  35. from location_wizard.dialogs import RegionDef
  36. sys.stderr = codecs.getwriter('utf8')(sys.stderr)
  37. class GRASSStartup(wx.Frame):
  38. """!GRASS start-up screen"""
  39. def __init__(self, parent = None, id = wx.ID_ANY, 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. self.panel = scrolled.ScrolledPanel(parent = self, id = wx.ID_ANY)
  55. # i18N
  56. import gettext
  57. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  58. #
  59. # graphical elements
  60. #
  61. # image
  62. try:
  63. name = os.path.join(globalvar.ETCDIR, "gui", "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.EmptyBitmap(530,150))
  69. # labels
  70. ### crashes when LOCATION doesn't exist
  71. versionFile = open(os.path.join(globalvar.ETCDIR, "VERSIONNUMBER"))
  72. grassVersion = versionFile.readline().split(' ')[0].rstrip('\n')
  73. versionFile.close()
  74. self.select_box = wx.StaticBox (parent = self.panel, id = wx.ID_ANY,
  75. label = " %s " % _("Choose project location and mapset"))
  76. self.manage_box = wx.StaticBox (parent = self.panel, id = wx.ID_ANY,
  77. label = " %s " % _("Manage"))
  78. self.lwelcome = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  79. label = _("Welcome to GRASS GIS %s\n"
  80. "The world's leading open source GIS") % grassVersion,
  81. style = wx.ALIGN_CENTRE)
  82. self.ltitle = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  83. label = _("Select an existing project location and mapset\n"
  84. "or define a new location"),
  85. style = wx.ALIGN_CENTRE)
  86. self.ldbase = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  87. label = _("GIS Data Directory:"))
  88. self.llocation = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  89. label = _("Project location\n(projection/coordinate system)"),
  90. style = wx.ALIGN_CENTRE)
  91. self.lmapset = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  92. label = _("Accessible mapsets\n(directories of GIS files)"),
  93. style = wx.ALIGN_CENTRE)
  94. self.lcreate = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  95. label = _("Create new mapset\nin selected location"),
  96. style = wx.ALIGN_CENTRE)
  97. self.ldefine = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  98. label = _("Define new location"),
  99. style = wx.ALIGN_CENTRE)
  100. self.lmanageloc = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  101. label = _("Rename/delete selected\nmapset or location"),
  102. style = wx.ALIGN_CENTRE)
  103. # buttons
  104. self.bstart = wx.Button(parent = self.panel, id = wx.ID_ANY,
  105. label = _("Start &GRASS"))
  106. self.bstart.SetDefault()
  107. self.bexit = wx.Button(parent = self.panel, id = wx.ID_EXIT)
  108. self.bstart.SetMinSize((180, self.bexit.GetSize()[1]))
  109. self.bhelp = wx.Button(parent = self.panel, id = wx.ID_HELP)
  110. self.bbrowse = wx.Button(parent = self.panel, id = wx.ID_ANY,
  111. label = _("&Browse"))
  112. self.bmapset = wx.Button(parent = self.panel, id = wx.ID_ANY,
  113. label = _("&Create mapset"))
  114. self.bwizard = wx.Button(parent = self.panel, id = wx.ID_ANY,
  115. label = _("&Location wizard"))
  116. self.bwizard.SetToolTipString(_("Start location wizard."
  117. " After location is created successfully,"
  118. " GRASS session is started."))
  119. self.manageloc = wx.Choice(parent = self.panel, id = wx.ID_ANY,
  120. choices = [_('Rename mapset'), _('Rename location'),
  121. _('Delete mapset'), _('Delete location')])
  122. self.manageloc.SetSelection(0)
  123. # textinputs
  124. self.tgisdbase = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY, value = "", size = (300, -1),
  125. style = wx.TE_PROCESS_ENTER)
  126. # Locations
  127. self.lblocations = GListBox(parent = self.panel,
  128. id = wx.ID_ANY, size = (180, 200),
  129. choices = self.listOfLocations)
  130. self.lblocations.SetColumnWidth(0, 180)
  131. # TODO: sort; but keep PERMANENT on top of list
  132. # Mapsets
  133. self.lbmapsets = GListBox(parent = self.panel,
  134. id = wx.ID_ANY, size = (180, 200),
  135. choices = self.listOfMapsets)
  136. self.lbmapsets.SetColumnWidth(0, 180)
  137. # layout & properties
  138. self._set_properties()
  139. self._do_layout()
  140. # events
  141. self.bbrowse.Bind(wx.EVT_BUTTON, self.OnBrowse)
  142. self.bstart.Bind(wx.EVT_BUTTON, self.OnStart)
  143. self.bexit.Bind(wx.EVT_BUTTON, self.OnExit)
  144. self.bhelp.Bind(wx.EVT_BUTTON, self.OnHelp)
  145. self.bmapset.Bind(wx.EVT_BUTTON, self.OnCreateMapset)
  146. self.bwizard.Bind(wx.EVT_BUTTON, self.OnWizard)
  147. self.manageloc.Bind(wx.EVT_CHOICE, self.OnManageLoc)
  148. self.lblocations.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectLocation)
  149. self.lbmapsets.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectMapset)
  150. self.lbmapsets.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnStart)
  151. self.tgisdbase.Bind(wx.EVT_TEXT_ENTER, self.OnSetDatabase)
  152. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  153. def _set_properties(self):
  154. """!Set frame properties"""
  155. self.SetTitle(_("Welcome to GRASS GIS"))
  156. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, "grass.ico"),
  157. wx.BITMAP_TYPE_ICO))
  158. self.lwelcome.SetForegroundColour(wx.Colour(35, 142, 35))
  159. self.lwelcome.SetFont(wx.Font(13, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
  160. self.bstart.SetForegroundColour(wx.Colour(35, 142, 35))
  161. self.bstart.SetToolTipString(_("Enter GRASS session"))
  162. self.bstart.Enable(False)
  163. self.bmapset.Enable(False)
  164. self.manageloc.Enable(False)
  165. # set database
  166. if not self.gisdbase:
  167. # sets an initial path for gisdbase if nothing in GISRC
  168. if os.path.isdir(os.getenv("HOME")):
  169. self.gisdbase = os.getenv("HOME")
  170. else:
  171. self.gisdbase = os.getcwd()
  172. try:
  173. self.tgisdbase.SetValue(self.gisdbase)
  174. except UnicodeDecodeError:
  175. wx.MessageBox(parent = self, caption = _("Error"),
  176. message = _("Unable to set GRASS database. "
  177. "Check your locale settings."),
  178. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  179. self.OnSetDatabase(None)
  180. location = self.GetRCValue("LOCATION_NAME")
  181. if location == "<UNKNOWN>":
  182. return
  183. if not os.path.isdir(os.path.join(self.gisdbase, location)):
  184. location = None
  185. # list of locations
  186. self.UpdateLocations(self.gisdbase)
  187. try:
  188. self.lblocations.SetSelection(self.listOfLocations.index(location),
  189. force = True)
  190. self.lblocations.EnsureVisible(self.listOfLocations.index(location))
  191. except ValueError:
  192. sys.stderr.write(_("ERROR: Location <%s> not found\n") % self.GetRCValue("LOCATION_NAME"))
  193. if len(self.listOfLocations) > 0:
  194. self.lblocations.SetSelection(0, force = True)
  195. self.lblocations.EnsureVisible(0)
  196. location = self.listOfLocations[0]
  197. else:
  198. return
  199. # list of mapsets
  200. self.UpdateMapsets(os.path.join(self.gisdbase, location))
  201. mapset = self.GetRCValue("MAPSET")
  202. if mapset:
  203. try:
  204. self.lbmapsets.SetSelection(self.listOfMapsets.index(mapset),
  205. force = True)
  206. self.lbmapsets.EnsureVisible(self.listOfMapsets.index(mapset))
  207. except ValueError:
  208. sys.stderr.write(_("ERROR: Mapset <%s> not found\n") % mapset)
  209. self.lbmapsets.SetSelection(0, force = True)
  210. self.lbmapsets.EnsureVisible(0)
  211. def _do_layout(self):
  212. sizer = wx.BoxSizer(wx.VERTICAL)
  213. dbase_sizer = wx.BoxSizer(wx.HORIZONTAL)
  214. location_sizer = wx.BoxSizer(wx.HORIZONTAL)
  215. select_boxsizer = wx.StaticBoxSizer(self.select_box, wx.VERTICAL)
  216. select_sizer = wx.FlexGridSizer(rows = 2, cols = 2, vgap = 4, hgap = 4)
  217. select_sizer.AddGrowableRow(1)
  218. select_sizer.AddGrowableCol(0)
  219. select_sizer.AddGrowableCol(1)
  220. manage_sizer = wx.StaticBoxSizer(self.manage_box, wx.VERTICAL)
  221. btns_sizer = wx.BoxSizer(wx.HORIZONTAL)
  222. # gis data directory
  223. dbase_sizer.Add(item = self.ldbase, proportion = 0,
  224. flag = wx.ALIGN_CENTER_VERTICAL |
  225. wx.ALIGN_CENTER_HORIZONTAL | wx.ALL,
  226. border = 3)
  227. dbase_sizer.Add(item = self.tgisdbase, proportion = 1,
  228. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  229. border = 3)
  230. dbase_sizer.Add(item = self.bbrowse, proportion = 0,
  231. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  232. border = 3)
  233. # select sizer
  234. select_sizer.Add(item = self.llocation, proportion = 0,
  235. flag = wx.ALIGN_CENTER_HORIZONTAL | wx.ALL,
  236. border = 3)
  237. select_sizer.Add(item = self.lmapset, proportion = 0,
  238. flag = wx.ALIGN_CENTER_HORIZONTAL | wx.ALL,
  239. border = 3)
  240. select_sizer.Add(item = self.lblocations, proportion = 1,
  241. flag = wx.EXPAND)
  242. select_sizer.Add(item = self.lbmapsets, proportion = 1,
  243. flag = wx.EXPAND)
  244. select_boxsizer.Add(item = select_sizer, proportion = 1,
  245. flag = wx.EXPAND)
  246. # define new location and mapset
  247. manage_sizer.Add(item = self.ldefine, proportion = 0,
  248. flag = wx.ALIGN_CENTER_HORIZONTAL | wx.ALL,
  249. border = 3)
  250. manage_sizer.Add(item = self.bwizard, proportion = 0,
  251. flag = wx.ALIGN_CENTER_HORIZONTAL | wx.BOTTOM,
  252. border = 5)
  253. manage_sizer.Add(item = self.lcreate, proportion = 0,
  254. flag = wx.ALIGN_CENTER_HORIZONTAL | wx.ALL,
  255. border = 3)
  256. manage_sizer.Add(item = self.bmapset, proportion = 0,
  257. flag = wx.ALIGN_CENTER_HORIZONTAL | wx.BOTTOM,
  258. border = 5)
  259. manage_sizer.Add(item = self.lmanageloc, proportion = 0,
  260. flag = wx.ALIGN_CENTER_HORIZONTAL | wx.ALL,
  261. border = 3)
  262. manage_sizer.Add(item = self.manageloc, proportion = 0,
  263. flag = wx.ALIGN_CENTER_HORIZONTAL | wx.BOTTOM,
  264. border = 5)
  265. # location sizer
  266. location_sizer.Add(item = select_boxsizer, proportion = 1,
  267. flag = wx.LEFT | wx.RIGHT | wx.EXPAND,
  268. border = 3)
  269. location_sizer.Add(item = manage_sizer, proportion = 0,
  270. flag = wx.RIGHT | wx.EXPAND,
  271. border = 3)
  272. # buttons
  273. btns_sizer.Add(item = self.bstart, proportion = 0,
  274. flag = wx.ALIGN_CENTER_HORIZONTAL |
  275. wx.ALIGN_CENTER_VERTICAL |
  276. wx.ALL,
  277. border = 5)
  278. btns_sizer.Add(item = self.bexit, proportion = 0,
  279. flag = wx.ALIGN_CENTER_HORIZONTAL |
  280. wx.ALIGN_CENTER_VERTICAL |
  281. wx.ALL,
  282. border = 5)
  283. btns_sizer.Add(item = self.bhelp, proportion = 0,
  284. flag = wx.ALIGN_CENTER_HORIZONTAL |
  285. wx.ALIGN_CENTER_VERTICAL |
  286. wx.ALL,
  287. border = 5)
  288. # main sizer
  289. sizer.Add(item = self.hbitmap,
  290. proportion = 0,
  291. flag = wx.ALIGN_CENTER_VERTICAL |
  292. wx.ALIGN_CENTER_HORIZONTAL |
  293. wx.ALL,
  294. border = 3) # image
  295. sizer.Add(item = self.lwelcome, # welcome message
  296. proportion = 0,
  297. flag = wx.ALIGN_CENTER_VERTICAL |
  298. wx.ALIGN_CENTER_HORIZONTAL |
  299. wx.BOTTOM,
  300. border = 5)
  301. sizer.Add(item = self.ltitle, # title
  302. proportion = 0,
  303. flag = wx.ALIGN_CENTER_VERTICAL |
  304. wx.ALIGN_CENTER_HORIZONTAL)
  305. sizer.Add(item = dbase_sizer, proportion = 0,
  306. flag = wx.ALIGN_CENTER_HORIZONTAL |
  307. wx.RIGHT | wx.LEFT | wx.EXPAND,
  308. border = 20) # GISDBASE setting
  309. sizer.Add(item = location_sizer, proportion = 1,
  310. flag = wx.RIGHT | wx.LEFT | wx.EXPAND,
  311. border = 1)
  312. sizer.Add(item = btns_sizer, proportion = 0,
  313. flag = wx.ALIGN_CENTER_VERTICAL |
  314. wx.ALIGN_CENTER_HORIZONTAL |
  315. wx.RIGHT | wx.LEFT,
  316. border = 1)
  317. self.panel.SetAutoLayout(True)
  318. self.panel.SetSizer(sizer)
  319. sizer.Fit(self.panel)
  320. sizer.SetSizeHints(self)
  321. self.Layout()
  322. def _readGisRC(self):
  323. """!Read variables from $HOME/.grass7/rc file
  324. """
  325. grassrc = {}
  326. gisrc = os.getenv("GISRC")
  327. if gisrc and os.path.isfile(gisrc):
  328. try:
  329. rc = open(gisrc, "r")
  330. for line in rc.readlines():
  331. try:
  332. key, val = line.split(":", 1)
  333. except ValueError, e:
  334. sys.stderr.write(_('Invalid line in GISRC file (%s):%s\n' % \
  335. (e, line)))
  336. grassrc[key.strip()] = DecodeString(val.strip())
  337. finally:
  338. rc.close()
  339. return grassrc
  340. def GetRCValue(self, value):
  341. """!Return GRASS variable (read from GISRC)
  342. """
  343. if self.grassrc.has_key(value):
  344. return self.grassrc[value]
  345. else:
  346. return None
  347. def OnWizard(self, event):
  348. """!Location wizard started"""
  349. from location_wizard.wizard import LocationWizard
  350. gWizard = LocationWizard(parent = self,
  351. grassdatabase = self.tgisdbase.GetValue())
  352. if gWizard.location != None:
  353. self.tgisdbase.SetValue(gWizard.grassdatabase)
  354. self.OnSetDatabase(None)
  355. self.UpdateMapsets(os.path.join(self.gisdbase, gWizard.location))
  356. self.lblocations.SetSelection(self.listOfLocations.index(gWizard.location))
  357. self.lbmapsets.SetSelection(0)
  358. self.SetLocation(self.gisdbase, gWizard.location, 'PERMANENT')
  359. if gWizard.georeffile:
  360. message = _("Do you want to import file <%(name)s> to created location? "
  361. "Default region will be set to match imported map.") % {'name': gWizard.georeffile}
  362. dlg = wx.MessageDialog(parent = self,
  363. message = message,
  364. caption = _("Import data?"),
  365. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  366. dlg.CenterOnScreen()
  367. if dlg.ShowModal() == wx.ID_YES:
  368. self.ImportFile(gWizard.georeffile)
  369. else:
  370. self.SetDefaultRegion(location = gWizard.location)
  371. dlg.Destroy()
  372. else:
  373. self.SetDefaultRegion(location = gWizard.location)
  374. self.ExitSuccessfully()
  375. def SetDefaultRegion(self, location):
  376. """!Asks to set default region."""
  377. dlg = wx.MessageDialog(parent = self,
  378. message = _("Do you want to set the default "
  379. "region extents and resolution now?"),
  380. caption = _("Location <%s> created") % location,
  381. style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  382. dlg.CenterOnScreen()
  383. if dlg.ShowModal() == wx.ID_YES:
  384. dlg.Destroy()
  385. defineRegion = RegionDef(self, location = location)
  386. defineRegion.CenterOnScreen()
  387. defineRegion.ShowModal()
  388. defineRegion.Destroy()
  389. else:
  390. dlg.Destroy()
  391. def ImportFile(self, filePath):
  392. """!Tries to import file as vector or raster.
  393. If successfull sets default region from imported map.
  394. """
  395. mapName = os.path.splitext(os.path.basename(filePath))[0]
  396. vectors = RunCommand('v.in.ogr', dsn = filePath, flags = 'l',
  397. read = True)
  398. print vectors, mapName in vectors
  399. wx.BeginBusyCursor()
  400. wx.Yield()
  401. if mapName in vectors:
  402. # vector detected
  403. returncode, error = RunCommand('v.in.ogr', dsn = filePath, output = mapName,
  404. getErrorMsg = True)
  405. else:
  406. returncode, error = RunCommand('r.in.gdal', input = filePath, output = mapName,
  407. getErrorMsg = True)
  408. wx.EndBusyCursor()
  409. if returncode != 0:
  410. GError(parent = self,
  411. message = _("Import of <%(name)s> failed.\n"
  412. "Reason: %(msg)s") % ({'name': filePath, 'msg': error}))
  413. else:
  414. GMessage(message = _("Data <%(name)s> imported successfully.") % {'name': filePath},
  415. parent = self)
  416. if not grass.find_file(element = 'cell', name = mapName)['fullname'] and \
  417. not grass.find_file(element = 'vector', name = mapName)['fullname']:
  418. GError(parent = self,
  419. message = _("Map <%s> not found.") % mapName)
  420. else:
  421. if mapName in vectors:
  422. args = {'vect' : mapName}
  423. else:
  424. args = {'rast' : mapName}
  425. RunCommand('g.region', flags = 's', parent = self, **args)
  426. def OnManageLoc(self, event):
  427. """!Location management choice control handler
  428. """
  429. sel = event.GetSelection()
  430. if sel == 0:
  431. self.RenameMapset()
  432. elif sel == 1:
  433. self.RenameLocation()
  434. elif sel == 2:
  435. self.DeleteMapset()
  436. elif sel == 3:
  437. self.DeleteLocation()
  438. event.Skip()
  439. def RenameMapset(self):
  440. """!Rename selected mapset
  441. """
  442. location = self.listOfLocations[self.lblocations.GetSelection()]
  443. mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
  444. if mapset == 'PERMANENT':
  445. GMessage(parent = self,
  446. message = _('Mapset <PERMANENT> is required for valid GRASS location.\n\n'
  447. 'This mapset cannot be renamed.'))
  448. return
  449. dlg = wx.TextEntryDialog(parent = self,
  450. message = _('Current name: %s\n\nEnter new name:') % mapset,
  451. caption = _('Rename selected mapset'))
  452. if dlg.ShowModal() == wx.ID_OK:
  453. newmapset = dlg.GetValue()
  454. if newmapset == mapset:
  455. dlg.Destroy()
  456. return
  457. if newmapset in self.listOfMapsets:
  458. wx.MessageBox(parent = self,
  459. caption = _('Message'),
  460. message = _('Unable to rename mapset.\n\n'
  461. 'Mapset <%s> already exists in location.') % newmapset,
  462. style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  463. else:
  464. try:
  465. os.rename(os.path.join(self.gisdbase, location, mapset),
  466. os.path.join(self.gisdbase, location, newmapset))
  467. self.OnSelectLocation(None)
  468. self.lbmapsets.SetSelection(self.listOfMapsets.index(newmapset))
  469. except StandardError, e:
  470. wx.MessageBox(parent = self,
  471. caption = _('Error'),
  472. message = _('Unable to rename mapset.\n\n%s') % e,
  473. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  474. dlg.Destroy()
  475. def RenameLocation(self):
  476. """!Rename selected location
  477. """
  478. location = self.listOfLocations[self.lblocations.GetSelection()]
  479. dlg = wx.TextEntryDialog(parent = self,
  480. message = _('Current name: %s\n\nEnter new name:') % location,
  481. caption = _('Rename selected location'))
  482. if dlg.ShowModal() == wx.ID_OK:
  483. newlocation = dlg.GetValue()
  484. if newlocation == location:
  485. dlg.Destroy()
  486. return
  487. if newlocation in self.listOfLocations:
  488. wx.MessageBox(parent = self,
  489. caption = _('Message'),
  490. message = _('Unable to rename location.\n\n'
  491. 'Location <%s> already exists in GRASS database.') % newlocation,
  492. style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  493. else:
  494. try:
  495. os.rename(os.path.join(self.gisdbase, location),
  496. os.path.join(self.gisdbase, newlocation))
  497. self.UpdateLocations(self.gisdbase)
  498. self.lblocations.SetSelection(self.listOfLocations.index(newlocation))
  499. self.UpdateMapsets(newlocation)
  500. except StandardError, e:
  501. wx.MessageBox(parent = self,
  502. caption = _('Error'),
  503. message = _('Unable to rename location.\n\n%s') % e,
  504. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  505. dlg.Destroy()
  506. def DeleteMapset(self):
  507. """!Delete selected mapset
  508. """
  509. location = self.listOfLocations[self.lblocations.GetSelection()]
  510. mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
  511. if mapset == 'PERMANENT':
  512. GMessage(parent = self,
  513. message = _('Mapset <PERMANENT> is required for valid GRASS location.\n\n'
  514. 'This mapset cannot be deleted.'))
  515. return
  516. dlg = wx.MessageDialog(parent = self, message = _("Do you want to continue with deleting mapset <%(mapset)s> "
  517. "from location <%(location)s>?\n\n"
  518. "ALL MAPS included in this mapset will be "
  519. "PERMANENTLY DELETED!") % {'mapset' : mapset,
  520. 'location' : location},
  521. caption = _("Delete selected mapset"),
  522. style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  523. if dlg.ShowModal() == wx.ID_YES:
  524. try:
  525. shutil.rmtree(os.path.join(self.gisdbase, location, mapset))
  526. self.OnSelectLocation(None)
  527. self.lbmapsets.SetSelection(0)
  528. except:
  529. wx.MessageBox(message = _('Unable to delete mapset'))
  530. dlg.Destroy()
  531. def DeleteLocation(self):
  532. """
  533. Delete selected location
  534. """
  535. location = self.listOfLocations[self.lblocations.GetSelection()]
  536. dlg = wx.MessageDialog(parent = self, message = _("Do you want to continue with deleting "
  537. "location <%s>?\n\n"
  538. "ALL MAPS included in this location will be "
  539. "PERMANENTLY DELETED!") % (location),
  540. caption = _("Delete selected location"),
  541. style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  542. if dlg.ShowModal() == wx.ID_YES:
  543. try:
  544. shutil.rmtree(os.path.join(self.gisdbase, location))
  545. self.UpdateLocations(self.gisdbase)
  546. self.lblocations.SetSelection(0)
  547. self.OnSelectLocation(None)
  548. self.lbmapsets.SetSelection(0)
  549. except:
  550. wx.MessageBox(message = _('Unable to delete location'))
  551. dlg.Destroy()
  552. def UpdateLocations(self, dbase):
  553. """!Update list of locations"""
  554. try:
  555. self.listOfLocations = GetListOfLocations(dbase)
  556. except UnicodeEncodeError:
  557. wx.MessageBox(parent = self, caption = _("Error"),
  558. message = _("Unable to set GRASS database. "
  559. "Check your locale settings."),
  560. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  561. self.lblocations.Clear()
  562. self.lblocations.InsertItems(self.listOfLocations, 0)
  563. if len(self.listOfLocations) > 0:
  564. self.lblocations.SetSelection(0)
  565. else:
  566. self.lblocations.SetSelection(wx.NOT_FOUND)
  567. return self.listOfLocations
  568. def UpdateMapsets(self, location):
  569. """!Update list of mapsets"""
  570. self.FormerMapsetSelection = wx.NOT_FOUND # for non-selectable item
  571. self.listOfMapsetsSelectable = list()
  572. self.listOfMapsets = GetListOfMapsets(self.gisdbase, location)
  573. self.lbmapsets.Clear()
  574. # disable mapset with denied permission
  575. locationName = os.path.basename(location)
  576. ret = RunCommand('g.mapset',
  577. read = True,
  578. flags = 'l',
  579. location = locationName,
  580. gisdbase = self.gisdbase)
  581. if ret:
  582. for line in ret.splitlines():
  583. self.listOfMapsetsSelectable += line.split(' ')
  584. else:
  585. RunCommand("g.gisenv",
  586. set = "GISDBASE=%s" % self.gisdbase)
  587. RunCommand("g.gisenv",
  588. set = "LOCATION_NAME=%s" % locationName)
  589. RunCommand("g.gisenv",
  590. set = "MAPSET=PERMANENT")
  591. # first run only
  592. self.listOfMapsetsSelectable = copy.copy(self.listOfMapsets)
  593. disabled = []
  594. idx = 0
  595. for mapset in self.listOfMapsets:
  596. if mapset not in self.listOfMapsetsSelectable or \
  597. os.path.isfile(os.path.join(self.gisdbase,
  598. locationName,
  599. mapset, ".gislock")):
  600. disabled.append(idx)
  601. idx += 1
  602. self.lbmapsets.InsertItems(self.listOfMapsets, 0, disabled = disabled)
  603. return self.listOfMapsets
  604. def OnSelectLocation(self, event):
  605. """!Location selected"""
  606. if event:
  607. self.lblocations.SetSelection(event.GetIndex())
  608. if self.lblocations.GetSelection() != wx.NOT_FOUND:
  609. self.UpdateMapsets(os.path.join(self.gisdbase,
  610. self.listOfLocations[self.lblocations.GetSelection()]))
  611. else:
  612. self.listOfMapsets = []
  613. disabled = []
  614. idx = 0
  615. try:
  616. locationName = self.listOfLocations[self.lblocations.GetSelection()]
  617. except IndexError:
  618. locationName = ''
  619. for mapset in self.listOfMapsets:
  620. if mapset not in self.listOfMapsetsSelectable or \
  621. os.path.isfile(os.path.join(self.gisdbase,
  622. locationName,
  623. mapset, ".gislock")):
  624. disabled.append(idx)
  625. idx += 1
  626. self.lbmapsets.Clear()
  627. self.lbmapsets.InsertItems(self.listOfMapsets, 0, disabled = disabled)
  628. if len(self.listOfMapsets) > 0:
  629. self.lbmapsets.SetSelection(0)
  630. if locationName:
  631. # enable start button when location and mapset is selected
  632. self.bstart.Enable()
  633. self.bmapset.Enable()
  634. self.manageloc.Enable()
  635. else:
  636. self.lbmapsets.SetSelection(wx.NOT_FOUND)
  637. self.bstart.Enable(False)
  638. self.bmapset.Enable(False)
  639. self.manageloc.Enable(False)
  640. def OnSelectMapset(self, event):
  641. """!Mapset selected"""
  642. self.lbmapsets.SetSelection(event.GetIndex())
  643. if event.GetText() not in self.listOfMapsetsSelectable:
  644. self.lbmapsets.SetSelection(self.FormerMapsetSelection)
  645. else:
  646. self.FormerMapsetSelection = event.GetIndex()
  647. event.Skip()
  648. def OnSetDatabase(self, event):
  649. """!Database set"""
  650. self.gisdbase = self.tgisdbase.GetValue()
  651. self.UpdateLocations(self.gisdbase)
  652. self.OnSelectLocation(None)
  653. def OnBrowse(self, event):
  654. """'Browse' button clicked"""
  655. if not event:
  656. defaultPath = os.getenv('HOME')
  657. else:
  658. defaultPath = ""
  659. dlg = wx.DirDialog(parent = self, message = _("Choose GIS Data Directory"),
  660. defaultPath = defaultPath, style = wx.DD_DEFAULT_STYLE)
  661. if dlg.ShowModal() == wx.ID_OK:
  662. self.gisdbase = dlg.GetPath()
  663. self.tgisdbase.SetValue(self.gisdbase)
  664. self.OnSetDatabase(event)
  665. dlg.Destroy()
  666. def OnCreateMapset(self,event):
  667. """!Create new mapset"""
  668. self.gisdbase = self.tgisdbase.GetValue()
  669. location = self.listOfLocations[self.lblocations.GetSelection()]
  670. dlg = wx.TextEntryDialog(parent = self,
  671. message = _('Enter name for new mapset:'),
  672. caption = _('Create new mapset'))
  673. if dlg.ShowModal() == wx.ID_OK:
  674. mapset = dlg.GetValue()
  675. if mapset in self.listOfMapsets:
  676. GMessage(parent = self,
  677. message = _("Mapset <%s> already exists.") % mapset)
  678. return
  679. if mapset.lower() == 'ogr':
  680. dlg1 = wx.MessageDialog(parent = self,
  681. message = _("Mapset <%s> is reserved for direct "
  682. "read access to OGR layers. Please consider to use "
  683. "another name for your mapset.\n\n"
  684. "Are you really sure that you want to create this mapset?") % mapset,
  685. caption = _("Reserved mapset name"),
  686. style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  687. ret = dlg1.ShowModal()
  688. dlg1.Destroy()
  689. if ret == wx.ID_NO:
  690. dlg.Destroy()
  691. return
  692. try:
  693. os.mkdir(os.path.join(self.gisdbase, location, mapset))
  694. # copy WIND file and its permissions from PERMANENT and set permissions to u+rw,go+r
  695. shutil.copy(os.path.join(self.gisdbase, location, 'PERMANENT', 'WIND'),
  696. os.path.join(self.gisdbase, location, mapset))
  697. # os.chmod(os.path.join(database,location,mapset,'WIND'), 0644)
  698. self.OnSelectLocation(None)
  699. self.lbmapsets.SetSelection(self.listOfMapsets.index(mapset))
  700. except StandardError, e:
  701. GError(parent = self,
  702. message = _("Unable to create new mapset: %s") % e,
  703. showTraceback = False)
  704. return False
  705. dlg.Destroy()
  706. self.bstart.SetFocus()
  707. return True
  708. def OnStart(self, event):
  709. """'Start GRASS' button clicked"""
  710. dbase = self.tgisdbase.GetValue()
  711. location = self.listOfLocations[self.lblocations.GetSelection()]
  712. mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
  713. lockfile = os.path.join(dbase, location, mapset, '.gislock')
  714. if os.path.isfile(lockfile):
  715. dlg = wx.MessageDialog(parent = self,
  716. message = _("GRASS is already running in selected mapset <%(mapset)s>\n"
  717. "(file %(lock)s found).\n\n"
  718. "Concurrent use not allowed.\n\n"
  719. "Do you want to try to remove .gislock (note that you "
  720. "need permission for this operation) and continue?") %
  721. { 'mapset' : mapset, 'lock' : lockfile },
  722. caption = _("Lock file found"),
  723. style = wx.YES_NO | wx.NO_DEFAULT |
  724. wx.ICON_QUESTION | wx.CENTRE)
  725. ret = dlg.ShowModal()
  726. dlg.Destroy()
  727. if ret == wx.ID_YES:
  728. dlg1 = wx.MessageDialog(parent = self,
  729. message = _("ARE YOU REALLY SURE?\n\n"
  730. "If you really are running another GRASS session doing this "
  731. "could corrupt your data. Have another look in the processor "
  732. "manager just to be sure..."),
  733. caption = _("Lock file found"),
  734. style = wx.YES_NO | wx.NO_DEFAULT |
  735. wx.ICON_QUESTION | wx.CENTRE)
  736. ret = dlg1.ShowModal()
  737. dlg1.Destroy()
  738. if ret == wx.ID_YES:
  739. try:
  740. os.remove(lockfile)
  741. except IOError, e:
  742. GError(_("Unable to remove '%(lock)s'.\n\n"
  743. "Details: %(reason)s") % { 'lock' : lockfile, 'reason' : e})
  744. else:
  745. return
  746. else:
  747. return
  748. self.SetLocation(dbase, location, mapset)
  749. self.ExitSuccessfully()
  750. def SetLocation(self, dbase, location, mapset):
  751. RunCommand("g.gisenv",
  752. set = "GISDBASE=%s" % dbase)
  753. RunCommand("g.gisenv",
  754. set = "LOCATION_NAME=%s" % location)
  755. RunCommand("g.gisenv",
  756. set = "MAPSET=%s" % mapset)
  757. def ExitSuccessfully(self):
  758. self.Destroy()
  759. sys.exit(0)
  760. def OnExit(self, event):
  761. """'Exit' button clicked"""
  762. self.Destroy()
  763. sys.exit(2)
  764. def OnHelp(self, event):
  765. """'Help' button clicked"""
  766. # help text in lib/init/helptext.html
  767. RunCommand('g.manual', entry = 'helptext')
  768. def OnCloseWindow(self, event):
  769. """!Close window event"""
  770. event.Skip()
  771. sys.exit(2)
  772. class GListBox(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin):
  773. """!Use wx.ListCtrl instead of wx.ListBox, different style for
  774. non-selectable items (e.g. mapsets with denied permission)"""
  775. def __init__(self, parent, id, size,
  776. choices, disabled = []):
  777. wx.ListCtrl.__init__(self, parent, id, size = size,
  778. style = wx.LC_REPORT | wx.LC_NO_HEADER | wx.LC_SINGLE_SEL |
  779. wx.BORDER_SUNKEN)
  780. listmix.ListCtrlAutoWidthMixin.__init__(self)
  781. self.InsertColumn(0, '')
  782. self.selected = wx.NOT_FOUND
  783. self._LoadData(choices, disabled)
  784. def _LoadData(self, choices, disabled = []):
  785. """!Load data into list
  786. @param choices list of item
  787. @param disabled list of indeces of non-selectable items
  788. """
  789. idx = 0
  790. for item in choices:
  791. index = self.InsertStringItem(sys.maxint, item)
  792. self.SetStringItem(index, 0, item)
  793. if idx in disabled:
  794. self.SetItemTextColour(idx, wx.Colour(150, 150, 150))
  795. idx += 1
  796. def Clear(self):
  797. self.DeleteAllItems()
  798. def InsertItems(self, choices, pos, disabled = []):
  799. self._LoadData(choices, disabled)
  800. def SetSelection(self, item, force = False):
  801. if item != wx.NOT_FOUND and \
  802. (platform.system() != 'Windows' or force):
  803. ### Windows -> FIXME
  804. self.SetItemState(item, wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED)
  805. self.selected = item
  806. def GetSelection(self):
  807. return self.selected
  808. class StartUp(wx.App):
  809. """!Start-up application"""
  810. def OnInit(self):
  811. wx.InitAllImageHandlers()
  812. StartUp = GRASSStartup()
  813. StartUp.CenterOnScreen()
  814. self.SetTopWindow(StartUp)
  815. StartUp.Show()
  816. if StartUp.GetRCValue("LOCATION_NAME") == "<UNKNOWN>":
  817. wx.MessageBox(parent = StartUp,
  818. caption = _('Starting GRASS for the first time'),
  819. message = _('GRASS needs a directory in which to store its data. '
  820. 'Create one now if you have not already done so. '
  821. 'A popular choice is "grassdata", located in '
  822. 'your home directory.'),
  823. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  824. StartUp.OnBrowse(None)
  825. return 1
  826. if __name__ == "__main__":
  827. if os.getenv("GISBASE") is None:
  828. sys.exit("Failed to start GUI, GRASS GIS is not running.")
  829. import gettext
  830. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  831. GRASSStartUp = StartUp(0)
  832. GRASSStartUp.MainLoop()