gis_set.py 41 KB

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