gis_set.py 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250
  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-2014 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. import getpass
  23. from core import globalvar
  24. from core.utils import _
  25. import wx
  26. import wx.lib.mixins.listctrl as listmix
  27. from grass.script import core as grass
  28. from core.gcmd import GMessage, GError, DecodeString, RunCommand
  29. from core.utils import GetListOfLocations, GetListOfMapsets
  30. from location_wizard.dialogs import RegionDef
  31. from gui_core.dialogs import TextEntryDialog
  32. from gui_core.widgets import GenericValidator, StaticWrapText
  33. from gui_core.wrap import Button
  34. from gui_core.wrap import ListCtrl
  35. sys.stderr = codecs.getwriter('utf8')(sys.stderr)
  36. class GRASSStartup(wx.Frame):
  37. exit_success = 0
  38. # 2 is file not found from python interpreter
  39. exit_user_requested = 5
  40. """GRASS start-up screen"""
  41. def __init__(self, parent=None, id=wx.ID_ANY,
  42. style=wx.DEFAULT_FRAME_STYLE):
  43. #
  44. # GRASS variables
  45. #
  46. self.gisbase = os.getenv("GISBASE")
  47. self.grassrc = self._readGisRC()
  48. self.gisdbase = self.GetRCValue("GISDBASE")
  49. #
  50. # list of locations/mapsets
  51. #
  52. self.listOfLocations = []
  53. self.listOfMapsets = []
  54. self.listOfMapsetsSelectable = []
  55. wx.Frame.__init__(self, parent=parent, id=id, style=style)
  56. self.locale = wx.Locale(language=wx.LANGUAGE_DEFAULT)
  57. # scroll panel was used here but not properly and is probably not need
  58. # as long as it is not high too much
  59. self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
  60. # i18N
  61. #
  62. # graphical elements
  63. #
  64. # image
  65. try:
  66. if os.getenv('ISISROOT'):
  67. name = os.path.join(
  68. globalvar.GUIDIR,
  69. "images",
  70. "startup_banner_isis.png")
  71. else:
  72. name = os.path.join(
  73. globalvar.GUIDIR, "images", "startup_banner.png")
  74. self.hbitmap = wx.StaticBitmap(self.panel, wx.ID_ANY,
  75. wx.Bitmap(name=name,
  76. type=wx.BITMAP_TYPE_PNG))
  77. except:
  78. self.hbitmap = wx.StaticBitmap(
  79. self.panel, wx.ID_ANY, wx.BitmapFromImage(
  80. wx.EmptyImage(530, 150)))
  81. # labels
  82. # crashes when LOCATION doesn't exist
  83. # get version & revision
  84. versionFile = open(os.path.join(globalvar.ETCDIR, "VERSIONNUMBER"))
  85. versionLine = versionFile.readline().rstrip('\n')
  86. versionFile.close()
  87. try:
  88. grassVersion, grassRevision = versionLine.split(' ', 1)
  89. if grassVersion.endswith('svn'):
  90. grassRevisionStr = ' (%s)' % grassRevision
  91. else:
  92. grassRevisionStr = ''
  93. except ValueError:
  94. grassVersion = versionLine
  95. grassRevisionStr = ''
  96. self.gisdbase_box = wx.StaticBox(
  97. parent=self.panel, id=wx.ID_ANY, label=" %s " %
  98. _("1. Select GRASS GIS database directory"))
  99. self.location_box = wx.StaticBox(
  100. parent=self.panel, id=wx.ID_ANY, label=" %s " %
  101. _("2. Select GRASS Location"))
  102. self.mapset_box = wx.StaticBox(
  103. parent=self.panel, id=wx.ID_ANY, label=" %s " %
  104. _("3. Select GRASS Mapset"))
  105. self.lmessage = wx.StaticText(parent=self.panel)
  106. # It is not clear if all wx versions supports color, so try-except.
  107. # The color itself may not be correct for all platforms/system settings
  108. # but in http://xoomer.virgilio.it/infinity77/wxPython/Widgets/wx.SystemSettings.html
  109. # there is no 'warning' color.
  110. try:
  111. self.lmessage.SetForegroundColour(wx.Colour(255, 0, 0))
  112. except AttributeError:
  113. pass
  114. self.gisdbase_panel = wx.Panel(parent=self.panel)
  115. self.location_panel = wx.Panel(parent=self.panel)
  116. self.mapset_panel = wx.Panel(parent=self.panel)
  117. self.ldbase = wx.StaticText(
  118. parent=self.gisdbase_panel, id=wx.ID_ANY,
  119. label=_("GRASS GIS database directory contains Locations."))
  120. self.llocation = StaticWrapText(
  121. parent=self.location_panel, id=wx.ID_ANY,
  122. label=_("All data in one Location is in the same "
  123. " coordinate reference system (projection)."
  124. " One Location can be one project."
  125. " Location contains Mapsets."),
  126. style=wx.ALIGN_LEFT)
  127. self.lmapset = StaticWrapText(
  128. parent=self.mapset_panel, id=wx.ID_ANY,
  129. label=_("Mapset contains GIS data related"
  130. " to one project, task within one project,"
  131. " subregion or user."),
  132. style=wx.ALIGN_LEFT)
  133. try:
  134. for label in [self.ldbase, self.llocation, self.lmapset]:
  135. label.SetForegroundColour(
  136. wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))
  137. except AttributeError:
  138. # for explanation of try-except see above
  139. pass
  140. # buttons
  141. self.bstart = Button(parent=self.panel, id=wx.ID_ANY,
  142. label=_("Start &GRASS session"))
  143. self.bstart.SetDefault()
  144. self.bexit = Button(parent=self.panel, id=wx.ID_EXIT)
  145. self.bstart.SetMinSize((180, self.bexit.GetSize()[1]))
  146. self.bhelp = Button(parent=self.panel, id=wx.ID_HELP)
  147. self.bbrowse = Button(parent=self.gisdbase_panel, id=wx.ID_ANY,
  148. label=_("&Browse"))
  149. self.bmapset = Button(parent=self.mapset_panel, id=wx.ID_ANY,
  150. # GTC New mapset
  151. label=_("&New"))
  152. self.bmapset.SetToolTip(_("Create a new Mapset in selected Location"))
  153. self.bwizard = Button(parent=self.location_panel, id=wx.ID_ANY,
  154. # GTC New location
  155. label=_("N&ew"))
  156. self.bwizard.SetToolTip(
  157. _(
  158. "Create a new location using location wizard."
  159. " After location is created successfully,"
  160. " GRASS session is started."))
  161. self.rename_location_button = Button(parent=self.location_panel, id=wx.ID_ANY,
  162. # GTC Rename location
  163. label=_("Ren&ame"))
  164. self.rename_location_button.SetToolTip(_("Rename selected location"))
  165. self.delete_location_button = Button(parent=self.location_panel, id=wx.ID_ANY,
  166. # GTC Delete location
  167. label=_("De&lete"))
  168. self.delete_location_button.SetToolTip(_("Delete selected location"))
  169. self.download_location_button = Button(parent=self.location_panel, id=wx.ID_ANY,
  170. label=_("Do&wnload"))
  171. self.download_location_button.SetToolTip(_("Download sample location"))
  172. self.rename_mapset_button = Button(parent=self.mapset_panel, id=wx.ID_ANY,
  173. # GTC Rename mapset
  174. label=_("&Rename"))
  175. self.rename_mapset_button.SetToolTip(_("Rename selected mapset"))
  176. self.delete_mapset_button = Button(parent=self.mapset_panel, id=wx.ID_ANY,
  177. # GTC Delete mapset
  178. label=_("&Delete"))
  179. self.delete_mapset_button.SetToolTip(_("Delete selected mapset"))
  180. # textinputs
  181. self.tgisdbase = wx.TextCtrl(
  182. parent=self.gisdbase_panel, id=wx.ID_ANY, value="", size=(
  183. 300, -1), style=wx.TE_PROCESS_ENTER)
  184. # Locations
  185. self.lblocations = GListBox(parent=self.location_panel,
  186. id=wx.ID_ANY, size=(180, 200),
  187. choices=self.listOfLocations)
  188. self.lblocations.SetColumnWidth(0, 180)
  189. # TODO: sort; but keep PERMANENT on top of list
  190. # Mapsets
  191. self.lbmapsets = GListBox(parent=self.mapset_panel,
  192. id=wx.ID_ANY, size=(180, 200),
  193. choices=self.listOfMapsets)
  194. self.lbmapsets.SetColumnWidth(0, 180)
  195. # layout & properties, first do layout so everything is created
  196. self._do_layout()
  197. self._set_properties(grassVersion, grassRevisionStr)
  198. # events
  199. self.bbrowse.Bind(wx.EVT_BUTTON, self.OnBrowse)
  200. self.bstart.Bind(wx.EVT_BUTTON, self.OnStart)
  201. self.bexit.Bind(wx.EVT_BUTTON, self.OnExit)
  202. self.bhelp.Bind(wx.EVT_BUTTON, self.OnHelp)
  203. self.bmapset.Bind(wx.EVT_BUTTON, self.OnCreateMapset)
  204. self.bwizard.Bind(wx.EVT_BUTTON, self.OnWizard)
  205. self.rename_location_button.Bind(wx.EVT_BUTTON, self.RenameLocation)
  206. self.delete_location_button.Bind(wx.EVT_BUTTON, self.DeleteLocation)
  207. self.download_location_button.Bind(wx.EVT_BUTTON, self.DownloadLocation)
  208. self.rename_mapset_button.Bind(wx.EVT_BUTTON, self.RenameMapset)
  209. self.delete_mapset_button.Bind(wx.EVT_BUTTON, self.DeleteMapset)
  210. self.lblocations.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectLocation)
  211. self.lbmapsets.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectMapset)
  212. self.lbmapsets.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnStart)
  213. self.tgisdbase.Bind(wx.EVT_TEXT_ENTER, self.OnSetDatabase)
  214. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  215. def _set_properties(self, version, revision):
  216. """Set frame properties"""
  217. self.SetTitle(_("GRASS GIS %s startup%s") % (version, revision))
  218. self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, "grass.ico"),
  219. wx.BITMAP_TYPE_ICO))
  220. self.bstart.SetForegroundColour(wx.Colour(35, 142, 35))
  221. self.bstart.SetToolTip(_("Enter GRASS session"))
  222. self.bstart.Enable(False)
  223. self.bmapset.Enable(False)
  224. # this all was originally a choice, perhaps just mapset needed
  225. self.rename_location_button.Enable(False)
  226. self.delete_location_button.Enable(False)
  227. self.rename_mapset_button.Enable(False)
  228. self.delete_mapset_button.Enable(False)
  229. # set database
  230. if not self.gisdbase:
  231. # sets an initial path for gisdbase if nothing in GISRC
  232. if os.path.isdir(os.getenv("HOME")):
  233. self.gisdbase = os.getenv("HOME")
  234. else:
  235. self.gisdbase = os.getcwd()
  236. try:
  237. self.tgisdbase.SetValue(self.gisdbase)
  238. except UnicodeDecodeError:
  239. wx.MessageBox(parent=self, caption=_("Error"),
  240. message=_("Unable to set GRASS database. "
  241. "Check your locale settings."),
  242. style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  243. self.OnSetDatabase(None)
  244. location = self.GetRCValue("LOCATION_NAME")
  245. if location == "<UNKNOWN>":
  246. return
  247. if not os.path.isdir(os.path.join(self.gisdbase, location)):
  248. location = None
  249. # list of locations
  250. self.UpdateLocations(self.gisdbase)
  251. try:
  252. self.lblocations.SetSelection(self.listOfLocations.index(location),
  253. force=True)
  254. self.lblocations.EnsureVisible(
  255. self.listOfLocations.index(location))
  256. except ValueError:
  257. sys.stderr.write(
  258. _("ERROR: Location <%s> not found\n") %
  259. self.GetRCValue("LOCATION_NAME"))
  260. if len(self.listOfLocations) > 0:
  261. self.lblocations.SetSelection(0, force=True)
  262. self.lblocations.EnsureVisible(0)
  263. location = self.listOfLocations[0]
  264. else:
  265. return
  266. # list of mapsets
  267. self.UpdateMapsets(os.path.join(self.gisdbase, location))
  268. mapset = self.GetRCValue("MAPSET")
  269. if mapset:
  270. try:
  271. self.lbmapsets.SetSelection(self.listOfMapsets.index(mapset),
  272. force=True)
  273. self.lbmapsets.EnsureVisible(self.listOfMapsets.index(mapset))
  274. except ValueError:
  275. sys.stderr.write(_("ERROR: Mapset <%s> not found\n") % mapset)
  276. self.lbmapsets.SetSelection(0, force=True)
  277. self.lbmapsets.EnsureVisible(0)
  278. def _do_layout(self):
  279. sizer = wx.BoxSizer(wx.VERTICAL)
  280. self.sizer = sizer # for the layout call after changing message
  281. dbase_sizer = wx.BoxSizer(wx.HORIZONTAL)
  282. location_mapset_sizer = wx.BoxSizer(wx.HORIZONTAL)
  283. gisdbase_panel_sizer = wx.BoxSizer(wx.VERTICAL)
  284. gisdbase_boxsizer = wx.StaticBoxSizer(self.gisdbase_box, wx.VERTICAL)
  285. btns_sizer = wx.BoxSizer(wx.HORIZONTAL)
  286. self.gisdbase_panel.SetSizer(gisdbase_panel_sizer)
  287. # gis data directory
  288. gisdbase_boxsizer.Add(self.gisdbase_panel, proportion=1,
  289. flag=wx.EXPAND | wx.ALL,
  290. border=1)
  291. gisdbase_panel_sizer.Add(dbase_sizer, proportion=1,
  292. flag=wx.EXPAND | wx.ALL,
  293. border=1)
  294. gisdbase_panel_sizer.Add(self.ldbase, proportion=0,
  295. flag=wx.EXPAND | wx.ALL,
  296. border=1)
  297. dbase_sizer.Add(self.tgisdbase, proportion=1,
  298. flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  299. border=1)
  300. dbase_sizer.Add(self.bbrowse, proportion=0,
  301. flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  302. border=1)
  303. gisdbase_panel_sizer.Fit(self.gisdbase_panel)
  304. # location and mapset lists
  305. def layout_list_box(box, panel, list_box, buttons, description):
  306. panel_sizer = wx.BoxSizer(wx.VERTICAL)
  307. main_sizer = wx.BoxSizer(wx.HORIZONTAL)
  308. box_sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  309. buttons_sizer = wx.BoxSizer(wx.VERTICAL)
  310. panel.SetSizer(panel_sizer)
  311. panel_sizer.Fit(panel)
  312. main_sizer.Add(list_box, proportion=1,
  313. flag=wx.EXPAND | wx.ALL,
  314. border=1)
  315. main_sizer.Add(buttons_sizer, proportion=0,
  316. flag=wx.ALIGN_CENTER_HORIZONTAL | wx.ALL,
  317. border=1)
  318. for button in buttons:
  319. buttons_sizer.Add(button, proportion=0,
  320. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  321. border=3)
  322. box_sizer.Add(panel, proportion=1,
  323. flag=wx.EXPAND | wx.ALL,
  324. border=1)
  325. panel_sizer.Add(main_sizer, proportion=1,
  326. flag=wx.EXPAND | wx.ALL,
  327. border=1)
  328. panel_sizer.Add(description, proportion=0,
  329. flag=wx.EXPAND | wx.ALL,
  330. border=1)
  331. return box_sizer
  332. location_boxsizer = layout_list_box(
  333. box=self.location_box,
  334. panel=self.location_panel,
  335. list_box=self.lblocations,
  336. buttons=[self.bwizard, self.rename_location_button,
  337. self.delete_location_button,
  338. self.download_location_button],
  339. description=self.llocation)
  340. mapset_boxsizer = layout_list_box(
  341. box=self.mapset_box,
  342. panel=self.mapset_panel,
  343. list_box=self.lbmapsets,
  344. buttons=[self.bmapset, self.rename_mapset_button,
  345. self.delete_mapset_button],
  346. description=self.lmapset)
  347. # location and mapset sizer
  348. location_mapset_sizer.Add(location_boxsizer, proportion=1,
  349. flag=wx.LEFT | wx.RIGHT | wx.EXPAND,
  350. border=3)
  351. location_mapset_sizer.Add(mapset_boxsizer, proportion=1,
  352. flag=wx.RIGHT | wx.EXPAND,
  353. border=3)
  354. # buttons
  355. btns_sizer.Add(self.bstart, proportion=0,
  356. flag=wx.ALIGN_CENTER_HORIZONTAL |
  357. wx.ALIGN_CENTER_VERTICAL |
  358. wx.ALL,
  359. border=5)
  360. btns_sizer.Add(self.bexit, proportion=0,
  361. flag=wx.ALIGN_CENTER_HORIZONTAL |
  362. wx.ALIGN_CENTER_VERTICAL |
  363. wx.ALL,
  364. border=5)
  365. btns_sizer.Add(self.bhelp, proportion=0,
  366. flag=wx.ALIGN_CENTER_HORIZONTAL |
  367. wx.ALIGN_CENTER_VERTICAL |
  368. wx.ALL,
  369. border=5)
  370. # main sizer
  371. sizer.Add(self.hbitmap,
  372. proportion=0,
  373. flag=wx.ALIGN_CENTER_VERTICAL |
  374. wx.ALIGN_CENTER_HORIZONTAL |
  375. wx.ALL,
  376. border=3) # image
  377. sizer.Add(gisdbase_boxsizer, proportion=0,
  378. flag=wx.ALIGN_CENTER_HORIZONTAL |
  379. wx.RIGHT | wx.LEFT | wx.TOP | wx.EXPAND,
  380. border=3) # GISDBASE setting
  381. # warning/error message
  382. sizer.Add(self.lmessage,
  383. proportion=0,
  384. flag=wx.ALIGN_CENTER_VERTICAL |
  385. wx.ALIGN_LEFT | wx.ALL | wx.EXPAND, border=5)
  386. sizer.Add(location_mapset_sizer, proportion=1,
  387. flag=wx.RIGHT | wx.LEFT | wx.EXPAND,
  388. border=1)
  389. sizer.Add(btns_sizer, proportion=0,
  390. flag=wx.ALIGN_CENTER_VERTICAL |
  391. wx.ALIGN_CENTER_HORIZONTAL |
  392. wx.RIGHT | wx.LEFT,
  393. border=3)
  394. self.panel.SetAutoLayout(True)
  395. self.panel.SetSizer(sizer)
  396. sizer.Fit(self.panel)
  397. sizer.SetSizeHints(self)
  398. self.Layout()
  399. def _readGisRC(self):
  400. """Read variables from $HOME/.grass7/rc file
  401. """
  402. grassrc = {}
  403. gisrc = os.getenv("GISRC")
  404. if gisrc and os.path.isfile(gisrc):
  405. try:
  406. rc = open(gisrc, "r")
  407. for line in rc.readlines():
  408. try:
  409. key, val = line.split(":", 1)
  410. except ValueError as e:
  411. sys.stderr.write(
  412. _('Invalid line in GISRC file (%s):%s\n' % (e, line)))
  413. grassrc[key.strip()] = DecodeString(val.strip())
  414. finally:
  415. rc.close()
  416. return grassrc
  417. def _showWarning(self, text):
  418. """Displays a warning, hint or info message to the user.
  419. This function can be used for all kinds of messages except for
  420. error messages.
  421. .. note::
  422. There is no cleaning procedure. You should call _hideMessage when
  423. you know that there is everything correct now.
  424. """
  425. self.lmessage.SetLabel(text)
  426. self.lmessage.Wrap(self.GetClientSize()[0])
  427. self.sizer.Layout()
  428. def _showError(self, text):
  429. """Displays a error message to the user.
  430. This function should be used only when something serious and unexpected
  431. happens, otherwise _showWarning should be used.
  432. .. note::
  433. There is no cleaning procedure. You should call _hideMessage when
  434. you know that there is everything correct now.
  435. """
  436. self.lmessage.SetLabel(_("Error: {text}").format(text=text))
  437. self.lmessage.Wrap(self.GetClientSize()[0])
  438. self.sizer.Layout()
  439. def _hideMessage(self):
  440. """Clears/hides the error message."""
  441. # we do no hide widget
  442. # because we do not want the dialog to change the size
  443. self.lmessage.SetLabel("")
  444. self.sizer.Layout()
  445. def GetRCValue(self, value):
  446. """Return GRASS variable (read from GISRC)
  447. """
  448. if value in self.grassrc:
  449. return self.grassrc[value]
  450. else:
  451. return None
  452. def SuggestDatabase(self):
  453. """Suggest (set) possible GRASS Database value"""
  454. # only if nothing is set (<UNKNOWN> comes from init script)
  455. if self.GetRCValue("LOCATION_NAME") != "<UNKNOWN>":
  456. return
  457. home = os.path.expanduser('~')
  458. # try some common directories for grassdata
  459. # always assuming grassdata (lowercase)
  460. # home for Linux
  461. # Documents and My Documents for Windows
  462. # potential translations (old Windows and some Linux)
  463. # but ~ and ~/Documents should cover most of the cases
  464. candidates = [
  465. os.path.join(home, "grassdata"),
  466. os.path.join(home, "Documents", "grassdata"),
  467. os.path.join(home, "My Documents", "grassdata"),
  468. ]
  469. try:
  470. # here goes everything which has potential unicode issues
  471. candidates.append(os.path.join(home, _("Documents"), "grassdata"))
  472. candidates.append(os.path.join(home, _("My Documents"), "grassdata"))
  473. except UnicodeDecodeError:
  474. # just ignore the errors if it doesn't work
  475. pass
  476. path = None
  477. for candidate in candidates:
  478. if os.path.exists(candidate):
  479. path = candidate
  480. if path:
  481. try:
  482. self.tgisdbase.SetValue(path)
  483. except UnicodeDecodeError:
  484. # restore previous state
  485. # wizard gives error in this case, we just ignore
  486. path = None
  487. self.tgisdbase.SetValue(self.gisdbase)
  488. # if we still have path
  489. if path:
  490. self.gisdbase = path
  491. self.OnSetDatabase(None)
  492. else:
  493. # nothing found
  494. # TODO: should it be warning, hint or message?
  495. self._showWarning(_(
  496. 'GRASS needs a directory (GRASS database) '
  497. 'in which to store its data. '
  498. 'Create one now if you have not already done so. '
  499. 'A popular choice is "grassdata", located in '
  500. 'your home directory. '
  501. 'Press Browse button to select the directory.'))
  502. def OnWizard(self, event):
  503. """Location wizard started"""
  504. from location_wizard.wizard import LocationWizard
  505. gWizard = LocationWizard(parent=self,
  506. grassdatabase=self.tgisdbase.GetValue())
  507. if gWizard.location is not None:
  508. self.tgisdbase.SetValue(gWizard.grassdatabase)
  509. self.OnSetDatabase(None)
  510. self.UpdateMapsets(os.path.join(self.gisdbase, gWizard.location))
  511. self.lblocations.SetSelection(
  512. self.listOfLocations.index(
  513. gWizard.location))
  514. self.lbmapsets.SetSelection(0)
  515. self.SetLocation(self.gisdbase, gWizard.location, 'PERMANENT')
  516. if gWizard.georeffile:
  517. message = _("Do you want to import <%(name)s> to the newly created location?") % {
  518. 'name': gWizard.georeffile}
  519. dlg = wx.MessageDialog(parent=self, message=message, caption=_(
  520. "Import data?"), style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  521. dlg.CenterOnParent()
  522. if dlg.ShowModal() == wx.ID_YES:
  523. self.ImportFile(gWizard.georeffile)
  524. dlg.Destroy()
  525. if gWizard.default_region:
  526. defineRegion = RegionDef(self, location=gWizard.location)
  527. defineRegion.CenterOnParent()
  528. defineRegion.ShowModal()
  529. defineRegion.Destroy()
  530. if gWizard.user_mapset:
  531. dlg = TextEntryDialog(
  532. parent=self,
  533. message=_("New mapset:"),
  534. caption=_("Create new mapset"),
  535. defaultValue=self._getDefaultMapsetName(),
  536. validator=GenericValidator(
  537. grass.legal_name,
  538. self._nameValidationFailed
  539. ),
  540. style=wx.OK | wx.CANCEL | wx.HELP
  541. )
  542. help = dlg.FindWindowById(wx.ID_HELP)
  543. help.Bind(wx.EVT_BUTTON, self.OnHelp)
  544. if dlg.ShowModal() == wx.ID_OK:
  545. mapsetName = dlg.GetValue()
  546. self.CreateNewMapset(mapsetName)
  547. def ImportFile(self, filePath):
  548. """Tries to import file as vector or raster.
  549. If successfull sets default region from imported map.
  550. """
  551. RunCommand('db.connect', flags='c')
  552. mapName = os.path.splitext(os.path.basename(filePath))[0]
  553. vectors = RunCommand('v.in.ogr', input=filePath, flags='l',
  554. read=True)
  555. wx.BeginBusyCursor()
  556. wx.Yield()
  557. if vectors:
  558. # vector detected
  559. returncode, error = RunCommand(
  560. 'v.in.ogr', input=filePath, output=mapName, flags='e',
  561. getErrorMsg=True)
  562. else:
  563. returncode, error = RunCommand(
  564. 'r.in.gdal', input=filePath, output=mapName, flags='e',
  565. getErrorMsg=True)
  566. wx.EndBusyCursor()
  567. if returncode != 0:
  568. GError(
  569. parent=self,
  570. message=_(
  571. "Import of <%(name)s> failed.\n"
  572. "Reason: %(msg)s") % ({
  573. 'name': filePath,
  574. 'msg': error}))
  575. else:
  576. GMessage(
  577. message=_(
  578. "Data file <%(name)s> imported successfully. "
  579. "The location's default region was set from this imported map.") % {
  580. 'name': filePath},
  581. parent=self)
  582. # the event can be refactored out by using lambda in bind
  583. def RenameMapset(self, event):
  584. """Rename selected mapset
  585. """
  586. location = self.listOfLocations[self.lblocations.GetSelection()]
  587. mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
  588. if mapset == 'PERMANENT':
  589. GMessage(
  590. parent=self, message=_(
  591. 'Mapset <PERMANENT> is required for valid GRASS location.\n\n'
  592. 'This mapset cannot be renamed.'))
  593. return
  594. dlg = TextEntryDialog(
  595. parent=self,
  596. message=_('Current name: %s\n\nEnter new name:') %
  597. mapset,
  598. caption=_('Rename selected mapset'),
  599. validator=GenericValidator(
  600. grass.legal_name,
  601. self._nameValidationFailed))
  602. if dlg.ShowModal() == wx.ID_OK:
  603. newmapset = dlg.GetValue()
  604. if newmapset == mapset:
  605. dlg.Destroy()
  606. return
  607. if newmapset in self.listOfMapsets:
  608. wx.MessageBox(
  609. parent=self, caption=_('Message'), message=_(
  610. 'Unable to rename mapset.\n\n'
  611. 'Mapset <%s> already exists in location.') %
  612. newmapset, style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  613. else:
  614. try:
  615. os.rename(os.path.join(self.gisdbase, location, mapset),
  616. os.path.join(self.gisdbase, location, newmapset))
  617. self.OnSelectLocation(None)
  618. self.lbmapsets.SetSelection(
  619. self.listOfMapsets.index(newmapset))
  620. except Exception as e:
  621. wx.MessageBox(
  622. parent=self,
  623. caption=_('Error'),
  624. message=_('Unable to rename mapset.\n\n%s') %
  625. e,
  626. style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  627. dlg.Destroy()
  628. def RenameLocation(self, event):
  629. """Rename selected location
  630. """
  631. location = self.listOfLocations[self.lblocations.GetSelection()]
  632. dlg = TextEntryDialog(
  633. parent=self,
  634. message=_('Current name: %s\n\nEnter new name:') %
  635. location,
  636. caption=_('Rename selected location'),
  637. validator=GenericValidator(
  638. grass.legal_name,
  639. self._nameValidationFailed))
  640. if dlg.ShowModal() == wx.ID_OK:
  641. newlocation = dlg.GetValue()
  642. if newlocation == location:
  643. dlg.Destroy()
  644. return
  645. if newlocation in self.listOfLocations:
  646. wx.MessageBox(
  647. parent=self, caption=_('Message'), message=_(
  648. 'Unable to rename location.\n\n'
  649. 'Location <%s> already exists in GRASS database.') %
  650. newlocation, style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  651. else:
  652. try:
  653. os.rename(os.path.join(self.gisdbase, location),
  654. os.path.join(self.gisdbase, newlocation))
  655. self.UpdateLocations(self.gisdbase)
  656. self.lblocations.SetSelection(
  657. self.listOfLocations.index(newlocation))
  658. self.UpdateMapsets(newlocation)
  659. except Exception as e:
  660. wx.MessageBox(
  661. parent=self,
  662. caption=_('Error'),
  663. message=_('Unable to rename location.\n\n%s') %
  664. e,
  665. style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  666. dlg.Destroy()
  667. def DeleteMapset(self, event):
  668. """Delete selected mapset
  669. """
  670. location = self.listOfLocations[self.lblocations.GetSelection()]
  671. mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
  672. if mapset == 'PERMANENT':
  673. GMessage(
  674. parent=self, message=_(
  675. 'Mapset <PERMANENT> is required for valid GRASS location.\n\n'
  676. 'This mapset cannot be deleted.'))
  677. return
  678. dlg = wx.MessageDialog(
  679. parent=self,
  680. message=_(
  681. "Do you want to continue with deleting mapset <%(mapset)s> "
  682. "from location <%(location)s>?\n\n"
  683. "ALL MAPS included in this mapset will be "
  684. "PERMANENTLY DELETED!") %
  685. {'mapset': mapset, 'location': location},
  686. caption=_("Delete selected mapset"),
  687. style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  688. if dlg.ShowModal() == wx.ID_YES:
  689. try:
  690. shutil.rmtree(os.path.join(self.gisdbase, location, mapset))
  691. self.OnSelectLocation(None)
  692. self.lbmapsets.SetSelection(0)
  693. except:
  694. wx.MessageBox(message=_('Unable to delete mapset'))
  695. dlg.Destroy()
  696. def DeleteLocation(self, event):
  697. """
  698. Delete selected location
  699. """
  700. location = self.listOfLocations[self.lblocations.GetSelection()]
  701. dlg = wx.MessageDialog(
  702. parent=self,
  703. message=_(
  704. "Do you want to continue with deleting "
  705. "location <%s>?\n\n"
  706. "ALL MAPS included in this location will be "
  707. "PERMANENTLY DELETED!") %
  708. (location),
  709. caption=_("Delete selected location"),
  710. style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  711. if dlg.ShowModal() == wx.ID_YES:
  712. try:
  713. shutil.rmtree(os.path.join(self.gisdbase, location))
  714. self.UpdateLocations(self.gisdbase)
  715. self.lblocations.SetSelection(0)
  716. self.OnSelectLocation(None)
  717. self.lbmapsets.SetSelection(0)
  718. except:
  719. wx.MessageBox(message=_('Unable to delete location'))
  720. dlg.Destroy()
  721. def DownloadLocation(self, event):
  722. """Download location online"""
  723. from startup.locdownload import LocationDownloadDialog
  724. loc_download = LocationDownloadDialog(parent=self, database=self.gisdbase)
  725. loc_download.ShowModal()
  726. location = loc_download.GetLocation()
  727. if location:
  728. # get the new location to the list
  729. self.UpdateLocations(self.gisdbase)
  730. # seems to be used in similar context
  731. self.UpdateMapsets(os.path.join(self.gisdbase, location))
  732. self.lblocations.SetSelection(
  733. self.listOfLocations.index(location))
  734. # wizard does this as well, not sure if needed
  735. self.SetLocation(self.gisdbase, location, 'PERMANENT')
  736. # seems to be used in similar context
  737. self.OnSelectLocation(None)
  738. loc_download.Destroy()
  739. def UpdateLocations(self, dbase):
  740. """Update list of locations"""
  741. try:
  742. self.listOfLocations = GetListOfLocations(dbase)
  743. except (UnicodeEncodeError, UnicodeDecodeError) as e:
  744. GError(parent=self,
  745. message=_("Unicode error detected. "
  746. "Check your locale settings. Details: {0}").format(e),
  747. showTraceback=False)
  748. self.lblocations.Clear()
  749. self.lblocations.InsertItems(self.listOfLocations, 0)
  750. if len(self.listOfLocations) > 0:
  751. self._hideMessage()
  752. self.lblocations.SetSelection(0)
  753. else:
  754. self.lblocations.SetSelection(wx.NOT_FOUND)
  755. self._showWarning(_("No GRASS Location found in '%s'."
  756. " Create a new Location or choose different"
  757. " GRASS database directory.")
  758. % self.gisdbase)
  759. return self.listOfLocations
  760. def UpdateMapsets(self, location):
  761. """Update list of mapsets"""
  762. self.FormerMapsetSelection = wx.NOT_FOUND # for non-selectable item
  763. self.listOfMapsetsSelectable = list()
  764. self.listOfMapsets = GetListOfMapsets(self.gisdbase, location)
  765. self.lbmapsets.Clear()
  766. # disable mapset with denied permission
  767. locationName = os.path.basename(location)
  768. ret = RunCommand('g.mapset',
  769. read=True,
  770. flags='l',
  771. location=locationName,
  772. gisdbase=self.gisdbase)
  773. if ret:
  774. for line in ret.splitlines():
  775. self.listOfMapsetsSelectable += line.split(' ')
  776. else:
  777. RunCommand("g.gisenv",
  778. set="GISDBASE=%s" % self.gisdbase)
  779. RunCommand("g.gisenv",
  780. set="LOCATION_NAME=%s" % locationName)
  781. RunCommand("g.gisenv",
  782. set="MAPSET=PERMANENT")
  783. # first run only
  784. self.listOfMapsetsSelectable = copy.copy(self.listOfMapsets)
  785. disabled = []
  786. idx = 0
  787. for mapset in self.listOfMapsets:
  788. if mapset not in self.listOfMapsetsSelectable or \
  789. os.path.isfile(os.path.join(self.gisdbase,
  790. locationName,
  791. mapset, ".gislock")):
  792. disabled.append(idx)
  793. idx += 1
  794. self.lbmapsets.InsertItems(self.listOfMapsets, 0, disabled=disabled)
  795. return self.listOfMapsets
  796. def OnSelectLocation(self, event):
  797. """Location selected"""
  798. if event:
  799. self.lblocations.SetSelection(event.GetIndex())
  800. if self.lblocations.GetSelection() != wx.NOT_FOUND:
  801. self.UpdateMapsets(
  802. os.path.join(
  803. self.gisdbase,
  804. self.listOfLocations[
  805. self.lblocations.GetSelection()]))
  806. else:
  807. self.listOfMapsets = []
  808. disabled = []
  809. idx = 0
  810. try:
  811. locationName = self.listOfLocations[
  812. self.lblocations.GetSelection()]
  813. except IndexError:
  814. locationName = ''
  815. for mapset in self.listOfMapsets:
  816. if mapset not in self.listOfMapsetsSelectable or \
  817. os.path.isfile(os.path.join(self.gisdbase,
  818. locationName,
  819. mapset, ".gislock")):
  820. disabled.append(idx)
  821. idx += 1
  822. self.lbmapsets.Clear()
  823. self.lbmapsets.InsertItems(self.listOfMapsets, 0, disabled=disabled)
  824. if len(self.listOfMapsets) > 0:
  825. self.lbmapsets.SetSelection(0)
  826. if locationName:
  827. # enable start button when location and mapset is selected
  828. self.bstart.Enable()
  829. self.bstart.SetFocus()
  830. self.bmapset.Enable()
  831. # replacing disabled choice, perhaps just mapset needed
  832. self.rename_location_button.Enable()
  833. self.delete_location_button.Enable()
  834. self.rename_mapset_button.Enable()
  835. self.delete_mapset_button.Enable()
  836. else:
  837. self.lbmapsets.SetSelection(wx.NOT_FOUND)
  838. self.bstart.Enable(False)
  839. self.bmapset.Enable(False)
  840. # this all was originally a choice, perhaps just mapset needed
  841. self.rename_location_button.Enable(False)
  842. self.delete_location_button.Enable(False)
  843. self.rename_mapset_button.Enable(False)
  844. self.delete_mapset_button.Enable(False)
  845. def OnSelectMapset(self, event):
  846. """Mapset selected"""
  847. self.lbmapsets.SetSelection(event.GetIndex())
  848. if event.GetText() not in self.listOfMapsetsSelectable:
  849. self.lbmapsets.SetSelection(self.FormerMapsetSelection)
  850. else:
  851. self.FormerMapsetSelection = event.GetIndex()
  852. event.Skip()
  853. def OnSetDatabase(self, event):
  854. """Database set"""
  855. gisdbase = self.tgisdbase.GetValue()
  856. self._hideMessage()
  857. if not os.path.exists(gisdbase):
  858. self._showError(_("Path '%s' doesn't exist.") % gisdbase)
  859. return
  860. self.gisdbase = self.tgisdbase.GetValue()
  861. self.UpdateLocations(self.gisdbase)
  862. self.OnSelectLocation(None)
  863. def OnBrowse(self, event):
  864. """'Browse' button clicked"""
  865. if not event:
  866. defaultPath = os.getenv('HOME')
  867. else:
  868. defaultPath = ""
  869. dlg = wx.DirDialog(parent=self, message=_("Choose GIS Data Directory"),
  870. defaultPath=defaultPath, style=wx.DD_DEFAULT_STYLE)
  871. if dlg.ShowModal() == wx.ID_OK:
  872. self.gisdbase = dlg.GetPath()
  873. self.tgisdbase.SetValue(self.gisdbase)
  874. self.OnSetDatabase(event)
  875. dlg.Destroy()
  876. def OnCreateMapset(self, event):
  877. """Create new mapset"""
  878. dlg = TextEntryDialog(
  879. parent=self,
  880. message=_('Enter name for new mapset:'),
  881. caption=_('Create new mapset'),
  882. defaultValue=self._getDefaultMapsetName(),
  883. validator=GenericValidator(
  884. grass.legal_name,
  885. self._nameValidationFailed))
  886. if dlg.ShowModal() == wx.ID_OK:
  887. mapset = dlg.GetValue()
  888. return self.CreateNewMapset(mapset=mapset)
  889. else:
  890. return False
  891. def CreateNewMapset(self, mapset):
  892. if mapset in self.listOfMapsets:
  893. GMessage(parent=self,
  894. message=_("Mapset <%s> already exists.") % mapset)
  895. return False
  896. if mapset.lower() == 'ogr':
  897. dlg1 = wx.MessageDialog(
  898. parent=self,
  899. message=_(
  900. "Mapset <%s> is reserved for direct "
  901. "read access to OGR layers. Please consider to use "
  902. "another name for your mapset.\n\n"
  903. "Are you really sure that you want to create this mapset?") %
  904. mapset,
  905. caption=_("Reserved mapset name"),
  906. style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  907. ret = dlg1.ShowModal()
  908. dlg1.Destroy()
  909. if ret == wx.ID_NO:
  910. dlg1.Destroy()
  911. return False
  912. try:
  913. self.gisdbase = self.tgisdbase.GetValue()
  914. location = self.listOfLocations[self.lblocations.GetSelection()]
  915. os.mkdir(os.path.join(self.gisdbase, location, mapset))
  916. # copy WIND file and its permissions from PERMANENT and set
  917. # permissions to u+rw,go+r
  918. shutil.copy(
  919. os.path.join(
  920. self.gisdbase,
  921. location,
  922. 'PERMANENT',
  923. 'WIND'),
  924. os.path.join(
  925. self.gisdbase,
  926. location,
  927. mapset))
  928. # os.chmod(os.path.join(database,location,mapset,'WIND'), 0644)
  929. self.OnSelectLocation(None)
  930. self.lbmapsets.SetSelection(self.listOfMapsets.index(mapset))
  931. self.bstart.SetFocus()
  932. return True
  933. except Exception as e:
  934. GError(parent=self,
  935. message=_("Unable to create new mapset: %s") % e,
  936. showTraceback=False)
  937. return False
  938. def OnStart(self, event):
  939. """'Start GRASS' button clicked"""
  940. dbase = self.tgisdbase.GetValue()
  941. location = self.listOfLocations[self.lblocations.GetSelection()]
  942. mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
  943. lockfile = os.path.join(dbase, location, mapset, '.gislock')
  944. if os.path.isfile(lockfile):
  945. dlg = wx.MessageDialog(
  946. parent=self,
  947. message=_(
  948. "GRASS is already running in selected mapset <%(mapset)s>\n"
  949. "(file %(lock)s found).\n\n"
  950. "Concurrent use not allowed.\n\n"
  951. "Do you want to try to remove .gislock (note that you "
  952. "need permission for this operation) and continue?") %
  953. {'mapset': mapset, 'lock': lockfile},
  954. caption=_("Lock file found"),
  955. style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
  956. ret = dlg.ShowModal()
  957. dlg.Destroy()
  958. if ret == wx.ID_YES:
  959. dlg1 = wx.MessageDialog(
  960. parent=self,
  961. message=_(
  962. "ARE YOU REALLY SURE?\n\n"
  963. "If you really are running another GRASS session doing this "
  964. "could corrupt your data. Have another look in the processor "
  965. "manager just to be sure..."),
  966. caption=_("Lock file found"),
  967. style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
  968. ret = dlg1.ShowModal()
  969. dlg1.Destroy()
  970. if ret == wx.ID_YES:
  971. try:
  972. os.remove(lockfile)
  973. except IOError as e:
  974. GError(_("Unable to remove '%(lock)s'.\n\n"
  975. "Details: %(reason)s") % {'lock': lockfile, 'reason': e})
  976. else:
  977. return
  978. else:
  979. return
  980. self.SetLocation(dbase, location, mapset)
  981. self.ExitSuccessfully()
  982. def SetLocation(self, dbase, location, mapset):
  983. RunCommand("g.gisenv",
  984. set="GISDBASE=%s" % dbase)
  985. RunCommand("g.gisenv",
  986. set="LOCATION_NAME=%s" % location)
  987. RunCommand("g.gisenv",
  988. set="MAPSET=%s" % mapset)
  989. def _getDefaultMapsetName(self):
  990. """Returns default name for mapset."""
  991. try:
  992. defaultName = getpass.getuser()
  993. # raise error if not ascii (not valid mapset name)
  994. defaultName.encode('ascii')
  995. except: # whatever might go wrong
  996. defaultName = 'user'
  997. return defaultName
  998. def ExitSuccessfully(self):
  999. self.Destroy()
  1000. sys.exit(self.exit_success)
  1001. def OnExit(self, event):
  1002. """'Exit' button clicked"""
  1003. self.Destroy()
  1004. sys.exit(self.exit_user_requested)
  1005. def OnHelp(self, event):
  1006. """'Help' button clicked"""
  1007. # help text in lib/init/helptext.html
  1008. RunCommand('g.manual', entry='helptext')
  1009. def OnCloseWindow(self, event):
  1010. """Close window event"""
  1011. event.Skip()
  1012. sys.exit(self.exit_user_requested)
  1013. def _nameValidationFailed(self, ctrl):
  1014. message = _(
  1015. "Name <%(name)s> is not a valid name for location or mapset. "
  1016. "Please use only ASCII characters excluding %(chars)s "
  1017. "and space.") % {
  1018. 'name': ctrl.GetValue(),
  1019. 'chars': '/"\'@,=*~'}
  1020. GError(parent=self, message=message, caption=_("Invalid name"))
  1021. class GListBox(ListCtrl, listmix.ListCtrlAutoWidthMixin):
  1022. """Use wx.ListCtrl instead of wx.ListBox, different style for
  1023. non-selectable items (e.g. mapsets with denied permission)"""
  1024. def __init__(self, parent, id, size,
  1025. choices, disabled=[]):
  1026. ListCtrl.__init__(
  1027. self, parent, id, size=size, style=wx.LC_REPORT | wx.LC_NO_HEADER |
  1028. wx.LC_SINGLE_SEL | wx.BORDER_SUNKEN)
  1029. listmix.ListCtrlAutoWidthMixin.__init__(self)
  1030. self.InsertColumn(0, '')
  1031. self.selected = wx.NOT_FOUND
  1032. self._LoadData(choices, disabled)
  1033. def _LoadData(self, choices, disabled=[]):
  1034. """Load data into list
  1035. :param choices: list of item
  1036. :param disabled: list of indices of non-selectable items
  1037. """
  1038. idx = 0
  1039. count = self.GetItemCount()
  1040. for item in choices:
  1041. index = self.InsertStringItem(count + idx, item)
  1042. self.SetStringItem(index, 0, item)
  1043. if idx in disabled:
  1044. self.SetItemTextColour(idx, wx.Colour(150, 150, 150))
  1045. idx += 1
  1046. def Clear(self):
  1047. self.DeleteAllItems()
  1048. def InsertItems(self, choices, pos, disabled=[]):
  1049. self._LoadData(choices, disabled)
  1050. def SetSelection(self, item, force=False):
  1051. if item != wx.NOT_FOUND and \
  1052. (platform.system() != 'Windows' or force):
  1053. # Windows -> FIXME
  1054. self.SetItemState(
  1055. item,
  1056. wx.LIST_STATE_SELECTED,
  1057. wx.LIST_STATE_SELECTED)
  1058. self.selected = item
  1059. def GetSelection(self):
  1060. return self.selected
  1061. class StartUp(wx.App):
  1062. """Start-up application"""
  1063. def OnInit(self):
  1064. if not globalvar.CheckWxVersion([2, 9]):
  1065. wx.InitAllImageHandlers()
  1066. StartUp = GRASSStartup()
  1067. StartUp.CenterOnScreen()
  1068. self.SetTopWindow(StartUp)
  1069. StartUp.Show()
  1070. StartUp.SuggestDatabase()
  1071. return 1
  1072. if __name__ == "__main__":
  1073. if os.getenv("GISBASE") is None:
  1074. sys.exit("Failed to start GUI, GRASS GIS is not running.")
  1075. GRASSStartUp = StartUp(0)
  1076. GRASSStartUp.MainLoop()