wxgui.py 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731
  1. """!
  2. @package wxgui.py
  3. @brief Main Python app for GRASS wxPython GUI. Main menu, layer management
  4. toolbar, notebook control for display management and access to
  5. command console.
  6. Classes:
  7. - GMFrame
  8. - GMApp
  9. (C) 2006-2011 by the GRASS Development Team
  10. This program is free software under the GNU General Public
  11. License (>=v2). Read the file COPYING that comes with GRASS
  12. for details.
  13. @author Michael Barton (Arizona State University)
  14. @author Jachym Cepicky (Mendel University of Agriculture)
  15. @author Martin Landa <landa.martin gmail.com>
  16. @author Vaclav Petras <wenzeslaus gmail.com> (menu customization)
  17. """
  18. import sys
  19. import os
  20. import time
  21. import string
  22. import getopt
  23. import platform
  24. import signal
  25. import tempfile
  26. try:
  27. import xml.etree.ElementTree as etree
  28. except ImportError:
  29. import elementtree.ElementTree as etree # Python <= 2.4
  30. from gui_modules import globalvar
  31. import wx
  32. import wx.aui
  33. import wx.combo
  34. import wx.html
  35. import wx.stc
  36. try:
  37. import wx.lib.agw.customtreectrl as CT
  38. import wx.lib.agw.flatnotebook as FN
  39. except ImportError:
  40. import wx.lib.customtreectrl as CT
  41. import wx.lib.flatnotebook as FN
  42. try:
  43. import wx.lib.agw.advancedsplash as SC
  44. except ImportError:
  45. SC = None
  46. sys.path.append(os.path.join(globalvar.ETCDIR, "python"))
  47. from grass.script import core as grass
  48. from gui_modules import utils
  49. from gui_modules import preferences
  50. from gui_modules import layertree
  51. from gui_modules import mapdisp
  52. from gui_modules import menudata
  53. from gui_modules import menuform
  54. from gui_modules import histogram
  55. from gui_modules import profile
  56. from gui_modules import mcalc_builder as mapcalculator
  57. from gui_modules import gcmd
  58. from gui_modules import dbm
  59. from gui_modules import workspace
  60. from gui_modules import goutput
  61. from gui_modules import gdialogs
  62. from gui_modules import colorrules
  63. from gui_modules import ogc_services
  64. from gui_modules import prompt
  65. from gui_modules import menu
  66. from gui_modules import gmodeler
  67. from gui_modules import vclean
  68. from gui_modules import nviz_tools
  69. from gui_modules import psmap
  70. from gui_modules.debug import Debug
  71. from gui_modules.ghelp import MenuTreeWindow, AboutWindow, InstallExtensionWindow
  72. from gui_modules.toolbars import LMWorkspaceToolbar, LMDataToolbar, LMToolsToolbar, LMMiscToolbar, LMVectorToolbar
  73. from gui_modules.gpyshell import PyShellWindow
  74. from icons.icon import Icons
  75. UserSettings = preferences.globalSettings
  76. class GMFrame(wx.Frame):
  77. """!Layer Manager frame with notebook widget for controlling GRASS
  78. GIS. Includes command console page for typing GRASS (and other)
  79. commands, tree widget page for managing map layers.
  80. """
  81. def __init__(self, parent, id = wx.ID_ANY, title = _("GRASS GIS Layer Manager"),
  82. workspace = None,
  83. size = globalvar.GM_WINDOW_SIZE, style = wx.DEFAULT_FRAME_STYLE, **kwargs):
  84. self.parent = parent
  85. self.baseTitle = title
  86. self.iconsize = (16, 16)
  87. wx.Frame.__init__(self, parent = parent, id = id, size = size,
  88. style = style, **kwargs)
  89. self.SetTitle(self.baseTitle)
  90. self.SetName("LayerManager")
  91. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  92. self._auimgr = wx.aui.AuiManager(self)
  93. # initialize variables
  94. self.disp_idx = 0 # index value for map displays and layer trees
  95. self.curr_page = None # currently selected page for layer tree notebook
  96. self.curr_pagenum = None # currently selected page number for layer tree notebook
  97. self.workspaceFile = workspace # workspace file
  98. self.workspaceChanged = False # track changes in workspace
  99. self.georectifying = None # reference to GCP class or None
  100. self.gcpmanagement = None # reference to GCP class or None
  101. # list of open dialogs
  102. self.dialogs = dict()
  103. self.dialogs['preferences'] = None
  104. self.dialogs['atm'] = list()
  105. # creating widgets
  106. self._createMenuBar()
  107. self.statusbar = self.CreateStatusBar(number = 1)
  108. self.notebook = self._createNoteBook()
  109. self.toolbars = { 'workspace' : LMWorkspaceToolbar(parent = self),
  110. 'data' : LMDataToolbar(parent = self),
  111. 'tools' : LMToolsToolbar(parent = self),
  112. 'misc' : LMMiscToolbar(parent = self),
  113. 'vector' : LMVectorToolbar(parent = self) }
  114. self._toolbarsData = { 'workspace' : ("toolbarWorkspace", # name
  115. _("Workspace Toolbar"), # caption
  116. 1), # row
  117. 'data' : ("toolbarData",
  118. _("Data Toolbar"),
  119. 1),
  120. 'misc' : ("toolbarMisc",
  121. _("Misc Toolbar"),
  122. 2),
  123. 'tools' : ("toolbarTools",
  124. _("Tools Toolbar"),
  125. 2),
  126. 'vector' : ("toolbarVector",
  127. _("Vector Toolbar"),
  128. 2),
  129. }
  130. if sys.platform == 'win32':
  131. self._toolbarsList = ('workspace', 'data',
  132. 'vector', 'tools', 'misc')
  133. else:
  134. self._toolbarsList = ('data', 'workspace',
  135. 'misc', 'tools', 'vector')
  136. for toolbar in self._toolbarsList:
  137. name, caption, row = self._toolbarsData[toolbar]
  138. self._auimgr.AddPane(self.toolbars[toolbar],
  139. wx.aui.AuiPaneInfo().
  140. Name(name).Caption(caption).
  141. ToolbarPane().Top().Row(row).
  142. LeftDockable(False).RightDockable(False).
  143. BottomDockable(False).TopDockable(True).
  144. CloseButton(False).Layer(2).
  145. BestSize((self.toolbars[toolbar].GetBestSize())))
  146. # bindings
  147. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  148. self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
  149. # minimal frame size
  150. self.SetMinSize((500, 400))
  151. # AUI stuff
  152. self._auimgr.AddPane(self.notebook, wx.aui.AuiPaneInfo().
  153. Left().CentrePane().BestSize((-1,-1)).Dockable(False).
  154. CloseButton(False).DestroyOnClose(True).Row(1).Layer(0))
  155. self._auimgr.Update()
  156. wx.CallAfter(self.notebook.SetSelectionByName, 'layers')
  157. # use default window layout ?
  158. if UserSettings.Get(group = 'general', key = 'defWindowPos', subkey = 'enabled'):
  159. dim = UserSettings.Get(group = 'general', key = 'defWindowPos', subkey = 'dim')
  160. try:
  161. x, y = map(int, dim.split(',')[0:2])
  162. w, h = map(int, dim.split(',')[2:4])
  163. self.SetPosition((x, y))
  164. self.SetSize((w, h))
  165. except:
  166. pass
  167. else:
  168. self.Centre()
  169. self.Layout()
  170. self.Show()
  171. # load workspace file if requested
  172. if self.workspaceFile:
  173. # load given workspace file
  174. if self.LoadWorkspaceFile(self.workspaceFile):
  175. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.workspaceFile))
  176. else:
  177. self.workspaceFile = None
  178. else:
  179. # start default initial display
  180. self.NewDisplay(show = False)
  181. # show map display widnow
  182. # -> OnSize() -> UpdateMap()
  183. if self.curr_page and not self.curr_page.maptree.mapdisplay.IsShown():
  184. self.curr_page.maptree.mapdisplay.Show()
  185. # redirect stderr to log area
  186. self.goutput.Redirect()
  187. # fix goutput's pane size
  188. self.goutput.SetSashPosition(int(self.GetSize()[1] * .45))
  189. self.workspaceChanged = False
  190. # start with layer manager on top
  191. if self.curr_page:
  192. self.curr_page.maptree.mapdisplay.Raise()
  193. wx.CallAfter(self.Raise)
  194. def _createMenuBar(self):
  195. """!Creates menu bar"""
  196. self.menubar = menu.Menu(parent = self, data = menudata.ManagerData())
  197. self.SetMenuBar(self.menubar)
  198. self.menucmd = self.menubar.GetCmd()
  199. def _setCopyingOfSelectedText(self):
  200. copy = UserSettings.Get(group = 'manager', key = 'copySelectedTextToClipboard', subkey = 'enabled')
  201. self.goutput.SetCopyingOfSelectedText(copy)
  202. def _createNoteBook(self):
  203. """!Creates notebook widgets"""
  204. self.notebook = menuform.GNotebook(parent = self, style = globalvar.FNPageDStyle)
  205. # create displays notebook widget and add it to main notebook page
  206. cbStyle = globalvar.FNPageStyle
  207. if globalvar.hasAgw:
  208. self.gm_cb = FN.FlatNotebook(self, id = wx.ID_ANY, agwStyle = cbStyle)
  209. else:
  210. self.gm_cb = FN.FlatNotebook(self, id = wx.ID_ANY, style = cbStyle)
  211. self.gm_cb.SetTabAreaColour(globalvar.FNPageColor)
  212. self.notebook.AddPage(page = self.gm_cb, text = _("Map layers"), name = 'layers')
  213. # create 'command output' text area
  214. self.goutput = goutput.GMConsole(self)
  215. self.notebook.AddPage(page = self.goutput, text = _("Command console"), name = 'output')
  216. self._setCopyingOfSelectedText()
  217. # create 'search module' notebook page
  218. if not UserSettings.Get(group = 'manager', key = 'hideTabs', subkey = 'search'):
  219. self.search = MenuTreeWindow(parent = self)
  220. self.notebook.AddPage(page = self.search, text = _("Search module"), name = 'search')
  221. else:
  222. self.search = None
  223. # create 'python shell' notebook page
  224. if not UserSettings.Get(group = 'manager', key = 'hideTabs', subkey = 'pyshell'):
  225. self.pyshell = PyShellWindow(parent = self)
  226. self.notebook.AddPage(page = self.pyshell, text = _("Python shell"), name = 'pyshell')
  227. else:
  228. self.pyshell = None
  229. # bindings
  230. self.gm_cb.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnCBPageChanged)
  231. self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
  232. self.gm_cb.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CLOSING, self.OnCBPageClosed)
  233. return self.notebook
  234. def AddNviz(self):
  235. """!Add nviz notebook page"""
  236. Debug.msg(5, "GMFrame.AddNviz(): begin")
  237. self.nviz = nviz_tools.NvizToolWindow(parent = self,
  238. display = self.curr_page.maptree.GetMapDisplay())
  239. idx = self.notebook.GetPageIndexByName('layers')
  240. self.notebook.InsertPage(indx = idx + 1, page = self.nviz, text = _("3D view"), name = 'nviz')
  241. self.notebook.SetSelectionByName('nviz')
  242. def RemoveNviz(self):
  243. """!Remove nviz notebook page"""
  244. # print self.notebook.GetPage(1)
  245. self.notebook.RemovePage(self.notebook.GetPageIndexByName('nviz'))
  246. del self.nviz
  247. self.notebook.SetSelectionByName('layers')
  248. def WorkspaceChanged(self):
  249. """!Update window title"""
  250. if not self.workspaceChanged:
  251. self.workspaceChanged = True
  252. if self.workspaceFile:
  253. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.workspaceFile) + '*')
  254. def OnLocationWizard(self, event):
  255. """!Launch location wizard"""
  256. from gui_modules import location_wizard
  257. gisdbase = grass.gisenv()['GISDBASE']
  258. gWizard = location_wizard.LocationWizard(parent = self,
  259. grassdatabase = gisdbase)
  260. if gWizard.location != None:
  261. dlg = wx.MessageDialog(parent = self,
  262. message = _('Location <%s> created.\n\n'
  263. 'Do you want to switch to the '
  264. 'new location?') % gWizard.location,
  265. caption=_("Switch to new location?"),
  266. style = wx.YES_NO | wx.NO_DEFAULT |
  267. wx.ICON_QUESTION | wx.CENTRE)
  268. ret = dlg.ShowModal()
  269. if ret == wx.ID_YES:
  270. gcmd.RunCommand("g.gisenv",
  271. set = "LOCATION_NAME=%s" % gWizard.location)
  272. gcmd.RunCommand("g.gisenv",
  273. set = "MAPSET=PERMANENT")
  274. dlg.Destroy()
  275. def OnSettingsChanged(self, event):
  276. """!Here can be functions which have to be called after EVT_SETTINGS_CHANGED.
  277. Now only set copying of selected text to clipboard (in goutput).
  278. """
  279. ### self._createMenuBar() # bug when menu is re-created on the fly
  280. self._setCopyingOfSelectedText()
  281. def OnGCPManager(self, event):
  282. """!Launch georectifier module
  283. """
  284. from gui_modules import gcpmanager
  285. gcpmanager.GCPWizard(self)
  286. def OnGModeler(self, event):
  287. """!Launch Graphical Modeler"""
  288. win = gmodeler.ModelFrame(parent = self)
  289. win.CentreOnScreen()
  290. win.Show()
  291. def OnPsMap(self, event):
  292. """!Launch Hardcopy Map Output Utility
  293. """
  294. win = psmap.PsMapFrame(parent = self)
  295. win.CentreOnScreen()
  296. win.Show()
  297. def OnRStream(self, event):
  298. """!GSoC's r.stream.* interface for testing
  299. """
  300. try:
  301. from gui_modules import rstream
  302. except:
  303. gcmd.GError(parent = self.parent,
  304. message = _("RStream Utility is not available. You can install it by %s") % \
  305. 'g.extension -s extension=wx.stream')
  306. return
  307. win = rstream.RStreamFrame(parent = self)
  308. win.CentreOnScreen()
  309. win.Show()
  310. def OnDone(self, returncode):
  311. """Command execution finised"""
  312. if hasattr(self, "model"):
  313. self.model.DeleteIntermediateData(log = self.goutput)
  314. del self.model
  315. self.SetStatusText('')
  316. def OnRunModel(self, event):
  317. """!Run model"""
  318. filename = ''
  319. dlg = wx.FileDialog(parent = self, message=_("Choose model to run"),
  320. defaultDir = os.getcwd(),
  321. wildcard=_("GRASS Model File (*.gxm)|*.gxm"))
  322. if dlg.ShowModal() == wx.ID_OK:
  323. filename = dlg.GetPath()
  324. if not filename:
  325. return
  326. self.model = gmodeler.Model()
  327. self.model.LoadModel(filename)
  328. self.SetStatusText(_('Validating model...'), 0)
  329. result = self.model.Validate()
  330. if result:
  331. dlg = wx.MessageDialog(parent = self,
  332. message = _('Model is not valid. Do you want to '
  333. 'run the model anyway?\n\n%s') % '\n'.join(errList),
  334. caption=_("Run model?"),
  335. style = wx.YES_NO | wx.NO_DEFAULT |
  336. wx.ICON_QUESTION | wx.CENTRE)
  337. ret = dlg.ShowModal()
  338. if ret != wx.ID_YES:
  339. return
  340. self.SetStatusText(_('Running model...'), 0)
  341. self.model.Run(log = self.goutput,
  342. onDone = self.OnDone)
  343. def OnMapsets(self, event):
  344. """!Launch mapset access dialog
  345. """
  346. dlg = preferences.MapsetAccess(parent = self, id = wx.ID_ANY)
  347. dlg.CenterOnScreen()
  348. if dlg.ShowModal() == wx.ID_OK:
  349. ms = dlg.GetMapsets()
  350. gcmd.RunCommand('g.mapsets',
  351. parent = self,
  352. mapset = '%s' % ','.join(ms))
  353. def OnCBPageChanged(self, event):
  354. """!Page in notebook (display) changed"""
  355. old_pgnum = event.GetOldSelection()
  356. new_pgnum = event.GetSelection()
  357. self.curr_page = self.gm_cb.GetCurrentPage()
  358. self.curr_pagenum = self.gm_cb.GetSelection()
  359. try:
  360. self.curr_page.maptree.mapdisplay.SetFocus()
  361. self.curr_page.maptree.mapdisplay.Raise()
  362. except:
  363. pass
  364. event.Skip()
  365. def OnPageChanged(self, event):
  366. """!Page in notebook changed"""
  367. page = event.GetSelection()
  368. if page == self.notebook.GetPageIndexByName('output'):
  369. # remove '(...)'
  370. self.notebook.SetPageText(page, _("Command console"))
  371. wx.CallAfter(self.goutput.cmd_prompt.SetFocus)
  372. self.SetStatusText('', 0)
  373. event.Skip()
  374. def OnCBPageClosed(self, event):
  375. """!Page of notebook closed
  376. Also close associated map display
  377. """
  378. if UserSettings.Get(group = 'manager', key = 'askOnQuit', subkey = 'enabled'):
  379. maptree = self.curr_page.maptree
  380. if self.workspaceFile:
  381. message = _("Do you want to save changes in the workspace?")
  382. else:
  383. message = _("Do you want to store current settings "
  384. "to workspace file?")
  385. # ask user to save current settings
  386. if maptree.GetCount() > 0:
  387. dlg = wx.MessageDialog(self,
  388. message = message,
  389. caption = _("Close Map Display %d") % (self.curr_pagenum + 1),
  390. style = wx.YES_NO | wx.YES_DEFAULT |
  391. wx.CANCEL | wx.ICON_QUESTION | wx.CENTRE)
  392. ret = dlg.ShowModal()
  393. if ret == wx.ID_YES:
  394. if not self.workspaceFile:
  395. self.OnWorkspaceSaveAs()
  396. else:
  397. self.SaveToWorkspaceFile(self.workspaceFile)
  398. elif ret == wx.ID_CANCEL:
  399. event.Veto()
  400. dlg.Destroy()
  401. return
  402. dlg.Destroy()
  403. self.gm_cb.GetPage(event.GetSelection()).maptree.Map.Clean()
  404. self.gm_cb.GetPage(event.GetSelection()).maptree.Close(True)
  405. self.curr_page = None
  406. event.Skip()
  407. def GetLayerTree(self):
  408. """!Get current layer tree"""
  409. return self.curr_page.maptree
  410. def GetLogWindow(self):
  411. """!Get widget for command output"""
  412. return self.goutput
  413. def GetMenuCmd(self, event):
  414. """!Get GRASS command from menu item
  415. Return command as a list"""
  416. layer = None
  417. if event:
  418. cmd = self.menucmd[event.GetId()]
  419. try:
  420. cmdlist = cmd.split(' ')
  421. except: # already list?
  422. cmdlist = cmd
  423. # check list of dummy commands for GUI modules that do not have GRASS
  424. # bin modules or scripts.
  425. if cmd in ['vcolors', 'r.mapcalc', 'r3.mapcalc']:
  426. return cmdlist
  427. try:
  428. layer = self.curr_page.maptree.layer_selected
  429. name = self.curr_page.maptree.GetPyData(layer)[0]['maplayer'].name
  430. type = self.curr_page.maptree.GetPyData(layer)[0]['type']
  431. except:
  432. layer = None
  433. if layer and len(cmdlist) == 1: # only if no paramaters given
  434. if (type == 'raster' and cmdlist[0][0] == 'r' and cmdlist[0][1] != '3') or \
  435. (type == 'vector' and cmdlist[0][0] == 'v'):
  436. input = menuform.GUI().GetCommandInputMapParamKey(cmdlist[0])
  437. if input:
  438. cmdlist.append("%s=%s" % (input, name))
  439. return cmdlist
  440. def RunMenuCmd(self, event = None, cmd = []):
  441. """!Run command selected from menu"""
  442. if event:
  443. cmd = self.GetMenuCmd(event)
  444. self.goutput.RunCmd(cmd, switchPage = False)
  445. def OnMenuCmd(self, event = None, cmd = []):
  446. """!Parse command selected from menu"""
  447. if event:
  448. cmd = self.GetMenuCmd(event)
  449. menuform.GUI(parent = self).ParseCommand(cmd)
  450. def OnVDigit(self, event):
  451. """!Start vector digitizer
  452. """
  453. if not self.curr_page:
  454. self.MsgNoLayerSelected()
  455. return
  456. tree = self.GetLayerTree()
  457. layer = tree.layer_selected
  458. # no map layer selected
  459. if not layer:
  460. self.MsgNoLayerSelected()
  461. return
  462. # available only for vector map layers
  463. try:
  464. mapLayer = tree.GetPyData(layer)[0]['maplayer']
  465. except:
  466. mapLayer = None
  467. if not mapLayer or mapLayer.GetType() != 'vector':
  468. gcmd.GMessage(parent = self,
  469. message = _("Selected map layer is not vector."))
  470. return
  471. if mapLayer.GetMapset() != grass.gisenv()['MAPSET']:
  472. gcmd.GMessage(parent = self,
  473. message = _("Editing is allowed only for vector maps from the "
  474. "current mapset."))
  475. return
  476. if not tree.GetPyData(layer)[0]:
  477. return
  478. dcmd = tree.GetPyData(layer)[0]['cmd']
  479. if not dcmd:
  480. return
  481. tree.OnStartEditing(None)
  482. def OnRunScript(self, event):
  483. """!Run script"""
  484. # open dialog and choose script file
  485. dlg = wx.FileDialog(parent = self, message = _("Choose script file to run"),
  486. defaultDir = os.getcwd(),
  487. wildcard = _("Python script (*.py)|*.py|Bash script (*.sh)|*.sh"))
  488. filename = None
  489. if dlg.ShowModal() == wx.ID_OK:
  490. filename = dlg.GetPath()
  491. if not filename:
  492. return False
  493. if not os.path.exists(filename):
  494. gcmd.GError(parent = self,
  495. message = _("Script file '%s' doesn't exist. "
  496. "Operation cancelled.") % filename)
  497. return
  498. self.goutput.WriteCmdLog(_("Launching script '%s'...") % filename)
  499. self.goutput.RunCmd([filename], switchPage = True)
  500. def OnChangeLocation(self, event):
  501. """Change current location"""
  502. dlg = gdialogs.LocationDialog(parent = self)
  503. if dlg.ShowModal() == wx.ID_OK:
  504. location, mapset = dlg.GetValues()
  505. if location and mapset:
  506. ret = gcmd.RunCommand("g.gisenv",
  507. set = "LOCATION_NAME=%s" % location)
  508. ret += gcmd.RunCommand("g.gisenv",
  509. set = "MAPSET=%s" % mapset)
  510. if ret > 0:
  511. wx.MessageBox(parent = self,
  512. message = _("Unable to switch to location <%(loc)s> mapset <%(mapset)s>.") % \
  513. { 'loc' : location, 'mapset' : mapset },
  514. caption = _("Error"), style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  515. else:
  516. # close workspace
  517. self.OnWorkspaceClose()
  518. self.OnWorkspaceNew()
  519. wx.MessageBox(parent = self,
  520. message = _("Current location is <%(loc)s>.\n"
  521. "Current mapset is <%(mapset)s>.") % \
  522. { 'loc' : location, 'mapset' : mapset },
  523. caption = _("Info"), style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  524. def OnChangeMapset(self, event):
  525. """Change current mapset"""
  526. dlg = gdialogs.MapsetDialog(parent = self)
  527. if dlg.ShowModal() == wx.ID_OK:
  528. mapset = dlg.GetMapset()
  529. if mapset:
  530. if gcmd.RunCommand("g.gisenv",
  531. set = "MAPSET=%s" % mapset) != 0:
  532. wx.MessageBox(parent = self,
  533. message = _("Unable to switch to mapset <%s>.") % mapset,
  534. caption = _("Error"), style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  535. else:
  536. wx.MessageBox(parent = self,
  537. message = _("Current mapset is <%s>.") % mapset,
  538. caption = _("Info"), style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  539. def OnNewVector(self, event):
  540. """!Create new vector map layer"""
  541. dlg = gdialogs.CreateNewVector(self, log = self.goutput,
  542. cmd = (('v.edit',
  543. { 'tool' : 'create' },
  544. 'map')))
  545. if not dlg:
  546. return
  547. name = dlg.GetName(full = True)
  548. if name and dlg.IsChecked('add'):
  549. # add layer to map layer tree
  550. self.curr_page.maptree.AddLayer(ltype = 'vector',
  551. lname = name,
  552. lcmd = ['d.vect', 'map=%s' % name])
  553. dlg.Destroy()
  554. def OnAboutGRASS(self, event):
  555. """!Display 'About GRASS' dialog"""
  556. win = AboutWindow(self)
  557. win.CentreOnScreen()
  558. win.Show(True)
  559. def _popupMenu(self, data):
  560. """!Create popup menu
  561. """
  562. point = wx.GetMousePosition()
  563. menu = wx.Menu()
  564. for key, handler in data:
  565. if key is None:
  566. menu.AppendSeparator()
  567. continue
  568. item = wx.MenuItem(menu, wx.ID_ANY, Icons['layerManager'][key].GetLabel())
  569. item.SetBitmap(Icons['layerManager'][key].GetBitmap(self.iconsize))
  570. menu.AppendItem(item)
  571. self.Bind(wx.EVT_MENU, handler, item)
  572. # create menu
  573. self.PopupMenu(menu)
  574. menu.Destroy()
  575. def OnImportMenu(self, event):
  576. """!Import maps menu (import, link)
  577. """
  578. self._popupMenu((('rastImport', self.OnImportGdalLayers),
  579. ('rastLink', self.OnLinkGdalLayers),
  580. (None, None),
  581. ('vectImport', self.OnImportOgrLayers),
  582. ('vectLink', self.OnLinkOgrLayers)))
  583. def OnWorkspaceNew(self, event = None):
  584. """!Create new workspace file
  585. Erase current workspace settings first
  586. """
  587. Debug.msg(4, "GMFrame.OnWorkspaceNew():")
  588. # start new map display if no display is available
  589. if not self.curr_page:
  590. self.NewDisplay()
  591. maptree = self.curr_page.maptree
  592. # ask user to save current settings
  593. if self.workspaceFile and self.workspaceChanged:
  594. self.OnWorkspaceSave()
  595. elif self.workspaceFile is None and maptree.GetCount() > 0:
  596. dlg = wx.MessageDialog(self, message = _("Current workspace is not empty. "
  597. "Do you want to store current settings "
  598. "to workspace file?"),
  599. caption = _("Create new workspace?"),
  600. style = wx.YES_NO | wx.YES_DEFAULT | \
  601. wx.CANCEL | wx.ICON_QUESTION)
  602. ret = dlg.ShowModal()
  603. if ret == wx.ID_YES:
  604. self.OnWorkspaceSaveAs()
  605. elif ret == wx.ID_CANCEL:
  606. dlg.Destroy()
  607. return
  608. dlg.Destroy()
  609. # delete all items
  610. maptree.DeleteAllItems()
  611. # add new root element
  612. maptree.root = maptree.AddRoot("Map Layers")
  613. self.curr_page.maptree.SetPyData(maptree.root, (None,None))
  614. # no workspace file loaded
  615. self.workspaceFile = None
  616. self.workspaceChanged = False
  617. self.SetTitle(self.baseTitle)
  618. def OnWorkspaceOpen(self, event = None):
  619. """!Open file with workspace definition"""
  620. dlg = wx.FileDialog(parent = self, message = _("Choose workspace file"),
  621. defaultDir = os.getcwd(), wildcard = _("GRASS Workspace File (*.gxw)|*.gxw"))
  622. filename = ''
  623. if dlg.ShowModal() == wx.ID_OK:
  624. filename = dlg.GetPath()
  625. if filename == '':
  626. return
  627. Debug.msg(4, "GMFrame.OnWorkspaceOpen(): filename=%s" % filename)
  628. # delete current layer tree content
  629. self.OnWorkspaceClose()
  630. self.LoadWorkspaceFile(filename)
  631. self.workspaceFile = filename
  632. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.workspaceFile))
  633. def LoadWorkspaceFile(self, filename):
  634. """!Load layer tree definition stored in GRASS Workspace XML file (gxw)
  635. @todo Validate against DTD
  636. @return True on success
  637. @return False on error
  638. """
  639. # dtd
  640. dtdFilename = os.path.join(globalvar.ETCWXDIR, "xml", "grass-gxw.dtd")
  641. # parse workspace file
  642. try:
  643. gxwXml = workspace.ProcessWorkspaceFile(etree.parse(filename))
  644. except Exception, e:
  645. gcmd.GError(parent = self,
  646. message = _("Reading workspace file <%s> failed.\n"
  647. "Invalid file, unable to parse XML document.") % filename)
  648. return
  649. busy = wx.BusyInfo(message = _("Please wait, loading workspace..."),
  650. parent = self)
  651. wx.Yield()
  652. #
  653. # load layer manager window properties
  654. #
  655. if UserSettings.Get(group = 'workspace', key = 'posManager', subkey = 'enabled') is False:
  656. if gxwXml.layerManager['pos']:
  657. self.SetPosition(gxwXml.layerManager['pos'])
  658. if gxwXml.layerManager['size']:
  659. self.SetSize(gxwXml.layerManager['size'])
  660. #
  661. # start map displays first (list of layers can be empty)
  662. #
  663. displayId = 0
  664. mapdisplay = list()
  665. for display in gxwXml.displays:
  666. mapdisp = self.NewDisplay(show = False)
  667. mapdisplay.append(mapdisp)
  668. maptree = self.gm_cb.GetPage(displayId).maptree
  669. # set windows properties
  670. mapdisp.SetProperties(render = display['render'],
  671. mode = display['mode'],
  672. showCompExtent = display['showCompExtent'],
  673. constrainRes = display['constrainRes'],
  674. projection = display['projection']['enabled'])
  675. if display['projection']['enabled']:
  676. if display['projection']['epsg']:
  677. UserSettings.Set(group = 'display', key = 'projection', subkey = 'epsg',
  678. value = display['projection']['epsg'])
  679. if display['projection']['proj']:
  680. UserSettings.Set(group = 'display', key = 'projection', subkey = 'proj4',
  681. value = display['projection']['proj'])
  682. # set position and size of map display
  683. if UserSettings.Get(group = 'workspace', key = 'posDisplay', subkey = 'enabled') is False:
  684. if display['pos']:
  685. mapdisp.SetPosition(display['pos'])
  686. if display['size']:
  687. mapdisp.SetSize(display['size'])
  688. # set extent if defined
  689. if display['extent']:
  690. w, s, e, n = display['extent']
  691. region = maptree.Map.region = maptree.Map.GetRegion(w = w, s = s, e = e, n = n)
  692. mapdisp.GetWindow().ResetZoomHistory()
  693. mapdisp.GetWindow().ZoomHistory(region['n'],
  694. region['s'],
  695. region['e'],
  696. region['w'])
  697. mapdisp.Show()
  698. displayId += 1
  699. maptree = None
  700. selected = [] # list of selected layers
  701. #
  702. # load list of map layers
  703. #
  704. for layer in gxwXml.layers:
  705. display = layer['display']
  706. maptree = self.gm_cb.GetPage(display).maptree
  707. newItem = maptree.AddLayer(ltype = layer['type'],
  708. lname = layer['name'],
  709. lchecked = layer['checked'],
  710. lopacity = layer['opacity'],
  711. lcmd = layer['cmd'],
  712. lgroup = layer['group'],
  713. lnviz = layer['nviz'],
  714. lvdigit = layer['vdigit'])
  715. if layer.has_key('selected'):
  716. if layer['selected']:
  717. selected.append((maptree, newItem))
  718. else:
  719. maptree.SelectItem(newItem, select = False)
  720. for maptree, layer in selected:
  721. if not maptree.IsSelected(layer):
  722. maptree.SelectItem(layer, select = True)
  723. maptree.layer_selected = layer
  724. busy.Destroy()
  725. if maptree:
  726. # reverse list of map layers
  727. maptree.Map.ReverseListOfLayers()
  728. for idx, mdisp in enumerate(mapdisplay):
  729. mdisp.MapWindow2D.UpdateMap()
  730. #nviz
  731. if gxwXml.displays[idx]['viewMode'] == '3d':
  732. mdisp.AddToolbar(name = 'nviz')
  733. self.nviz.UpdateState(view = gxwXml.nviz_state['view'],
  734. iview = gxwXml.nviz_state['iview'],
  735. light = gxwXml.nviz_state['light'])
  736. mdisp.MapWindow3D.constants = gxwXml.nviz_state['constants']
  737. for idx, constant in enumerate(mdisp.MapWindow3D.constants):
  738. mdisp.MapWindow3D.AddConstant(constant, idx + 1)
  739. for page in ('view', 'light', 'fringe', 'constant', 'cplane'):
  740. self.nviz.UpdatePage(page)
  741. self.nviz.UpdateSettings()
  742. mapdisp.toolbars['map'].combo.SetSelection(1)
  743. return True
  744. def OnWorkspaceLoadGrcFile(self, event):
  745. """!Load map layers from GRC file (Tcl/Tk GUI) into map layer tree"""
  746. dlg = wx.FileDialog(parent = self, message = _("Choose GRC file to load"),
  747. defaultDir = os.getcwd(), wildcard = _("Old GRASS Workspace File (*.grc)|*.grc"))
  748. filename = ''
  749. if dlg.ShowModal() == wx.ID_OK:
  750. filename = dlg.GetPath()
  751. if filename == '':
  752. return
  753. Debug.msg(4, "GMFrame.OnWorkspaceLoadGrcFile(): filename=%s" % filename)
  754. # start new map display if no display is available
  755. if not self.curr_page:
  756. self.NewDisplay()
  757. busy = wx.BusyInfo(message = _("Please wait, loading workspace..."),
  758. parent = self)
  759. wx.Yield()
  760. maptree = None
  761. for layer in workspace.ProcessGrcFile(filename).read(self):
  762. maptree = self.gm_cb.GetPage(layer['display']).maptree
  763. newItem = maptree.AddLayer(ltype = layer['type'],
  764. lname = layer['name'],
  765. lchecked = layer['checked'],
  766. lopacity = layer['opacity'],
  767. lcmd = layer['cmd'],
  768. lgroup = layer['group'])
  769. busy.Destroy()
  770. if maptree:
  771. # reverse list of map layers
  772. maptree.Map.ReverseListOfLayers()
  773. def OnWorkspaceSaveAs(self, event = None):
  774. """!Save workspace definition to selected file"""
  775. dlg = wx.FileDialog(parent = self, message = _("Choose file to save current workspace"),
  776. defaultDir = os.getcwd(), wildcard = _("GRASS Workspace File (*.gxw)|*.gxw"), style = wx.FD_SAVE)
  777. filename = ''
  778. if dlg.ShowModal() == wx.ID_OK:
  779. filename = dlg.GetPath()
  780. if filename == '':
  781. return False
  782. # check for extension
  783. if filename[-4:] != ".gxw":
  784. filename += ".gxw"
  785. if os.path.exists(filename):
  786. dlg = wx.MessageDialog(self, message = _("Workspace file <%s> already exists. "
  787. "Do you want to overwrite this file?") % filename,
  788. caption = _("Save workspace"), style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  789. if dlg.ShowModal() != wx.ID_YES:
  790. dlg.Destroy()
  791. return False
  792. Debug.msg(4, "GMFrame.OnWorkspaceSaveAs(): filename=%s" % filename)
  793. self.SaveToWorkspaceFile(filename)
  794. self.workspaceFile = filename
  795. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.workspaceFile))
  796. def OnWorkspaceSave(self, event = None):
  797. """!Save file with workspace definition"""
  798. if self.workspaceFile:
  799. dlg = wx.MessageDialog(self, message = _("Workspace file <%s> already exists. "
  800. "Do you want to overwrite this file?") % \
  801. self.workspaceFile,
  802. caption = _("Save workspace"), style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  803. if dlg.ShowModal() == wx.ID_NO:
  804. dlg.Destroy()
  805. else:
  806. Debug.msg(4, "GMFrame.OnWorkspaceSave(): filename=%s" % self.workspaceFile)
  807. self.SaveToWorkspaceFile(self.workspaceFile)
  808. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.workspaceFile))
  809. self.workspaceChanged = False
  810. else:
  811. self.OnWorkspaceSaveAs()
  812. def SaveToWorkspaceFile(self, filename):
  813. """!Save layer tree layout to workspace file
  814. Return True on success, False on error
  815. """
  816. tmpfile = tempfile.TemporaryFile(mode = 'w+b')
  817. try:
  818. workspace.WriteWorkspaceFile(lmgr = self, file = tmpfile)
  819. except StandardError, e:
  820. gcmd.GError(parent = self,
  821. message = _("Writing current settings to workspace file "
  822. "failed."))
  823. return False
  824. try:
  825. mfile = open(filename, "w")
  826. tmpfile.seek(0)
  827. for line in tmpfile.readlines():
  828. mfile.write(line)
  829. except IOError:
  830. gcmd.GError(parent = self,
  831. message = _("Unable to open file <%s> for writing.") % filename)
  832. return False
  833. mfile.close()
  834. return True
  835. def OnWorkspaceClose(self, event = None):
  836. """!Close file with workspace definition
  837. If workspace has been modified ask user to save the changes.
  838. """
  839. Debug.msg(4, "GMFrame.OnWorkspaceClose(): file=%s" % self.workspaceFile)
  840. self.OnDisplayCloseAll()
  841. self.workspaceFile = None
  842. self.workspaceChanged = False
  843. self.SetTitle(self.baseTitle)
  844. self.disp_idx = 0
  845. self.curr_page = None
  846. def OnDisplayClose(self, event = None):
  847. """!Close current map display window
  848. """
  849. if self.curr_page and self.curr_page.maptree.mapdisplay:
  850. self.curr_page.maptree.mapdisplay.OnCloseWindow(event)
  851. def OnDisplayCloseAll(self, event = None):
  852. """!Close all open map display windows
  853. """
  854. displays = list()
  855. for page in range(0, self.gm_cb.GetPageCount()):
  856. displays.append(self.gm_cb.GetPage(page).maptree.mapdisplay)
  857. for display in displays:
  858. display.OnCloseWindow(event)
  859. def RulesCmd(self, event):
  860. """!Launches dialog for commands that need rules input and
  861. processes rules
  862. """
  863. cmd = self.GetMenuCmd(event)
  864. if cmd[0] == 'r.colors':
  865. ctable = colorrules.ColorTable(self, raster = True)
  866. else:
  867. ctable = colorrules.ColorTable(self, raster = False)
  868. ctable.CentreOnScreen()
  869. ctable.Show()
  870. def OnInstallExtension(self, event):
  871. """!Install extension from GRASS Addons SVN repository"""
  872. win = InstallExtensionWindow(self, size = (650, 550))
  873. win.CentreOnScreen()
  874. win.Show()
  875. def OnPreferences(self, event):
  876. """!General GUI preferences/settings
  877. """
  878. if not self.dialogs['preferences']:
  879. dlg = preferences.PreferencesDialog(parent = self)
  880. self.dialogs['preferences'] = dlg
  881. self.dialogs['preferences'].CenterOnScreen()
  882. dlg.Bind(preferences.EVT_SETTINGS_CHANGED, self.OnSettingsChanged)
  883. self.dialogs['preferences'].ShowModal()
  884. def OnHelp(self, event):
  885. """!Show help
  886. """
  887. self.goutput.RunCmd(['g.manual','-i'])
  888. def DispHistogram(self, event):
  889. """
  890. Init histogram display canvas and tools
  891. """
  892. self.histogram = histogram.HistFrame(self,
  893. id = wx.ID_ANY, pos = wx.DefaultPosition, size = (400,300),
  894. style = wx.DEFAULT_FRAME_STYLE)
  895. #show new display
  896. self.histogram.Show()
  897. self.histogram.Refresh()
  898. self.histogram.Update()
  899. def DispProfile(self, event):
  900. """
  901. Init profile canvas and tools
  902. """
  903. self.profile = profile.ProfileFrame(self,
  904. id = wx.ID_ANY, pos = wx.DefaultPosition, size = (400,300),
  905. style = wx.DEFAULT_FRAME_STYLE)
  906. self.profile.Show()
  907. self.profile.Refresh()
  908. self.profile.Update()
  909. def OnMapCalculator(self, event, cmd = ''):
  910. """!Init map calculator for interactive creation of mapcalc statements
  911. """
  912. if event:
  913. try:
  914. cmd = self.GetMenuCmd(event)
  915. except KeyError:
  916. cmd = ['r.mapcalc']
  917. win = mapcalculator.MapCalcFrame(parent = self,
  918. cmd = cmd[0])
  919. win.CentreOnScreen()
  920. win.Show()
  921. def OnVectorCleaning(self, event, cmd = ''):
  922. """!Init interactive vector cleaning
  923. """
  924. if event:
  925. cmd = self.GetMenuCmd(event)
  926. win = vclean.VectorCleaningFrame(parent = self, cmd = cmd[0])
  927. win.CentreOnScreen()
  928. win.Show()
  929. def OnImportDxfFile(self, event, cmd = None):
  930. """!Convert multiple DXF layers to GRASS vector map layers"""
  931. dlg = gdialogs.DxfImportDialog(parent = self)
  932. dlg.CentreOnScreen()
  933. dlg.Show()
  934. def OnImportGdalLayers(self, event, cmd = None):
  935. """!Convert multiple GDAL layers to GRASS raster map layers"""
  936. dlg = gdialogs.GdalImportDialog(parent = self)
  937. dlg.CentreOnScreen()
  938. dlg.Show()
  939. def OnLinkGdalLayers(self, event, cmd = None):
  940. """!Link multiple GDAL layers to GRASS raster map layers"""
  941. dlg = gdialogs.GdalImportDialog(parent = self, link = True)
  942. dlg.CentreOnScreen()
  943. dlg.Show()
  944. def OnImportOgrLayers(self, event, cmd = None):
  945. """!Convert multiple OGR layers to GRASS vector map layers"""
  946. dlg = gdialogs.GdalImportDialog(parent = self, ogr = True)
  947. dlg.CentreOnScreen()
  948. dlg.Show()
  949. def OnLinkOgrLayers(self, event, cmd = None):
  950. """!Links multiple OGR layers to GRASS vector map layers"""
  951. dlg = gdialogs.GdalImportDialog(parent = self, ogr = True, link = True)
  952. dlg.CentreOnScreen()
  953. dlg.Show()
  954. def OnImportWMS(self, event):
  955. """!Import data from OGC WMS server"""
  956. dlg = ogc_services.WMSDialog(parent = self, service = 'wms')
  957. dlg.CenterOnScreen()
  958. if dlg.ShowModal() == wx.ID_OK: # -> import layers
  959. layers = dlg.GetLayers()
  960. if len(layers.keys()) > 0:
  961. for layer in layers.keys():
  962. cmd = ['r.in.wms',
  963. 'mapserver=%s' % dlg.GetSettings()['server'],
  964. 'layers=%s' % layer,
  965. 'output=%s' % layer,
  966. 'format=png',
  967. '--overwrite']
  968. styles = ','.join(layers[layer])
  969. if styles:
  970. cmd.append('styles=%s' % styles)
  971. self.goutput.RunCmd(cmd, switchPage = True)
  972. self.curr_page.maptree.AddLayer(ltype = 'raster',
  973. lname = layer,
  974. lcmd = ['d.rast', 'map=%s' % layer],
  975. multiple = False)
  976. else:
  977. self.goutput.WriteWarning(_("Nothing to import. No WMS layer selected."))
  978. dlg.Destroy()
  979. def OnShowAttributeTable(self, event, selection = None):
  980. """!Show attribute table of the given vector map layer
  981. """
  982. if not self.curr_page:
  983. self.MsgNoLayerSelected()
  984. return
  985. tree = self.GetLayerTree()
  986. layer = tree.layer_selected
  987. # no map layer selected
  988. if not layer:
  989. self.MsgNoLayerSelected()
  990. return
  991. # available only for vector map layers
  992. try:
  993. maptype = tree.GetPyData(layer)[0]['maplayer'].type
  994. except:
  995. maptype = None
  996. if not maptype or maptype != 'vector':
  997. gcmd.GMessage(parent = self,
  998. message = _("Selected map layer is not vector."))
  999. return
  1000. if not tree.GetPyData(layer)[0]:
  1001. return
  1002. dcmd = tree.GetPyData(layer)[0]['cmd']
  1003. if not dcmd:
  1004. return
  1005. busy = wx.BusyInfo(message = _("Please wait, loading attribute data..."),
  1006. parent = self)
  1007. wx.Yield()
  1008. dbmanager = dbm.AttributeManager(parent = self, id = wx.ID_ANY,
  1009. size = wx.Size(500, 300),
  1010. item = layer, log = self.goutput,
  1011. selection = selection)
  1012. busy.Destroy()
  1013. # register ATM dialog
  1014. self.dialogs['atm'].append(dbmanager)
  1015. # show ATM window
  1016. dbmanager.Show()
  1017. def OnNewDisplayWMS(self, event = None):
  1018. """!Create new layer tree and map display instance"""
  1019. self.NewDisplayWMS()
  1020. def NewDisplayWMS(self, show = True):
  1021. Debug.msg(1, "GMFrame.NewDisplay(): idx=%d" % self.disp_idx)
  1022. try:
  1023. from gui_modules.wms.wmsmenu import DisplayWMSMenu
  1024. except:
  1025. gcmd.GError(parent = self.parent,
  1026. message = _("Experimental WMS support for wxGUI not available. "
  1027. "You can install it by '%s'") % \
  1028. "g.extension -s extension=wx.wms")
  1029. return
  1030. DisplayWMSMenu()
  1031. def OnNewDisplay(self, event = None):
  1032. """!Create new layer tree and map display instance"""
  1033. self.NewDisplay()
  1034. def NewDisplay(self, show = True):
  1035. """!Create new layer tree, which will
  1036. create an associated map display frame
  1037. @param show show map display window if True
  1038. @return reference to mapdisplay intance
  1039. """
  1040. Debug.msg(1, "GMFrame.NewDisplay(): idx=%d" % self.disp_idx)
  1041. # make a new page in the bookcontrol for the layer tree (on page 0 of the notebook)
  1042. self.pg_panel = wx.Panel(self.gm_cb, id = wx.ID_ANY, style = wx.EXPAND)
  1043. self.gm_cb.AddPage(self.pg_panel, text = "Display "+ str(self.disp_idx + 1), select = True)
  1044. self.curr_page = self.gm_cb.GetCurrentPage()
  1045. # create layer tree (tree control for managing GIS layers) and put on new notebook page
  1046. self.curr_page.maptree = layertree.LayerTree(self.curr_page, id = wx.ID_ANY, pos = wx.DefaultPosition,
  1047. size = wx.DefaultSize, style = wx.TR_HAS_BUTTONS |
  1048. wx.TR_LINES_AT_ROOT| wx.TR_HIDE_ROOT |
  1049. wx.TR_DEFAULT_STYLE| wx.NO_BORDER | wx.FULL_REPAINT_ON_RESIZE,
  1050. idx = self.disp_idx, lmgr = self, notebook = self.gm_cb,
  1051. auimgr = self._auimgr, showMapDisplay = show)
  1052. # layout for controls
  1053. cb_boxsizer = wx.BoxSizer(wx.VERTICAL)
  1054. cb_boxsizer.Add(self.curr_page.maptree, proportion = 1, flag = wx.EXPAND, border = 1)
  1055. self.curr_page.SetSizer(cb_boxsizer)
  1056. cb_boxsizer.Fit(self.curr_page.maptree)
  1057. self.curr_page.Layout()
  1058. self.curr_page.maptree.Layout()
  1059. # use default window layout
  1060. if UserSettings.Get(group = 'general', key = 'defWindowPos', subkey = 'enabled'):
  1061. dim = UserSettings.Get(group = 'general', key = 'defWindowPos', subkey = 'dim')
  1062. idx = 4 + self.disp_idx * 4
  1063. try:
  1064. x, y = map(int, dim.split(',')[idx:idx + 2])
  1065. w, h = map(int, dim.split(',')[idx + 2:idx + 4])
  1066. self.curr_page.maptree.mapdisplay.SetPosition((x, y))
  1067. self.curr_page.maptree.mapdisplay.SetSize((w, h))
  1068. except:
  1069. pass
  1070. self.disp_idx += 1
  1071. return self.curr_page.maptree.mapdisplay
  1072. def OnAddMaps(self, event = None):
  1073. """!Add selected map layers into layer tree"""
  1074. dialog = gdialogs.AddMapLayersDialog(parent = self, title = _("Add selected map layers into layer tree"))
  1075. if dialog.ShowModal() == wx.ID_OK:
  1076. # start new map display if no display is available
  1077. if not self.curr_page:
  1078. self.NewDisplay()
  1079. maptree = self.curr_page.maptree
  1080. busy = wx.BusyInfo(message = _("Please wait, loading workspace..."),
  1081. parent = self)
  1082. wx.Yield()
  1083. for layerName in dialog.GetMapLayers():
  1084. if dialog.GetLayerType() == 'raster':
  1085. cmd = ['d.rast', 'map=%s' % layerName]
  1086. elif dialog.GetLayerType() == 'vector':
  1087. cmd = ['d.vect', 'map=%s' % layerName]
  1088. newItem = maptree.AddLayer(ltype = dialog.GetLayerType(),
  1089. lname = layerName,
  1090. lchecked = False,
  1091. lopacity = 1.0,
  1092. lcmd = cmd,
  1093. lgroup = None)
  1094. busy.Destroy()
  1095. def OnAddRaster(self, event):
  1096. """!Add raster map layer"""
  1097. # start new map display if no display is available
  1098. if not self.curr_page:
  1099. self.NewDisplay(show = True)
  1100. self.notebook.SetSelectionByName('layers')
  1101. self.curr_page.maptree.AddLayer('raster')
  1102. def OnAddRaster3D(self, event):
  1103. """!Add 3D raster map layer"""
  1104. # start new map display if no display is available
  1105. if not self.curr_page:
  1106. self.NewDisplay(show = True)
  1107. self.AddRaster3D(event)
  1108. def OnAddRasterMisc(self, event):
  1109. """!Create misc raster popup-menu"""
  1110. # start new map display if no display is available
  1111. if not self.curr_page:
  1112. self.NewDisplay(show = True)
  1113. self._popupMenu((('addRast3d', self.OnAddRaster3D),
  1114. (None, None),
  1115. ('addRgb', self.OnAddRasterRGB),
  1116. ('addHis', self.OnAddRasterHIS),
  1117. (None, None),
  1118. ('addShaded', self.OnAddRasterShaded),
  1119. (None, None),
  1120. ('addRArrow', self.OnAddRasterArrow),
  1121. ('addRNum', self.OnAddRasterNum)))
  1122. # show map display
  1123. self.curr_page.maptree.mapdisplay.Show()
  1124. def OnAddVector(self, event):
  1125. """!Add vector map to the current layer tree"""
  1126. # start new map display if no display is available
  1127. if not self.curr_page:
  1128. self.NewDisplay(show = True)
  1129. self.notebook.SetSelectionByName('layers')
  1130. self.curr_page.maptree.AddLayer('vector')
  1131. def OnAddVectorMisc(self, event):
  1132. """!Create misc vector popup-menu"""
  1133. # start new map display if no display is available
  1134. if not self.curr_page:
  1135. self.NewDisplay(show = True)
  1136. self._popupMenu((('addThematic', self.OnAddVectorTheme),
  1137. ('addChart', self.OnAddVectorChart)))
  1138. # show map display
  1139. self.curr_page.maptree.mapdisplay.Show()
  1140. def OnAddVectorTheme(self, event):
  1141. """!Add thematic vector map to the current layer tree"""
  1142. self.notebook.SetSelectionByName('layers')
  1143. self.curr_page.maptree.AddLayer('thememap')
  1144. def OnAddVectorChart(self, event):
  1145. """!Add chart vector map to the current layer tree"""
  1146. self.notebook.SetSelectionByName('layers')
  1147. self.curr_page.maptree.AddLayer('themechart')
  1148. def OnAddOverlay(self, event):
  1149. """!Create decoration overlay menu"""
  1150. # start new map display if no display is available
  1151. if not self.curr_page:
  1152. self.NewDisplay(show = True)
  1153. self._popupMenu((('addGrid', self.OnAddGrid),
  1154. ('addLabels', self.OnAddLabels),
  1155. ('addGeodesic', self.OnAddGeodesic),
  1156. ('addRhumb', self.OnAddRhumb),
  1157. (None, None),
  1158. ('addCmd', self.OnAddCommand)))
  1159. # show map display
  1160. self.curr_page.maptree.mapdisplay.Show()
  1161. def OnAddRaster3D(self, event):
  1162. """!Add 3D raster map to the current layer tree"""
  1163. self.notebook.SetSelectionByName('layers')
  1164. self.curr_page.maptree.AddLayer('3d-raster')
  1165. def OnAddRasterRGB(self, event):
  1166. """!Add RGB raster map to the current layer tree"""
  1167. self.notebook.SetSelectionByName('layers')
  1168. self.curr_page.maptree.AddLayer('rgb')
  1169. def OnAddRasterHIS(self, event):
  1170. """!Add HIS raster map to the current layer tree"""
  1171. self.notebook.SetSelectionByName('layers')
  1172. self.curr_page.maptree.AddLayer('his')
  1173. def OnAddRasterShaded(self, event):
  1174. """!Add shaded relief raster map to the current layer tree"""
  1175. self.notebook.SetSelectionByName('layers')
  1176. self.curr_page.maptree.AddLayer('shaded')
  1177. def OnAddRasterArrow(self, event):
  1178. """!Add flow arrows raster map to the current layer tree"""
  1179. self.notebook.SetSelectionByName('layers')
  1180. self.curr_page.maptree.AddLayer('rastarrow')
  1181. def OnAddRasterNum(self, event):
  1182. """!Add cell number raster map to the current layer tree"""
  1183. self.notebook.SetSelectionByName('layers')
  1184. self.curr_page.maptree.AddLayer('rastnum')
  1185. def OnAddCommand(self, event):
  1186. """!Add command line map layer to the current layer tree"""
  1187. # start new map display if no display is available
  1188. if not self.curr_page:
  1189. self.NewDisplay(show = True)
  1190. self.notebook.SetSelectionByName('layers')
  1191. self.curr_page.maptree.AddLayer('command')
  1192. # show map display
  1193. self.curr_page.maptree.mapdisplay.Show()
  1194. def OnAddGroup(self, event):
  1195. """!Add layer group"""
  1196. # start new map display if no display is available
  1197. if not self.curr_page:
  1198. self.NewDisplay(show = True)
  1199. self.notebook.SetSelectionByName('layers')
  1200. self.curr_page.maptree.AddLayer('group')
  1201. # show map display
  1202. self.curr_page.maptree.mapdisplay.Show()
  1203. def OnAddGrid(self, event):
  1204. """!Add grid map layer to the current layer tree"""
  1205. self.notebook.SetSelectionByName('layers')
  1206. self.curr_page.maptree.AddLayer('grid')
  1207. def OnAddGeodesic(self, event):
  1208. """!Add geodesic line map layer to the current layer tree"""
  1209. self.notebook.SetSelectionByName('layers')
  1210. self.curr_page.maptree.AddLayer('geodesic')
  1211. def OnAddRhumb(self, event):
  1212. """!Add rhumb map layer to the current layer tree"""
  1213. self.notebook.SetSelectionByName('layers')
  1214. self.curr_page.maptree.AddLayer('rhumb')
  1215. def OnAddLabels(self, event):
  1216. """!Add vector labels map layer to the current layer tree"""
  1217. # start new map display if no display is available
  1218. if not self.curr_page:
  1219. self.NewDisplay(show = True)
  1220. self.notebook.SetSelectionByName('layers')
  1221. self.curr_page.maptree.AddLayer('labels')
  1222. # show map display
  1223. self.curr_page.maptree.mapdisplay.Show()
  1224. def OnDeleteLayer(self, event):
  1225. """!Remove selected map layer from the current layer Tree
  1226. """
  1227. if not self.curr_page or not self.curr_page.maptree.layer_selected:
  1228. self.MsgNoLayerSelected()
  1229. return
  1230. if UserSettings.Get(group = 'manager', key = 'askOnRemoveLayer', subkey = 'enabled'):
  1231. layerName = ''
  1232. for item in self.curr_page.maptree.GetSelections():
  1233. name = str(self.curr_page.maptree.GetItemText(item))
  1234. idx = name.find('(opacity')
  1235. if idx > -1:
  1236. layerName += '<' + name[:idx].strip(' ') + '>,\n'
  1237. else:
  1238. layerName += '<' + name + '>,\n'
  1239. layerName = layerName.rstrip(',\n')
  1240. if len(layerName) > 2: # <>
  1241. message = _("Do you want to remove map layer(s)\n%s\n"
  1242. "from layer tree?") % layerName
  1243. else:
  1244. message = _("Do you want to remove selected map layer(s) "
  1245. "from layer tree?")
  1246. dlg = wx.MessageDialog (parent = self, message = message,
  1247. caption = _("Remove map layer"),
  1248. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  1249. if dlg.ShowModal() != wx.ID_YES:
  1250. dlg.Destroy()
  1251. return
  1252. dlg.Destroy()
  1253. for layer in self.curr_page.maptree.GetSelections():
  1254. if self.curr_page.maptree.GetPyData(layer)[0]['type'] == 'group':
  1255. self.curr_page.maptree.DeleteChildren(layer)
  1256. self.curr_page.maptree.Delete(layer)
  1257. def OnKeyDown(self, event):
  1258. """!Key pressed"""
  1259. kc = event.GetKeyCode()
  1260. if event.ControlDown():
  1261. if kc == wx.WXK_TAB:
  1262. # switch layer list / command output
  1263. if self.notebook.GetSelection() == self.notebook.GetPageIndexByName('layers'):
  1264. self.notebook.SetSelectionByName('output')
  1265. else:
  1266. self.notebook.SetSelectionByName('layers')
  1267. try:
  1268. ckc = chr(kc)
  1269. except ValueError:
  1270. event.Skip()
  1271. return
  1272. if event.CtrlDown():
  1273. if kc == 'R':
  1274. self.OnAddRaster(None)
  1275. elif kc == 'V':
  1276. self.OnAddVector(None)
  1277. event.Skip()
  1278. def OnCloseWindow(self, event):
  1279. """!Cleanup when wxGUI is quitted"""
  1280. if not self.curr_page:
  1281. self._auimgr.UnInit()
  1282. self.Destroy()
  1283. return
  1284. maptree = self.curr_page.maptree
  1285. if self.workspaceChanged and \
  1286. UserSettings.Get(group = 'manager', key = 'askOnQuit', subkey = 'enabled'):
  1287. if self.workspaceFile:
  1288. message = _("Do you want to save changes in the workspace?")
  1289. else:
  1290. message = _("Do you want to store current settings "
  1291. "to workspace file?")
  1292. # ask user to save current settings
  1293. if maptree.GetCount() > 0:
  1294. dlg = wx.MessageDialog(self,
  1295. message = message,
  1296. caption = _("Quit GRASS GUI"),
  1297. style = wx.YES_NO | wx.YES_DEFAULT |
  1298. wx.CANCEL | wx.ICON_QUESTION | wx.CENTRE)
  1299. ret = dlg.ShowModal()
  1300. if ret == wx.ID_YES:
  1301. if not self.workspaceFile:
  1302. self.OnWorkspaceSaveAs()
  1303. else:
  1304. self.SaveToWorkspaceFile(self.workspaceFile)
  1305. elif ret == wx.ID_CANCEL:
  1306. event.Veto()
  1307. dlg.Destroy()
  1308. return
  1309. dlg.Destroy()
  1310. # don't ask any more...
  1311. UserSettings.Set(group = 'manager', key = 'askOnQuit', subkey = 'enabled',
  1312. value = False)
  1313. self.OnDisplayCloseAll()
  1314. self.gm_cb.DeleteAllPages()
  1315. self._auimgr.UnInit()
  1316. self.Destroy()
  1317. def MsgNoLayerSelected(self):
  1318. """!Show dialog message 'No layer selected'"""
  1319. wx.MessageBox(parent = self,
  1320. message = _("No map layer selected. Operation cancelled."),
  1321. caption = _("Message"),
  1322. style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  1323. class GMApp(wx.App):
  1324. def __init__(self, workspace = None):
  1325. """!Main GUI class.
  1326. @param workspace path to the workspace file
  1327. """
  1328. self.workspaceFile = workspace
  1329. # call parent class initializer
  1330. wx.App.__init__(self, False)
  1331. self.locale = wx.Locale(language = wx.LANGUAGE_DEFAULT)
  1332. def OnInit(self):
  1333. """!Initialize all available image handlers
  1334. @return True
  1335. """
  1336. wx.InitAllImageHandlers()
  1337. # create splash screen
  1338. introImagePath = os.path.join(globalvar.ETCIMGDIR, "silesia_splash.png")
  1339. introImage = wx.Image(introImagePath, wx.BITMAP_TYPE_PNG)
  1340. introBmp = introImage.ConvertToBitmap()
  1341. if SC:
  1342. splash = SC.AdvancedSplash(bitmap = introBmp,
  1343. timeout = 2000, parent = None, id = wx.ID_ANY)
  1344. splash.SetText(_('Starting GRASS GUI...'))
  1345. splash.SetTextColour(wx.Colour(45, 52, 27))
  1346. splash.SetTextFont(wx.Font(pointSize = 15, family = wx.DEFAULT, style = wx.NORMAL,
  1347. weight = wx.BOLD))
  1348. splash.SetTextPosition((150, 430))
  1349. else:
  1350. wx.SplashScreen (bitmap = introBmp, splashStyle = wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT,
  1351. milliseconds = 2000, parent = None, id = wx.ID_ANY)
  1352. wx.Yield()
  1353. ### TODO: adjust initial window layout if necessary
  1354. w, h = wx.GetDisplaySize()
  1355. # only neccessary if one of the windows is falling out of
  1356. # the current display size
  1357. # check if settings file exists
  1358. # if settings file exists, check if we should use the stored settings
  1359. # if we should use stored settings, use stored settings
  1360. # else use default settings
  1361. # else if settings file does not exist, use default settings
  1362. # check if any of the windows is falling out of the current display
  1363. # if yes, pull it in
  1364. # falling out to the right
  1365. # x pos = display width - window width
  1366. # falling out to the bottom
  1367. # y pos = 0
  1368. # update settings
  1369. # if settings file exists, update settings but keep settings for
  1370. # additional map display windows, or update them too
  1371. # do not erase settings for additional map display windows !
  1372. # create and show main frame
  1373. mainframe = GMFrame(parent = None, id = wx.ID_ANY,
  1374. workspace = self.workspaceFile)
  1375. mainframe.Show()
  1376. self.SetTopWindow(mainframe)
  1377. return True
  1378. class Usage(Exception):
  1379. def __init__(self, msg):
  1380. self.msg = msg
  1381. def printHelp():
  1382. """!Print program help"""
  1383. print >> sys.stderr, "Usage:"
  1384. print >> sys.stderr, " python wxgui.py [options]"
  1385. print >> sys.stderr, "%sOptions:" % os.linesep
  1386. print >> sys.stderr, " -w\t--workspace file\tWorkspace file to load"
  1387. sys.exit(0)
  1388. def process_opt(opts, args):
  1389. """!Process command-line arguments"""
  1390. workspaceFile = None
  1391. for o, a in opts:
  1392. if o in ("-h", "--help"):
  1393. printHelp()
  1394. if o in ("-w", "--workspace"):
  1395. if a != '':
  1396. workspaceFile = str(a)
  1397. else:
  1398. workspaceFile = args.pop(0)
  1399. return (workspaceFile,)
  1400. def main(argv = None):
  1401. import gettext
  1402. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  1403. if argv is None:
  1404. argv = sys.argv
  1405. try:
  1406. try:
  1407. opts, args = getopt.getopt(argv[1:], "hw:",
  1408. ["help", "workspace"])
  1409. except getopt.error, msg:
  1410. raise Usage(msg)
  1411. except Usage, err:
  1412. print >> sys.stderr, err.msg
  1413. print >> sys.stderr, "for help use --help"
  1414. printHelp()
  1415. workspaceFile = process_opt(opts, args)[0]
  1416. app = GMApp(workspaceFile)
  1417. # suppress wxPython logs
  1418. q = wx.LogNull()
  1419. app.MainLoop()
  1420. if __name__ == "__main__":
  1421. sys.exit(main())