wxgui.py 60 KB

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