gis_set.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  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. key, val = line.split(":", 1)
  324. grassrc[key.strip()] = DecodeString(val.strip())
  325. finally:
  326. rc.close()
  327. return grassrc
  328. def GetRCValue(self, value):
  329. """!Return GRASS variable (read from GISRC)
  330. """
  331. if self.grassrc.has_key(value):
  332. return self.grassrc[value]
  333. else:
  334. return None
  335. def OnWizard(self, event):
  336. """!Location wizard started"""
  337. from location_wizard.wizard import LocationWizard
  338. gWizard = LocationWizard(parent = self,
  339. grassdatabase = self.tgisdbase.GetValue())
  340. if gWizard.location != None:
  341. self.tgisdbase.SetValue(gWizard.grassdatabase)
  342. self.OnSetDatabase(None)
  343. self.UpdateMapsets(os.path.join(self.gisdbase, gWizard.location))
  344. self.lblocations.SetSelection(self.listOfLocations.index(gWizard.location))
  345. self.lbmapsets.SetSelection(0)
  346. self.SetLocation(self.gisdbase, gWizard.location, 'PERMANENT')
  347. if gWizard.georeffile:
  348. message = _("Do you want to import data source <%(name)s> to created location?"
  349. " Default region will be set to match imported map.") % {'name': gWizard.georeffile}
  350. dlg = wx.MessageDialog(parent = self,
  351. message = message,
  352. caption = _("Import data"),
  353. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  354. dlg.CenterOnScreen()
  355. if dlg.ShowModal() == wx.ID_YES:
  356. self.ImportFile(gWizard.georeffile)
  357. else:
  358. self.SetDefaultRegion(location = gWizard.location)
  359. dlg.Destroy()
  360. else:
  361. self.SetDefaultRegion(location = gWizard.location)
  362. self.ExitSuccessfully()
  363. def SetDefaultRegion(self, location):
  364. """!Asks to set default region."""
  365. dlg = wx.MessageDialog(parent = self,
  366. message = _("Do you want to set the default "
  367. "region extents and resolution now?"),
  368. caption = _("Location <%s> created") % location,
  369. style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  370. dlg.CenterOnScreen()
  371. if dlg.ShowModal() == wx.ID_YES:
  372. dlg.Destroy()
  373. defineRegion = RegionDef(self, location = location)
  374. defineRegion.CenterOnScreen()
  375. defineRegion.ShowModal()
  376. defineRegion.Destroy()
  377. else:
  378. dlg.Destroy()
  379. def ImportFile(self, filePath):
  380. """!Tries to import file as vector or raster.
  381. If successfull sets default region from imported map.
  382. """
  383. returncode, stdout, messagesIfVector = RunCommand('v.in.ogr', dsn = filePath, flags = 'l',
  384. read = True, getErrorMsg = True)
  385. if returncode == 0:
  386. wx.BeginBusyCursor()
  387. wx.Yield()
  388. returncode, messages = RunCommand('v.in.ogr', dsn = filePath,
  389. output = os.path.splitext(os.path.basename(filePath))[0],
  390. getErrorMsg = True)
  391. wx.EndBusyCursor()
  392. if returncode != 0:
  393. message = _("Import of vector data source <%(name)s> failed.") % {'name': filePath}
  394. message += "\n" + messages
  395. GError(message = message)
  396. else:
  397. GMessage(message = _("Vector data source <%(name)s> imported successfully.") % {'name': filePath})
  398. stdout = RunCommand('g.list', type = 'vect', read = True)
  399. maps = stdout.splitlines()
  400. if maps:
  401. # TODO: what about resolution?
  402. RunCommand('g.region', flags = 's', vect = maps[0])
  403. else:
  404. wx.BeginBusyCursor()
  405. wx.Yield()
  406. returncode, messages = RunCommand('r.in.gdal', input = filePath,
  407. output = os.path.splitext(os.path.basename(filePath))[0],
  408. getErrorMsg = True)
  409. wx.EndBusyCursor()
  410. if returncode != 0:
  411. message = _("Attempt to import data source <%(name)s> as raster or vector failed. ") % {'name': filePath}
  412. message += "\n\n" + messagesIfVector + "\n" + messages
  413. GError(message = message)
  414. else:
  415. GMessage(message = _("Raster data source <%(name)s> imported successfully.") % {'name': filePath})
  416. stdout = RunCommand('g.list', type = 'rast', read = True)
  417. maps = stdout.splitlines()
  418. if maps:
  419. RunCommand('g.region', flags = 's', rast = maps[0])
  420. def OnManageLoc(self, event):
  421. """!Location management choice control handler
  422. """
  423. sel = event.GetSelection()
  424. if sel == 0:
  425. self.RenameMapset()
  426. elif sel == 1:
  427. self.RenameLocation()
  428. elif sel == 2:
  429. self.DeleteMapset()
  430. elif sel == 3:
  431. self.DeleteLocation()
  432. event.Skip()
  433. def RenameMapset(self):
  434. """!Rename selected mapset
  435. """
  436. location = self.listOfLocations[self.lblocations.GetSelection()]
  437. mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
  438. if mapset == 'PERMANENT':
  439. GMessage(parent = self,
  440. message = _('Mapset <PERMANENT> is required for valid GRASS location.\n\n'
  441. 'This mapset cannot be renamed.'))
  442. return
  443. dlg = wx.TextEntryDialog(parent = self,
  444. message = _('Current name: %s\n\nEnter new name:') % mapset,
  445. caption = _('Rename selected mapset'))
  446. if dlg.ShowModal() == wx.ID_OK:
  447. newmapset = dlg.GetValue()
  448. if newmapset == mapset:
  449. dlg.Destroy()
  450. return
  451. if newmapset in self.listOfMapsets:
  452. wx.MessageBox(parent = self,
  453. caption = _('Message'),
  454. message = _('Unable to rename mapset.\n\n'
  455. 'Mapset <%s> already exists in location.') % newmapset,
  456. style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  457. else:
  458. try:
  459. os.rename(os.path.join(self.gisdbase, location, mapset),
  460. os.path.join(self.gisdbase, location, newmapset))
  461. self.OnSelectLocation(None)
  462. self.lbmapsets.SetSelection(self.listOfMapsets.index(newmapset))
  463. except StandardError, e:
  464. wx.MessageBox(parent = self,
  465. caption = _('Error'),
  466. message = _('Unable to rename mapset.\n\n%s') % e,
  467. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  468. dlg.Destroy()
  469. def RenameLocation(self):
  470. """!Rename selected location
  471. """
  472. location = self.listOfLocations[self.lblocations.GetSelection()]
  473. dlg = wx.TextEntryDialog(parent = self,
  474. message = _('Current name: %s\n\nEnter new name:') % location,
  475. caption = _('Rename selected location'))
  476. if dlg.ShowModal() == wx.ID_OK:
  477. newlocation = dlg.GetValue()
  478. if newlocation == location:
  479. dlg.Destroy()
  480. return
  481. if newlocation in self.listOfLocations:
  482. wx.MessageBox(parent = self,
  483. caption = _('Message'),
  484. message = _('Unable to rename location.\n\n'
  485. 'Location <%s> already exists in GRASS database.') % newlocation,
  486. style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  487. else:
  488. try:
  489. os.rename(os.path.join(self.gisdbase, location),
  490. os.path.join(self.gisdbase, newlocation))
  491. self.UpdateLocations(self.gisdbase)
  492. self.lblocations.SetSelection(self.listOfLocations.index(newlocation))
  493. self.UpdateMapsets(newlocation)
  494. except StandardError, e:
  495. wx.MessageBox(parent = self,
  496. caption = _('Error'),
  497. message = _('Unable to rename location.\n\n%s') % e,
  498. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  499. dlg.Destroy()
  500. def DeleteMapset(self):
  501. """!Delete selected mapset
  502. """
  503. location = self.listOfLocations[self.lblocations.GetSelection()]
  504. mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
  505. if mapset == 'PERMANENT':
  506. GMessage(parent = self,
  507. message = _('Mapset <PERMANENT> is required for valid GRASS location.\n\n'
  508. 'This mapset cannot be deleted.'))
  509. return
  510. dlg = wx.MessageDialog(parent = self, message = _("Do you want to continue with deleting mapset <%(mapset)s> "
  511. "from location <%(location)s>?\n\n"
  512. "ALL MAPS included in this mapset will be "
  513. "PERMANENTLY DELETED!") % {'mapset' : mapset,
  514. 'location' : location},
  515. caption = _("Delete selected mapset"),
  516. style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  517. if dlg.ShowModal() == wx.ID_YES:
  518. try:
  519. shutil.rmtree(os.path.join(self.gisdbase, location, mapset))
  520. self.OnSelectLocation(None)
  521. self.lbmapsets.SetSelection(0)
  522. except:
  523. wx.MessageBox(message = _('Unable to delete mapset'))
  524. dlg.Destroy()
  525. def DeleteLocation(self):
  526. """
  527. Delete selected location
  528. """
  529. location = self.listOfLocations[self.lblocations.GetSelection()]
  530. dlg = wx.MessageDialog(parent = self, message = _("Do you want to continue with deleting "
  531. "location <%s>?\n\n"
  532. "ALL MAPS included in this location will be "
  533. "PERMANENTLY DELETED!") % (location),
  534. caption = _("Delete selected location"),
  535. style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  536. if dlg.ShowModal() == wx.ID_YES:
  537. try:
  538. shutil.rmtree(os.path.join(self.gisdbase, location))
  539. self.UpdateLocations(self.gisdbase)
  540. self.lblocations.SetSelection(0)
  541. self.OnSelectLocation(None)
  542. self.lbmapsets.SetSelection(0)
  543. except:
  544. wx.MessageBox(message = _('Unable to delete location'))
  545. dlg.Destroy()
  546. def UpdateLocations(self, dbase):
  547. """!Update list of locations"""
  548. try:
  549. self.listOfLocations = GetListOfLocations(dbase)
  550. except UnicodeEncodeError:
  551. wx.MessageBox(parent = self, caption = _("Error"),
  552. message = _("Unable to set GRASS database. "
  553. "Check your locale settings."),
  554. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  555. self.lblocations.Clear()
  556. self.lblocations.InsertItems(self.listOfLocations, 0)
  557. if len(self.listOfLocations) > 0:
  558. self.lblocations.SetSelection(0)
  559. else:
  560. self.lblocations.SetSelection(wx.NOT_FOUND)
  561. return self.listOfLocations
  562. def UpdateMapsets(self, location):
  563. """!Update list of mapsets"""
  564. self.FormerMapsetSelection = wx.NOT_FOUND # for non-selectable item
  565. self.listOfMapsetsSelectable = list()
  566. self.listOfMapsets = GetListOfMapsets(self.gisdbase, location)
  567. self.lbmapsets.Clear()
  568. # disable mapset with denied permission
  569. locationName = os.path.basename(location)
  570. ret = RunCommand('g.mapset',
  571. read = True,
  572. flags = 'l',
  573. location = locationName,
  574. gisdbase = self.gisdbase)
  575. if ret:
  576. for line in ret.splitlines():
  577. self.listOfMapsetsSelectable += line.split(' ')
  578. else:
  579. RunCommand("g.gisenv",
  580. set = "GISDBASE=%s" % self.gisdbase)
  581. RunCommand("g.gisenv",
  582. set = "LOCATION_NAME=%s" % locationName)
  583. RunCommand("g.gisenv",
  584. set = "MAPSET=PERMANENT")
  585. # first run only
  586. self.listOfMapsetsSelectable = copy.copy(self.listOfMapsets)
  587. disabled = []
  588. idx = 0
  589. for mapset in self.listOfMapsets:
  590. if mapset not in self.listOfMapsetsSelectable or \
  591. os.path.isfile(os.path.join(self.gisdbase,
  592. locationName,
  593. mapset, ".gislock")):
  594. disabled.append(idx)
  595. idx += 1
  596. self.lbmapsets.InsertItems(self.listOfMapsets, 0, disabled = disabled)
  597. return self.listOfMapsets
  598. def OnSelectLocation(self, event):
  599. """!Location selected"""
  600. if event:
  601. self.lblocations.SetSelection(event.GetIndex())
  602. if self.lblocations.GetSelection() != wx.NOT_FOUND:
  603. self.UpdateMapsets(os.path.join(self.gisdbase,
  604. self.listOfLocations[self.lblocations.GetSelection()]))
  605. else:
  606. self.listOfMapsets = []
  607. disabled = []
  608. idx = 0
  609. try:
  610. locationName = self.listOfLocations[self.lblocations.GetSelection()]
  611. except IndexError:
  612. locationName = ''
  613. for mapset in self.listOfMapsets:
  614. if mapset not in self.listOfMapsetsSelectable or \
  615. os.path.isfile(os.path.join(self.gisdbase,
  616. locationName,
  617. mapset, ".gislock")):
  618. disabled.append(idx)
  619. idx += 1
  620. self.lbmapsets.Clear()
  621. self.lbmapsets.InsertItems(self.listOfMapsets, 0, disabled = disabled)
  622. if len(self.listOfMapsets) > 0:
  623. self.lbmapsets.SetSelection(0)
  624. if locationName:
  625. # enable start button when location and mapset is selected
  626. self.bstart.Enable()
  627. self.bmapset.Enable()
  628. self.manageloc.Enable()
  629. else:
  630. self.lbmapsets.SetSelection(wx.NOT_FOUND)
  631. self.bstart.Enable(False)
  632. self.bmapset.Enable(False)
  633. self.manageloc.Enable(False)
  634. def OnSelectMapset(self, event):
  635. """!Mapset selected"""
  636. self.lbmapsets.SetSelection(event.GetIndex())
  637. if event.GetText() not in self.listOfMapsetsSelectable:
  638. self.lbmapsets.SetSelection(self.FormerMapsetSelection)
  639. else:
  640. self.FormerMapsetSelection = event.GetIndex()
  641. event.Skip()
  642. def OnSetDatabase(self, event):
  643. """!Database set"""
  644. self.gisdbase = self.tgisdbase.GetValue()
  645. self.UpdateLocations(self.gisdbase)
  646. self.OnSelectLocation(None)
  647. def OnBrowse(self, event):
  648. """'Browse' button clicked"""
  649. if not event:
  650. defaultPath = os.getenv('HOME')
  651. else:
  652. defaultPath = ""
  653. dlg = wx.DirDialog(parent = self, message = _("Choose GIS Data Directory"),
  654. defaultPath = defaultPath, style = wx.DD_DEFAULT_STYLE)
  655. if dlg.ShowModal() == wx.ID_OK:
  656. self.gisdbase = dlg.GetPath()
  657. self.tgisdbase.SetValue(self.gisdbase)
  658. self.OnSetDatabase(event)
  659. dlg.Destroy()
  660. def OnCreateMapset(self,event):
  661. """!Create new mapset"""
  662. self.gisdbase = self.tgisdbase.GetValue()
  663. location = self.listOfLocations[self.lblocations.GetSelection()]
  664. dlg = wx.TextEntryDialog(parent = self,
  665. message = _('Enter name for new mapset:'),
  666. caption = _('Create new mapset'))
  667. if dlg.ShowModal() == wx.ID_OK:
  668. mapset = dlg.GetValue()
  669. if mapset in self.listOfMapsets:
  670. GMessage(parent = self,
  671. message = _("Mapset <%s> already exists.") % mapset)
  672. return
  673. if mapset.lower() == 'ogr':
  674. dlg1 = wx.MessageDialog(parent = self,
  675. message = _("Mapset <%s> is reserved for direct "
  676. "read access to OGR layers. Please consider to use "
  677. "another name for your mapset.\n\n"
  678. "Are you really sure that you want to create this mapset?") % mapset,
  679. caption = _("Reserved mapset name"),
  680. style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  681. ret = dlg1.ShowModal()
  682. dlg1.Destroy()
  683. if ret == wx.ID_NO:
  684. dlg.Destroy()
  685. return
  686. try:
  687. os.mkdir(os.path.join(self.gisdbase, location, mapset))
  688. # copy WIND file and its permissions from PERMANENT and set permissions to u+rw,go+r
  689. shutil.copy(os.path.join(self.gisdbase, location, 'PERMANENT', 'WIND'),
  690. os.path.join(self.gisdbase, location, mapset))
  691. # os.chmod(os.path.join(database,location,mapset,'WIND'), 0644)
  692. self.OnSelectLocation(None)
  693. self.lbmapsets.SetSelection(self.listOfMapsets.index(mapset))
  694. except StandardError, e:
  695. GError(parent = self,
  696. message = _("Unable to create new mapset: %s") % e,
  697. showTraceback = False)
  698. return False
  699. dlg.Destroy()
  700. self.bstart.SetFocus()
  701. return True
  702. def OnStart(self, event):
  703. """'Start GRASS' button clicked"""
  704. dbase = self.tgisdbase.GetValue()
  705. location = self.listOfLocations[self.lblocations.GetSelection()]
  706. mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
  707. lockfile = os.path.join(dbase, location, mapset, '.gislock')
  708. if os.path.isfile(lockfile):
  709. dlg = wx.MessageDialog(parent = self,
  710. message = _("GRASS is already running in selected mapset <%(mapset)s>\n"
  711. "(file %(lock)s found).\n\n"
  712. "Concurrent use not allowed.\n\n"
  713. "Do you want to try to remove .gislock (note that you "
  714. "need permission for this operation) and continue?") %
  715. { 'mapset' : mapset, 'lock' : lockfile },
  716. caption = _("Lock file found"),
  717. style = wx.YES_NO | wx.NO_DEFAULT |
  718. wx.ICON_QUESTION | wx.CENTRE)
  719. ret = dlg.ShowModal()
  720. dlg.Destroy()
  721. if ret == wx.ID_YES:
  722. dlg1 = wx.MessageDialog(parent = self,
  723. message = _("ARE YOU REALLY SURE?\n\n"
  724. "If you really are running another GRASS session doing this "
  725. "could corrupt your data. Have another look in the processor "
  726. "manager just to be sure..."),
  727. caption = _("Lock file found"),
  728. style = wx.YES_NO | wx.NO_DEFAULT |
  729. wx.ICON_QUESTION | wx.CENTRE)
  730. ret = dlg1.ShowModal()
  731. dlg1.Destroy()
  732. if ret == wx.ID_YES:
  733. try:
  734. os.remove(lockfile)
  735. except IOError, e:
  736. GError(_("Unable to remove '%(lock)s'.\n\n"
  737. "Details: %(reason)s") % { 'lock' : lockfile, 'reason' : e})
  738. else:
  739. return
  740. else:
  741. return
  742. self.SetLocation(dbase, location, mapset)
  743. self.ExitSuccessfully()
  744. def SetLocation(self, dbase, location, mapset):
  745. RunCommand("g.gisenv",
  746. set = "GISDBASE=%s" % dbase)
  747. RunCommand("g.gisenv",
  748. set = "LOCATION_NAME=%s" % location)
  749. RunCommand("g.gisenv",
  750. set = "MAPSET=%s" % mapset)
  751. def ExitSuccessfully(self):
  752. self.Destroy()
  753. sys.exit(0)
  754. def OnExit(self, event):
  755. """'Exit' button clicked"""
  756. self.Destroy()
  757. sys.exit(2)
  758. def OnHelp(self, event):
  759. """'Help' button clicked"""
  760. # help text in lib/init/helptext.html
  761. RunCommand('g.manual', entry = 'helptext')
  762. def OnCloseWindow(self, event):
  763. """!Close window event"""
  764. event.Skip()
  765. sys.exit(2)
  766. class GListBox(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin):
  767. """!Use wx.ListCtrl instead of wx.ListBox, different style for
  768. non-selectable items (e.g. mapsets with denied permission)"""
  769. def __init__(self, parent, id, size,
  770. choices, disabled = []):
  771. wx.ListCtrl.__init__(self, parent, id, size = size,
  772. style = wx.LC_REPORT | wx.LC_NO_HEADER | wx.LC_SINGLE_SEL |
  773. wx.BORDER_SUNKEN)
  774. listmix.ListCtrlAutoWidthMixin.__init__(self)
  775. self.InsertColumn(0, '')
  776. self.selected = wx.NOT_FOUND
  777. self._LoadData(choices, disabled)
  778. def _LoadData(self, choices, disabled = []):
  779. """!Load data into list
  780. @param choices list of item
  781. @param disabled list of indeces of non-selectable items
  782. """
  783. idx = 0
  784. for item in choices:
  785. index = self.InsertStringItem(sys.maxint, item)
  786. self.SetStringItem(index, 0, item)
  787. if idx in disabled:
  788. self.SetItemTextColour(idx, wx.Colour(150, 150, 150))
  789. idx += 1
  790. def Clear(self):
  791. self.DeleteAllItems()
  792. def InsertItems(self, choices, pos, disabled = []):
  793. self._LoadData(choices, disabled)
  794. def SetSelection(self, item, force = False):
  795. if item != wx.NOT_FOUND and \
  796. (platform.system() != 'Windows' or force):
  797. ### Windows -> FIXME
  798. self.SetItemState(item, wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED)
  799. self.selected = item
  800. def GetSelection(self):
  801. return self.selected
  802. class StartUp(wx.App):
  803. """!Start-up application"""
  804. def OnInit(self):
  805. wx.InitAllImageHandlers()
  806. StartUp = GRASSStartup()
  807. StartUp.CenterOnScreen()
  808. self.SetTopWindow(StartUp)
  809. StartUp.Show()
  810. if StartUp.GetRCValue("LOCATION_NAME") == "<UNKNOWN>":
  811. wx.MessageBox(parent = StartUp,
  812. caption = _('Starting GRASS for the first time'),
  813. message = _('GRASS needs a directory in which to store its data. '
  814. 'Create one now if you have not already done so. '
  815. 'A popular choice is "grassdata", located in '
  816. 'your home directory.'),
  817. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  818. StartUp.OnBrowse(None)
  819. return 1
  820. if __name__ == "__main__":
  821. if os.getenv("GISBASE") is None:
  822. sys.exit("Failed to start GUI, GRASS GIS is not running.")
  823. import gettext
  824. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  825. GRASSStartUp = StartUp(0)
  826. GRASSStartUp.MainLoop()