wxgui.py 60 KB

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