gis_set.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  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-2013 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. wx.BeginBusyCursor()
  399. wx.Yield()
  400. if mapName in vectors:
  401. # vector detected
  402. returncode, error = RunCommand('v.in.ogr', dsn = filePath, output = mapName,
  403. getErrorMsg = True)
  404. else:
  405. returncode, error = RunCommand('r.in.gdal', input = filePath, output = mapName,
  406. getErrorMsg = True)
  407. wx.EndBusyCursor()
  408. if returncode != 0:
  409. GError(parent = self,
  410. message = _("Import of <%(name)s> failed.\n"
  411. "Reason: %(msg)s") % ({'name': filePath, 'msg': error}))
  412. else:
  413. GMessage(message = _("Data <%(name)s> imported successfully.") % {'name': filePath},
  414. parent = self)
  415. if not grass.find_file(element = 'cell', name = mapName)['fullname'] and \
  416. not grass.find_file(element = 'vector', name = mapName)['fullname']:
  417. GError(parent = self,
  418. message = _("Map <%s> not found.") % mapName)
  419. else:
  420. if mapName in vectors:
  421. args = {'vect' : mapName}
  422. else:
  423. args = {'rast' : mapName}
  424. RunCommand('g.region', flags = 's', parent = self, **args)
  425. def OnManageLoc(self, event):
  426. """!Location management choice control handler
  427. """
  428. sel = event.GetSelection()
  429. if sel == 0:
  430. self.RenameMapset()
  431. elif sel == 1:
  432. self.RenameLocation()
  433. elif sel == 2:
  434. self.DeleteMapset()
  435. elif sel == 3:
  436. self.DeleteLocation()
  437. event.Skip()
  438. def RenameMapset(self):
  439. """!Rename selected mapset
  440. """
  441. location = self.listOfLocations[self.lblocations.GetSelection()]
  442. mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
  443. if mapset == 'PERMANENT':
  444. GMessage(parent = self,
  445. message = _('Mapset <PERMANENT> is required for valid GRASS location.\n\n'
  446. 'This mapset cannot be renamed.'))
  447. return
  448. dlg = wx.TextEntryDialog(parent = self,
  449. message = _('Current name: %s\n\nEnter new name:') % mapset,
  450. caption = _('Rename selected mapset'))
  451. if dlg.ShowModal() == wx.ID_OK:
  452. newmapset = dlg.GetValue()
  453. if newmapset == mapset:
  454. dlg.Destroy()
  455. return
  456. if newmapset in self.listOfMapsets:
  457. wx.MessageBox(parent = self,
  458. caption = _('Message'),
  459. message = _('Unable to rename mapset.\n\n'
  460. 'Mapset <%s> already exists in location.') % newmapset,
  461. style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  462. else:
  463. try:
  464. os.rename(os.path.join(self.gisdbase, location, mapset),
  465. os.path.join(self.gisdbase, location, newmapset))
  466. self.OnSelectLocation(None)
  467. self.lbmapsets.SetSelection(self.listOfMapsets.index(newmapset))
  468. except StandardError, e:
  469. wx.MessageBox(parent = self,
  470. caption = _('Error'),
  471. message = _('Unable to rename mapset.\n\n%s') % e,
  472. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  473. dlg.Destroy()
  474. def RenameLocation(self):
  475. """!Rename selected location
  476. """
  477. location = self.listOfLocations[self.lblocations.GetSelection()]
  478. dlg = wx.TextEntryDialog(parent = self,
  479. message = _('Current name: %s\n\nEnter new name:') % location,
  480. caption = _('Rename selected location'))
  481. if dlg.ShowModal() == wx.ID_OK:
  482. newlocation = dlg.GetValue()
  483. if newlocation == location:
  484. dlg.Destroy()
  485. return
  486. if newlocation in self.listOfLocations:
  487. wx.MessageBox(parent = self,
  488. caption = _('Message'),
  489. message = _('Unable to rename location.\n\n'
  490. 'Location <%s> already exists in GRASS database.') % newlocation,
  491. style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  492. else:
  493. try:
  494. os.rename(os.path.join(self.gisdbase, location),
  495. os.path.join(self.gisdbase, newlocation))
  496. self.UpdateLocations(self.gisdbase)
  497. self.lblocations.SetSelection(self.listOfLocations.index(newlocation))
  498. self.UpdateMapsets(newlocation)
  499. except StandardError, e:
  500. wx.MessageBox(parent = self,
  501. caption = _('Error'),
  502. message = _('Unable to rename location.\n\n%s') % e,
  503. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  504. dlg.Destroy()
  505. def DeleteMapset(self):
  506. """!Delete selected mapset
  507. """
  508. location = self.listOfLocations[self.lblocations.GetSelection()]
  509. mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
  510. if mapset == 'PERMANENT':
  511. GMessage(parent = self,
  512. message = _('Mapset <PERMANENT> is required for valid GRASS location.\n\n'
  513. 'This mapset cannot be deleted.'))
  514. return
  515. dlg = wx.MessageDialog(parent = self, message = _("Do you want to continue with deleting mapset <%(mapset)s> "
  516. "from location <%(location)s>?\n\n"
  517. "ALL MAPS included in this mapset will be "
  518. "PERMANENTLY DELETED!") % {'mapset' : mapset,
  519. 'location' : location},
  520. caption = _("Delete selected mapset"),
  521. style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  522. if dlg.ShowModal() == wx.ID_YES:
  523. try:
  524. shutil.rmtree(os.path.join(self.gisdbase, location, mapset))
  525. self.OnSelectLocation(None)
  526. self.lbmapsets.SetSelection(0)
  527. except:
  528. wx.MessageBox(message = _('Unable to delete mapset'))
  529. dlg.Destroy()
  530. def DeleteLocation(self):
  531. """
  532. Delete selected location
  533. """
  534. location = self.listOfLocations[self.lblocations.GetSelection()]
  535. dlg = wx.MessageDialog(parent = self, message = _("Do you want to continue with deleting "
  536. "location <%s>?\n\n"
  537. "ALL MAPS included in this location will be "
  538. "PERMANENTLY DELETED!") % (location),
  539. caption = _("Delete selected location"),
  540. style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  541. if dlg.ShowModal() == wx.ID_YES:
  542. try:
  543. shutil.rmtree(os.path.join(self.gisdbase, location))
  544. self.UpdateLocations(self.gisdbase)
  545. self.lblocations.SetSelection(0)
  546. self.OnSelectLocation(None)
  547. self.lbmapsets.SetSelection(0)
  548. except:
  549. wx.MessageBox(message = _('Unable to delete location'))
  550. dlg.Destroy()
  551. def UpdateLocations(self, dbase):
  552. """!Update list of locations"""
  553. try:
  554. self.listOfLocations = GetListOfLocations(dbase)
  555. except UnicodeEncodeError:
  556. GError(parent = self,
  557. message = _("Unable to set GRASS database. "
  558. "Check your locale settings."))
  559. self.lblocations.Clear()
  560. self.lblocations.InsertItems(self.listOfLocations, 0)
  561. if len(self.listOfLocations) > 0:
  562. self.lblocations.SetSelection(0)
  563. else:
  564. self.lblocations.SetSelection(wx.NOT_FOUND)
  565. GWarning(_("No GRASS location found in '%s'.") % self.gisdbase,
  566. parent = self)
  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. gisdbase = self.tgisdbase.GetValue()
  651. if not os.path.exists(gisdbase):
  652. GError(_("Path '%s' doesn't exist.") % gisdbase,
  653. parent = self)
  654. return
  655. self.gisdbase = self.tgisdbase.GetValue()
  656. self.UpdateLocations(self.gisdbase)
  657. self.OnSelectLocation(None)
  658. def OnBrowse(self, event):
  659. """'Browse' button clicked"""
  660. if not event:
  661. defaultPath = os.getenv('HOME')
  662. else:
  663. defaultPath = ""
  664. dlg = wx.DirDialog(parent = self, message = _("Choose GIS Data Directory"),
  665. defaultPath = defaultPath, style = wx.DD_DEFAULT_STYLE)
  666. if dlg.ShowModal() == wx.ID_OK:
  667. self.gisdbase = dlg.GetPath()
  668. self.tgisdbase.SetValue(self.gisdbase)
  669. self.OnSetDatabase(event)
  670. dlg.Destroy()
  671. def OnCreateMapset(self,event):
  672. """!Create new mapset"""
  673. self.gisdbase = self.tgisdbase.GetValue()
  674. location = self.listOfLocations[self.lblocations.GetSelection()]
  675. dlg = wx.TextEntryDialog(parent = self,
  676. message = _('Enter name for new mapset:'),
  677. caption = _('Create new mapset'))
  678. if dlg.ShowModal() == wx.ID_OK:
  679. mapset = dlg.GetValue()
  680. if mapset in self.listOfMapsets:
  681. GMessage(parent = self,
  682. message = _("Mapset <%s> already exists.") % mapset)
  683. return
  684. if mapset.lower() == 'ogr':
  685. dlg1 = wx.MessageDialog(parent = self,
  686. message = _("Mapset <%s> is reserved for direct "
  687. "read access to OGR layers. Please consider to use "
  688. "another name for your mapset.\n\n"
  689. "Are you really sure that you want to create this mapset?") % mapset,
  690. caption = _("Reserved mapset name"),
  691. style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  692. ret = dlg1.ShowModal()
  693. dlg1.Destroy()
  694. if ret == wx.ID_NO:
  695. dlg.Destroy()
  696. return
  697. try:
  698. os.mkdir(os.path.join(self.gisdbase, location, mapset))
  699. # copy WIND file and its permissions from PERMANENT and set permissions to u+rw,go+r
  700. shutil.copy(os.path.join(self.gisdbase, location, 'PERMANENT', 'WIND'),
  701. os.path.join(self.gisdbase, location, mapset))
  702. # os.chmod(os.path.join(database,location,mapset,'WIND'), 0644)
  703. self.OnSelectLocation(None)
  704. self.lbmapsets.SetSelection(self.listOfMapsets.index(mapset))
  705. except StandardError, e:
  706. GError(parent = self,
  707. message = _("Unable to create new mapset: %s") % e,
  708. showTraceback = False)
  709. return False
  710. dlg.Destroy()
  711. self.bstart.SetFocus()
  712. return True
  713. def OnStart(self, event):
  714. """'Start GRASS' button clicked"""
  715. dbase = self.tgisdbase.GetValue()
  716. location = self.listOfLocations[self.lblocations.GetSelection()]
  717. mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
  718. lockfile = os.path.join(dbase, location, mapset, '.gislock')
  719. if os.path.isfile(lockfile):
  720. dlg = wx.MessageDialog(parent = self,
  721. message = _("GRASS is already running in selected mapset <%(mapset)s>\n"
  722. "(file %(lock)s found).\n\n"
  723. "Concurrent use not allowed.\n\n"
  724. "Do you want to try to remove .gislock (note that you "
  725. "need permission for this operation) and continue?") %
  726. { 'mapset' : mapset, 'lock' : lockfile },
  727. caption = _("Lock file found"),
  728. style = wx.YES_NO | wx.NO_DEFAULT |
  729. wx.ICON_QUESTION | wx.CENTRE)
  730. ret = dlg.ShowModal()
  731. dlg.Destroy()
  732. if ret == wx.ID_YES:
  733. dlg1 = wx.MessageDialog(parent = self,
  734. message = _("ARE YOU REALLY SURE?\n\n"
  735. "If you really are running another GRASS session doing this "
  736. "could corrupt your data. Have another look in the processor "
  737. "manager just to be sure..."),
  738. caption = _("Lock file found"),
  739. style = wx.YES_NO | wx.NO_DEFAULT |
  740. wx.ICON_QUESTION | wx.CENTRE)
  741. ret = dlg1.ShowModal()
  742. dlg1.Destroy()
  743. if ret == wx.ID_YES:
  744. try:
  745. os.remove(lockfile)
  746. except IOError, e:
  747. GError(_("Unable to remove '%(lock)s'.\n\n"
  748. "Details: %(reason)s") % { 'lock' : lockfile, 'reason' : e})
  749. else:
  750. return
  751. else:
  752. return
  753. self.SetLocation(dbase, location, mapset)
  754. self.ExitSuccessfully()
  755. def SetLocation(self, dbase, location, mapset):
  756. RunCommand("g.gisenv",
  757. set = "GISDBASE=%s" % dbase)
  758. RunCommand("g.gisenv",
  759. set = "LOCATION_NAME=%s" % location)
  760. RunCommand("g.gisenv",
  761. set = "MAPSET=%s" % mapset)
  762. def ExitSuccessfully(self):
  763. self.Destroy()
  764. sys.exit(0)
  765. def OnExit(self, event):
  766. """'Exit' button clicked"""
  767. self.Destroy()
  768. sys.exit(2)
  769. def OnHelp(self, event):
  770. """'Help' button clicked"""
  771. # help text in lib/init/helptext.html
  772. RunCommand('g.manual', entry = 'helptext')
  773. def OnCloseWindow(self, event):
  774. """!Close window event"""
  775. event.Skip()
  776. sys.exit(2)
  777. class GListBox(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin):
  778. """!Use wx.ListCtrl instead of wx.ListBox, different style for
  779. non-selectable items (e.g. mapsets with denied permission)"""
  780. def __init__(self, parent, id, size,
  781. choices, disabled = []):
  782. wx.ListCtrl.__init__(self, parent, id, size = size,
  783. style = wx.LC_REPORT | wx.LC_NO_HEADER | wx.LC_SINGLE_SEL |
  784. wx.BORDER_SUNKEN)
  785. listmix.ListCtrlAutoWidthMixin.__init__(self)
  786. self.InsertColumn(0, '')
  787. self.selected = wx.NOT_FOUND
  788. self._LoadData(choices, disabled)
  789. def _LoadData(self, choices, disabled = []):
  790. """!Load data into list
  791. @param choices list of item
  792. @param disabled list of indeces of non-selectable items
  793. """
  794. idx = 0
  795. for item in choices:
  796. index = self.InsertStringItem(sys.maxint, item)
  797. self.SetStringItem(index, 0, item)
  798. if idx in disabled:
  799. self.SetItemTextColour(idx, wx.Colour(150, 150, 150))
  800. idx += 1
  801. def Clear(self):
  802. self.DeleteAllItems()
  803. def InsertItems(self, choices, pos, disabled = []):
  804. self._LoadData(choices, disabled)
  805. def SetSelection(self, item, force = False):
  806. if item != wx.NOT_FOUND and \
  807. (platform.system() != 'Windows' or force):
  808. ### Windows -> FIXME
  809. self.SetItemState(item, wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED)
  810. self.selected = item
  811. def GetSelection(self):
  812. return self.selected
  813. class StartUp(wx.App):
  814. """!Start-up application"""
  815. def OnInit(self):
  816. wx.InitAllImageHandlers()
  817. StartUp = GRASSStartup()
  818. StartUp.CenterOnScreen()
  819. self.SetTopWindow(StartUp)
  820. StartUp.Show()
  821. if StartUp.GetRCValue("LOCATION_NAME") == "<UNKNOWN>":
  822. wx.MessageBox(parent = StartUp,
  823. caption = _('Starting GRASS for the first time'),
  824. message = _('GRASS needs a directory in which to store its data. '
  825. 'Create one now if you have not already done so. '
  826. 'A popular choice is "grassdata", located in '
  827. 'your home directory.'),
  828. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  829. StartUp.OnBrowse(None)
  830. return 1
  831. if __name__ == "__main__":
  832. if os.getenv("GISBASE") is None:
  833. sys.exit("Failed to start GUI, GRASS GIS is not running.")
  834. import gettext
  835. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  836. GRASSStartUp = StartUp(0)
  837. GRASSStartUp.MainLoop()