gis_set.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  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, GWarning
  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>":
  181. return
  182. if not os.path.isdir(os.path.join(self.gisdbase, location)):
  183. location = None
  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. sys.stderr.write(_("ERROR: Location <%s> not found\n") % self.GetRCValue("LOCATION_NAME"))
  192. if len(self.listOfLocations) > 0:
  193. self.lblocations.SetSelection(0, force = True)
  194. self.lblocations.EnsureVisible(0)
  195. location = self.listOfLocations[0]
  196. else:
  197. return
  198. # list of mapsets
  199. self.UpdateMapsets(os.path.join(self.gisdbase, location))
  200. mapset = self.GetRCValue("MAPSET")
  201. if mapset:
  202. try:
  203. self.lbmapsets.SetSelection(self.listOfMapsets.index(mapset),
  204. force = True)
  205. self.lbmapsets.EnsureVisible(self.listOfMapsets.index(mapset))
  206. except ValueError:
  207. sys.stderr.write(_("ERROR: Mapset <%s> not found\n") % mapset)
  208. self.lbmapsets.SetSelection(0, force = True)
  209. self.lbmapsets.EnsureVisible(0)
  210. def _do_layout(self):
  211. sizer = wx.BoxSizer(wx.VERTICAL)
  212. dbase_sizer = wx.BoxSizer(wx.HORIZONTAL)
  213. location_sizer = wx.BoxSizer(wx.HORIZONTAL)
  214. select_boxsizer = wx.StaticBoxSizer(self.select_box, wx.VERTICAL)
  215. select_sizer = wx.FlexGridSizer(rows = 2, cols = 2, vgap = 4, hgap = 4)
  216. select_sizer.AddGrowableRow(1)
  217. select_sizer.AddGrowableCol(0)
  218. select_sizer.AddGrowableCol(1)
  219. manage_sizer = wx.StaticBoxSizer(self.manage_box, wx.VERTICAL)
  220. btns_sizer = wx.BoxSizer(wx.HORIZONTAL)
  221. # gis data directory
  222. dbase_sizer.Add(item = self.ldbase, proportion = 0,
  223. flag = wx.ALIGN_CENTER_VERTICAL |
  224. wx.ALIGN_CENTER_HORIZONTAL | wx.ALL,
  225. border = 3)
  226. dbase_sizer.Add(item = self.tgisdbase, proportion = 1,
  227. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  228. border = 3)
  229. dbase_sizer.Add(item = self.bbrowse, proportion = 0,
  230. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  231. border = 3)
  232. # select sizer
  233. select_sizer.Add(item = self.llocation, proportion = 0,
  234. flag = wx.ALIGN_CENTER_HORIZONTAL | wx.ALL,
  235. border = 3)
  236. select_sizer.Add(item = self.lmapset, proportion = 0,
  237. flag = wx.ALIGN_CENTER_HORIZONTAL | wx.ALL,
  238. border = 3)
  239. select_sizer.Add(item = self.lblocations, proportion = 1,
  240. flag = wx.EXPAND)
  241. select_sizer.Add(item = self.lbmapsets, proportion = 1,
  242. flag = wx.EXPAND)
  243. select_boxsizer.Add(item = select_sizer, proportion = 1,
  244. flag = wx.EXPAND)
  245. # define new location and mapset
  246. manage_sizer.Add(item = self.ldefine, proportion = 0,
  247. flag = wx.ALIGN_CENTER_HORIZONTAL | wx.ALL,
  248. border = 3)
  249. manage_sizer.Add(item = self.bwizard, proportion = 0,
  250. flag = wx.ALIGN_CENTER_HORIZONTAL | wx.BOTTOM,
  251. border = 5)
  252. manage_sizer.Add(item = self.lcreate, proportion = 0,
  253. flag = wx.ALIGN_CENTER_HORIZONTAL | wx.ALL,
  254. border = 3)
  255. manage_sizer.Add(item = self.bmapset, proportion = 0,
  256. flag = wx.ALIGN_CENTER_HORIZONTAL | wx.BOTTOM,
  257. border = 5)
  258. manage_sizer.Add(item = self.lmanageloc, proportion = 0,
  259. flag = wx.ALIGN_CENTER_HORIZONTAL | wx.ALL,
  260. border = 3)
  261. manage_sizer.Add(item = self.manageloc, proportion = 0,
  262. flag = wx.ALIGN_CENTER_HORIZONTAL | wx.BOTTOM,
  263. border = 5)
  264. # location sizer
  265. location_sizer.Add(item = select_boxsizer, proportion = 1,
  266. flag = wx.LEFT | wx.RIGHT | wx.EXPAND,
  267. border = 3)
  268. location_sizer.Add(item = manage_sizer, proportion = 0,
  269. flag = wx.RIGHT | wx.EXPAND,
  270. border = 3)
  271. # buttons
  272. btns_sizer.Add(item = self.bstart, proportion = 0,
  273. flag = wx.ALIGN_CENTER_HORIZONTAL |
  274. wx.ALIGN_CENTER_VERTICAL |
  275. wx.ALL,
  276. border = 5)
  277. btns_sizer.Add(item = self.bexit, proportion = 0,
  278. flag = wx.ALIGN_CENTER_HORIZONTAL |
  279. wx.ALIGN_CENTER_VERTICAL |
  280. wx.ALL,
  281. border = 5)
  282. btns_sizer.Add(item = self.bhelp, proportion = 0,
  283. flag = wx.ALIGN_CENTER_HORIZONTAL |
  284. wx.ALIGN_CENTER_VERTICAL |
  285. wx.ALL,
  286. border = 5)
  287. # main sizer
  288. sizer.Add(item = self.hbitmap,
  289. proportion = 0,
  290. flag = wx.ALIGN_CENTER_VERTICAL |
  291. wx.ALIGN_CENTER_HORIZONTAL |
  292. wx.ALL,
  293. border = 3) # image
  294. sizer.Add(item = self.lwelcome, # welcome message
  295. proportion = 0,
  296. flag = wx.ALIGN_CENTER_VERTICAL |
  297. wx.ALIGN_CENTER_HORIZONTAL |
  298. wx.BOTTOM,
  299. border = 5)
  300. sizer.Add(item = self.ltitle, # title
  301. proportion = 0,
  302. flag = wx.ALIGN_CENTER_VERTICAL |
  303. wx.ALIGN_CENTER_HORIZONTAL)
  304. sizer.Add(item = dbase_sizer, proportion = 0,
  305. flag = wx.ALIGN_CENTER_HORIZONTAL |
  306. wx.RIGHT | wx.LEFT | wx.EXPAND,
  307. border = 20) # GISDBASE setting
  308. sizer.Add(item = location_sizer, proportion = 1,
  309. flag = wx.RIGHT | wx.LEFT | wx.EXPAND,
  310. border = 1)
  311. sizer.Add(item = btns_sizer, proportion = 0,
  312. flag = wx.ALIGN_CENTER_VERTICAL |
  313. wx.ALIGN_CENTER_HORIZONTAL |
  314. wx.RIGHT | wx.LEFT,
  315. border = 1)
  316. self.panel.SetAutoLayout(True)
  317. self.panel.SetSizer(sizer)
  318. sizer.Fit(self.panel)
  319. sizer.SetSizeHints(self)
  320. self.Layout()
  321. def _readGisRC(self):
  322. """!Read variables from $HOME/.grass7/rc file
  323. """
  324. grassrc = {}
  325. gisrc = os.getenv("GISRC")
  326. if gisrc and os.path.isfile(gisrc):
  327. try:
  328. rc = open(gisrc, "r")
  329. for line in rc.readlines():
  330. try:
  331. key, val = line.split(":", 1)
  332. except ValueError, e:
  333. sys.stderr.write(_('Invalid line in GISRC file (%s):%s\n' % \
  334. (e, line)))
  335. grassrc[key.strip()] = DecodeString(val.strip())
  336. finally:
  337. rc.close()
  338. return grassrc
  339. def GetRCValue(self, value):
  340. """!Return GRASS variable (read from GISRC)
  341. """
  342. if self.grassrc.has_key(value):
  343. return self.grassrc[value]
  344. else:
  345. return None
  346. def OnWizard(self, event):
  347. """!Location wizard started"""
  348. from location_wizard.wizard import LocationWizard
  349. gWizard = LocationWizard(parent = self,
  350. grassdatabase = self.tgisdbase.GetValue())
  351. if gWizard.location != None:
  352. self.tgisdbase.SetValue(gWizard.grassdatabase)
  353. self.OnSetDatabase(None)
  354. self.UpdateMapsets(os.path.join(self.gisdbase, gWizard.location))
  355. self.lblocations.SetSelection(self.listOfLocations.index(gWizard.location))
  356. self.lbmapsets.SetSelection(0)
  357. self.SetLocation(self.gisdbase, gWizard.location, 'PERMANENT')
  358. if gWizard.georeffile:
  359. message = _("Do you want to import data source <%(name)s> to created location?"
  360. " Default region will be set to match imported map.") % {'name': gWizard.georeffile}
  361. dlg = wx.MessageDialog(parent = self,
  362. message = message,
  363. caption = _("Import data"),
  364. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  365. dlg.CenterOnScreen()
  366. if dlg.ShowModal() == wx.ID_YES:
  367. self.ImportFile(gWizard.georeffile)
  368. else:
  369. self.SetDefaultRegion(location = gWizard.location)
  370. dlg.Destroy()
  371. else:
  372. self.SetDefaultRegion(location = gWizard.location)
  373. self.ExitSuccessfully()
  374. def SetDefaultRegion(self, location):
  375. """!Asks to set default region."""
  376. dlg = wx.MessageDialog(parent = self,
  377. message = _("Do you want to set the default "
  378. "region extents and resolution now?"),
  379. caption = _("Location <%s> created") % location,
  380. style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  381. dlg.CenterOnScreen()
  382. if dlg.ShowModal() == wx.ID_YES:
  383. dlg.Destroy()
  384. defineRegion = RegionDef(self, location = location)
  385. defineRegion.CenterOnScreen()
  386. defineRegion.ShowModal()
  387. defineRegion.Destroy()
  388. else:
  389. dlg.Destroy()
  390. def ImportFile(self, filePath):
  391. """!Tries to import file as vector or raster.
  392. If successfull sets default region from imported map.
  393. """
  394. returncode, stdout, messagesIfVector = RunCommand('v.in.ogr', dsn = filePath, flags = 'l',
  395. read = True, getErrorMsg = True)
  396. if returncode == 0:
  397. wx.BeginBusyCursor()
  398. wx.Yield()
  399. returncode, messages = RunCommand('v.in.ogr', dsn = filePath,
  400. output = os.path.splitext(os.path.basename(filePath))[0],
  401. getErrorMsg = True)
  402. wx.EndBusyCursor()
  403. if returncode != 0:
  404. message = _("Import of vector data source <%(name)s> failed.") % {'name': filePath}
  405. message += "\n" + messages
  406. GError(message = message)
  407. else:
  408. GMessage(message = _("Vector data source <%(name)s> imported successfully.") % {'name': filePath})
  409. stdout = RunCommand('g.list', type = 'vect', read = True)
  410. maps = stdout.splitlines()
  411. if maps:
  412. # TODO: what about resolution?
  413. RunCommand('g.region', flags = 's', vect = maps[0])
  414. else:
  415. wx.BeginBusyCursor()
  416. wx.Yield()
  417. returncode, messages = RunCommand('r.in.gdal', input = filePath,
  418. output = os.path.splitext(os.path.basename(filePath))[0],
  419. getErrorMsg = True)
  420. wx.EndBusyCursor()
  421. if returncode != 0:
  422. message = _("Attempt to import data source <%(name)s> as raster or vector failed. ") % {'name': filePath}
  423. message += "\n\n" + messagesIfVector + "\n" + messages
  424. GError(message = message)
  425. else:
  426. GMessage(message = _("Raster data source <%(name)s> imported successfully.") % {'name': filePath})
  427. stdout = RunCommand('g.list', type = 'rast', read = True)
  428. maps = stdout.splitlines()
  429. if maps:
  430. RunCommand('g.region', flags = 's', rast = maps[0])
  431. def OnManageLoc(self, event):
  432. """!Location management choice control handler
  433. """
  434. sel = event.GetSelection()
  435. if sel == 0:
  436. self.RenameMapset()
  437. elif sel == 1:
  438. self.RenameLocation()
  439. elif sel == 2:
  440. self.DeleteMapset()
  441. elif sel == 3:
  442. self.DeleteLocation()
  443. event.Skip()
  444. def RenameMapset(self):
  445. """!Rename selected mapset
  446. """
  447. location = self.listOfLocations[self.lblocations.GetSelection()]
  448. mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
  449. if mapset == 'PERMANENT':
  450. GMessage(parent = self,
  451. message = _('Mapset <PERMANENT> is required for valid GRASS location.\n\n'
  452. 'This mapset cannot be renamed.'))
  453. return
  454. dlg = wx.TextEntryDialog(parent = self,
  455. message = _('Current name: %s\n\nEnter new name:') % mapset,
  456. caption = _('Rename selected mapset'))
  457. if dlg.ShowModal() == wx.ID_OK:
  458. newmapset = dlg.GetValue()
  459. if newmapset == mapset:
  460. dlg.Destroy()
  461. return
  462. if newmapset in self.listOfMapsets:
  463. wx.MessageBox(parent = self,
  464. caption = _('Message'),
  465. message = _('Unable to rename mapset.\n\n'
  466. 'Mapset <%s> already exists in location.') % newmapset,
  467. style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  468. else:
  469. try:
  470. os.rename(os.path.join(self.gisdbase, location, mapset),
  471. os.path.join(self.gisdbase, location, newmapset))
  472. self.OnSelectLocation(None)
  473. self.lbmapsets.SetSelection(self.listOfMapsets.index(newmapset))
  474. except StandardError, e:
  475. wx.MessageBox(parent = self,
  476. caption = _('Error'),
  477. message = _('Unable to rename mapset.\n\n%s') % e,
  478. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  479. dlg.Destroy()
  480. def RenameLocation(self):
  481. """!Rename selected location
  482. """
  483. location = self.listOfLocations[self.lblocations.GetSelection()]
  484. dlg = wx.TextEntryDialog(parent = self,
  485. message = _('Current name: %s\n\nEnter new name:') % location,
  486. caption = _('Rename selected location'))
  487. if dlg.ShowModal() == wx.ID_OK:
  488. newlocation = dlg.GetValue()
  489. if newlocation == location:
  490. dlg.Destroy()
  491. return
  492. if newlocation in self.listOfLocations:
  493. wx.MessageBox(parent = self,
  494. caption = _('Message'),
  495. message = _('Unable to rename location.\n\n'
  496. 'Location <%s> already exists in GRASS database.') % newlocation,
  497. style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  498. else:
  499. try:
  500. os.rename(os.path.join(self.gisdbase, location),
  501. os.path.join(self.gisdbase, newlocation))
  502. self.UpdateLocations(self.gisdbase)
  503. self.lblocations.SetSelection(self.listOfLocations.index(newlocation))
  504. self.UpdateMapsets(newlocation)
  505. except StandardError, e:
  506. wx.MessageBox(parent = self,
  507. caption = _('Error'),
  508. message = _('Unable to rename location.\n\n%s') % e,
  509. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  510. dlg.Destroy()
  511. def DeleteMapset(self):
  512. """!Delete selected mapset
  513. """
  514. location = self.listOfLocations[self.lblocations.GetSelection()]
  515. mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
  516. if mapset == 'PERMANENT':
  517. GMessage(parent = self,
  518. message = _('Mapset <PERMANENT> is required for valid GRASS location.\n\n'
  519. 'This mapset cannot be deleted.'))
  520. return
  521. dlg = wx.MessageDialog(parent = self, message = _("Do you want to continue with deleting mapset <%(mapset)s> "
  522. "from location <%(location)s>?\n\n"
  523. "ALL MAPS included in this mapset will be "
  524. "PERMANENTLY DELETED!") % {'mapset' : mapset,
  525. 'location' : location},
  526. caption = _("Delete selected mapset"),
  527. style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  528. if dlg.ShowModal() == wx.ID_YES:
  529. try:
  530. shutil.rmtree(os.path.join(self.gisdbase, location, mapset))
  531. self.OnSelectLocation(None)
  532. self.lbmapsets.SetSelection(0)
  533. except:
  534. wx.MessageBox(message = _('Unable to delete mapset'))
  535. dlg.Destroy()
  536. def DeleteLocation(self):
  537. """
  538. Delete selected location
  539. """
  540. location = self.listOfLocations[self.lblocations.GetSelection()]
  541. dlg = wx.MessageDialog(parent = self, message = _("Do you want to continue with deleting "
  542. "location <%s>?\n\n"
  543. "ALL MAPS included in this location will be "
  544. "PERMANENTLY DELETED!") % (location),
  545. caption = _("Delete selected location"),
  546. style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  547. if dlg.ShowModal() == wx.ID_YES:
  548. try:
  549. shutil.rmtree(os.path.join(self.gisdbase, location))
  550. self.UpdateLocations(self.gisdbase)
  551. self.lblocations.SetSelection(0)
  552. self.OnSelectLocation(None)
  553. self.lbmapsets.SetSelection(0)
  554. except:
  555. wx.MessageBox(message = _('Unable to delete location'))
  556. dlg.Destroy()
  557. def UpdateLocations(self, dbase):
  558. """!Update list of locations"""
  559. try:
  560. self.listOfLocations = GetListOfLocations(dbase)
  561. except UnicodeEncodeError:
  562. wx.MessageBox(parent = self, caption = _("Error"),
  563. message = _("Unable to set GRASS database. "
  564. "Check your locale settings."),
  565. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  566. self.lblocations.Clear()
  567. self.lblocations.InsertItems(self.listOfLocations, 0)
  568. if len(self.listOfLocations) > 0:
  569. self.lblocations.SetSelection(0)
  570. else:
  571. self.lblocations.SetSelection(wx.NOT_FOUND)
  572. return self.listOfLocations
  573. def UpdateMapsets(self, location):
  574. """!Update list of mapsets"""
  575. self.FormerMapsetSelection = wx.NOT_FOUND # for non-selectable item
  576. self.listOfMapsetsSelectable = list()
  577. self.listOfMapsets = GetListOfMapsets(self.gisdbase, location)
  578. self.lbmapsets.Clear()
  579. # disable mapset with denied permission
  580. locationName = os.path.basename(location)
  581. ret = RunCommand('g.mapset',
  582. read = True,
  583. flags = 'l',
  584. location = locationName,
  585. gisdbase = self.gisdbase)
  586. if ret:
  587. for line in ret.splitlines():
  588. self.listOfMapsetsSelectable += line.split(' ')
  589. else:
  590. RunCommand("g.gisenv",
  591. set = "GISDBASE=%s" % self.gisdbase)
  592. RunCommand("g.gisenv",
  593. set = "LOCATION_NAME=%s" % locationName)
  594. RunCommand("g.gisenv",
  595. set = "MAPSET=PERMANENT")
  596. # first run only
  597. self.listOfMapsetsSelectable = copy.copy(self.listOfMapsets)
  598. disabled = []
  599. idx = 0
  600. for mapset in self.listOfMapsets:
  601. if mapset not in self.listOfMapsetsSelectable or \
  602. os.path.isfile(os.path.join(self.gisdbase,
  603. locationName,
  604. mapset, ".gislock")):
  605. disabled.append(idx)
  606. idx += 1
  607. self.lbmapsets.InsertItems(self.listOfMapsets, 0, disabled = disabled)
  608. return self.listOfMapsets
  609. def OnSelectLocation(self, event):
  610. """!Location selected"""
  611. if event:
  612. self.lblocations.SetSelection(event.GetIndex())
  613. if self.lblocations.GetSelection() != wx.NOT_FOUND:
  614. self.UpdateMapsets(os.path.join(self.gisdbase,
  615. self.listOfLocations[self.lblocations.GetSelection()]))
  616. else:
  617. self.listOfMapsets = []
  618. disabled = []
  619. idx = 0
  620. try:
  621. locationName = self.listOfLocations[self.lblocations.GetSelection()]
  622. except IndexError:
  623. locationName = ''
  624. for mapset in self.listOfMapsets:
  625. if mapset not in self.listOfMapsetsSelectable or \
  626. os.path.isfile(os.path.join(self.gisdbase,
  627. locationName,
  628. mapset, ".gislock")):
  629. disabled.append(idx)
  630. idx += 1
  631. self.lbmapsets.Clear()
  632. self.lbmapsets.InsertItems(self.listOfMapsets, 0, disabled = disabled)
  633. if len(self.listOfMapsets) > 0:
  634. self.lbmapsets.SetSelection(0)
  635. if locationName:
  636. # enable start button when location and mapset is selected
  637. self.bstart.Enable()
  638. self.bmapset.Enable()
  639. self.manageloc.Enable()
  640. else:
  641. self.lbmapsets.SetSelection(wx.NOT_FOUND)
  642. self.bstart.Enable(False)
  643. self.bmapset.Enable(False)
  644. self.manageloc.Enable(False)
  645. def OnSelectMapset(self, event):
  646. """!Mapset selected"""
  647. self.lbmapsets.SetSelection(event.GetIndex())
  648. if event.GetText() not in self.listOfMapsetsSelectable:
  649. self.lbmapsets.SetSelection(self.FormerMapsetSelection)
  650. else:
  651. self.FormerMapsetSelection = event.GetIndex()
  652. event.Skip()
  653. def OnSetDatabase(self, event):
  654. """!Database set"""
  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()