gis_set.py 41 KB

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