mapdisp.py 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912
  1. """
  2. @package mapdisp.py
  3. @brief GIS map display canvas, with toolbar for various display
  4. management functions, and additional toolbars (vector digitizer, 3d
  5. view).
  6. Can be used either from Layer Manager or as p.mon backend.
  7. Classes:
  8. - MapFrame
  9. - MapApp
  10. Usage:
  11. python mapdisp.py monitor-identifier /path/to/command/file
  12. (C) 2006-2009 by the GRASS Development Team
  13. This program is free software under the GNU General Public
  14. License (>=v2). Read the file COPYING that comes with GRASS
  15. for details.
  16. @author Michael Barton
  17. @author Jachym Cepicky
  18. @author Martin Landa <landa.martin gmail.com>
  19. """
  20. import os
  21. import sys
  22. import glob
  23. import math
  24. import tempfile
  25. import copy
  26. import globalvar
  27. if not os.getenv("GRASS_WXBUNDLED"):
  28. globalvar.CheckForWx()
  29. import wx
  30. import wx.aui
  31. try:
  32. import subprocess
  33. except:
  34. CompatPath = os.path.join(globalvar.ETCWXDIR)
  35. sys.path.append(CompatPath)
  36. from compat import subprocess
  37. gmpath = os.path.join(globalvar.ETCWXDIR, "icons")
  38. sys.path.append(gmpath)
  39. grassPath = os.path.join(globalvar.ETCDIR, "python")
  40. sys.path.append(grassPath)
  41. import render
  42. import toolbars
  43. import menuform
  44. import gselect
  45. import disp_print
  46. import gcmd
  47. import dbm
  48. import dbm_dialogs
  49. import histogram
  50. import profile
  51. import globalvar
  52. import utils
  53. import gdialogs
  54. from grass.script import core as grass
  55. from debug import Debug
  56. from icon import Icons
  57. from preferences import globalSettings as UserSettings
  58. from mapdisp_command import Command
  59. from mapdisp_window import BufferedWindow
  60. import images
  61. imagepath = images.__path__[0]
  62. sys.path.append(imagepath)
  63. ###
  64. ### global variables
  65. ###
  66. # for standalone app
  67. cmdfilename = None
  68. class MapFrame(wx.Frame):
  69. """
  70. Main frame for map display window. Drawing takes place in child double buffered
  71. drawing window.
  72. """
  73. def __init__(self, parent=None, id=wx.ID_ANY, title=_("GRASS GIS - Map display"),
  74. pos=wx.DefaultPosition, size=wx.DefaultSize,
  75. style=wx.DEFAULT_FRAME_STYLE, toolbars=["map"],
  76. tree=None, notebook=None, lmgr=None, page=None,
  77. Map=None, auimgr=None):
  78. """
  79. Main map display window with toolbars, statusbar and
  80. DrawWindow
  81. @param toolbars array of activated toolbars, e.g. ['map', 'digit']
  82. @param tree reference to layer tree
  83. @param notebook control book ID in Layer Manager
  84. @param mgr Layer Manager
  85. @param page notebook page with layer tree
  86. @param Map instance of render.Map
  87. """
  88. self._layerManager = lmgr # Layer Manager object
  89. self.Map = Map # instance of render.Map
  90. self.tree = tree # Layer Manager layer tree object
  91. self.page = page # Notebook page holding the layer tree
  92. self.layerbook = notebook # Layer Manager layer tree notebook
  93. self.parent = parent
  94. #
  95. # available cursors
  96. #
  97. self.cursors = {
  98. # default: cross
  99. # "default" : wx.StockCursor(wx.CURSOR_DEFAULT),
  100. "default" : wx.StockCursor(wx.CURSOR_ARROW),
  101. "cross" : wx.StockCursor(wx.CURSOR_CROSS),
  102. "hand" : wx.StockCursor(wx.CURSOR_HAND),
  103. "pencil" : wx.StockCursor(wx.CURSOR_PENCIL),
  104. "sizenwse": wx.StockCursor(wx.CURSOR_SIZENWSE)
  105. }
  106. wx.Frame.__init__(self, parent, id, title, pos, size, style)
  107. self.SetName("MapWindow")
  108. #
  109. # set the size & system icon
  110. #
  111. self.SetClientSize(size)
  112. self.iconsize = (16, 16)
  113. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_map.ico'), wx.BITMAP_TYPE_ICO))
  114. #
  115. # Fancy gui
  116. #
  117. # self._mgr = auimgr
  118. self._mgr = wx.aui.AuiManager(self)
  119. #
  120. # Add toolbars
  121. #
  122. self.toolbars = { 'map' : None,
  123. 'vdigit' : None,
  124. 'georect' : None,
  125. 'nviz' : None }
  126. for toolb in toolbars:
  127. self.AddToolbar(toolb)
  128. #
  129. # Add statusbar
  130. #
  131. self.statusbar = self.CreateStatusBar(number=4, style=0)
  132. self.statusbar.SetStatusWidths([-5, -2, -1, -1])
  133. self.statusbarWin = dict()
  134. self.statusbarWin['toggle'] = wx.Choice(self.statusbar, wx.ID_ANY,
  135. choices = globalvar.MAP_DISPLAY_STATUSBAR_MODE)
  136. self.statusbarWin['toggle'].SetSelection(UserSettings.Get(group='display',
  137. key='statusbarMode',
  138. subkey='selection'))
  139. self.statusbar.Bind(wx.EVT_CHOICE, self.OnToggleStatus, self.statusbarWin['toggle'])
  140. # auto-rendering checkbox
  141. self.statusbarWin['render'] = wx.CheckBox(parent=self.statusbar, id=wx.ID_ANY,
  142. label=_("Render"))
  143. self.statusbar.Bind(wx.EVT_CHECKBOX, self.OnToggleRender, self.statusbarWin['render'])
  144. self.statusbarWin['render'].SetValue(UserSettings.Get(group='display',
  145. key='autoRendering',
  146. subkey='enabled'))
  147. self.statusbarWin['render'].SetToolTip(wx.ToolTip (_("Enable/disable auto-rendering")))
  148. # show region
  149. self.statusbarWin['region'] = wx.CheckBox(parent=self.statusbar, id=wx.ID_ANY,
  150. label=_("Show computational extent"))
  151. self.statusbar.Bind(wx.EVT_CHECKBOX, self.OnToggleShowRegion, self.statusbarWin['region'])
  152. self.statusbarWin['region'].SetValue(False)
  153. self.statusbarWin['region'].Hide()
  154. self.statusbarWin['region'].SetToolTip(wx.ToolTip (_("Show/hide computational "
  155. "region extent (set with g.region). "
  156. "Display region drawn as a blue box inside the "
  157. "computational region, "
  158. "computational region inside a display region "
  159. "as a red box).")))
  160. # set resolution
  161. self.statusbarWin['resolution'] = wx.CheckBox(parent=self.statusbar, id=wx.ID_ANY,
  162. label=_("Constrain display resolution to computational settings"))
  163. self.statusbar.Bind(wx.EVT_CHECKBOX, self.OnToggleResolution, self.statusbarWin['resolution'])
  164. self.statusbarWin['resolution'].SetValue(UserSettings.Get(group='display', key='compResolution', subkey='enabled'))
  165. self.statusbarWin['resolution'].Hide()
  166. self.statusbarWin['resolution'].SetToolTip(wx.ToolTip (_("Constrain display resolution "
  167. "to computational region settings. "
  168. "Default value for new map displays can "
  169. "be set up in 'User GUI settings' dialog.")))
  170. # map scale
  171. self.statusbarWin['mapscale'] = wx.TextCtrl(parent=self.statusbar, id=wx.ID_ANY,
  172. value="", style=wx.TE_PROCESS_ENTER,
  173. size=(150, -1))
  174. self.statusbarWin['mapscale'].Hide()
  175. self.statusbar.Bind(wx.EVT_TEXT_ENTER, self.OnChangeMapScale, self.statusbarWin['mapscale'])
  176. # go to
  177. self.statusbarWin['goto'] = wx.TextCtrl(parent=self.statusbar, id=wx.ID_ANY,
  178. value="", style=wx.TE_PROCESS_ENTER,
  179. size=(300, -1))
  180. self.statusbarWin['goto'].Hide()
  181. self.statusbar.Bind(wx.EVT_TEXT_ENTER, self.OnGoTo, self.statusbarWin['goto'])
  182. # mask
  183. self.statusbarWin['mask'] = wx.StaticText(parent = self.statusbar, id = wx.ID_ANY,
  184. label = '')
  185. self.statusbarWin['mask'].SetForegroundColour(wx.Colour(255, 0, 0))
  186. # on-render gauge
  187. self.statusbarWin['progress'] = wx.Gauge(parent=self.statusbar, id=wx.ID_ANY,
  188. range=0, style=wx.GA_HORIZONTAL)
  189. self.statusbarWin['progress'].Hide()
  190. self.StatusbarReposition() # reposition statusbar
  191. #
  192. # Init map display (buffered DC & set default cursor)
  193. #
  194. self.MapWindow2D = BufferedWindow(self, id=wx.ID_ANY,
  195. Map=self.Map, tree=self.tree, lmgr=self._layerManager)
  196. # default is 2D display mode
  197. self.MapWindow = self.MapWindow2D
  198. self.MapWindow.Bind(wx.EVT_MOTION, self.OnMotion)
  199. self.MapWindow.SetCursor(self.cursors["default"])
  200. # used by Nviz (3D display mode)
  201. self.MapWindow3D = None
  202. #
  203. # initialize region values
  204. #
  205. self.__InitDisplay()
  206. #
  207. # Bind various events
  208. #
  209. self.Bind(wx.EVT_ACTIVATE, self.OnFocus)
  210. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  211. self.Bind(render.EVT_UPDATE_PRGBAR, self.OnUpdateProgress)
  212. #
  213. # Update fancy gui style
  214. #
  215. self._mgr.AddPane(self.MapWindow, wx.aui.AuiPaneInfo().CentrePane().
  216. Dockable(False).BestSize((-1,-1)).
  217. CloseButton(False).DestroyOnClose(True).
  218. Layer(0))
  219. self._mgr.Update()
  220. #
  221. # Init print module and classes
  222. #
  223. self.printopt = disp_print.PrintOptions(self, self.MapWindow)
  224. #
  225. # Initialization of digitization tool
  226. #
  227. self.digit = None
  228. #
  229. # Init zoom history
  230. #
  231. self.MapWindow.ZoomHistory(self.Map.region['n'],
  232. self.Map.region['s'],
  233. self.Map.region['e'],
  234. self.Map.region['w'])
  235. #
  236. # Re-use dialogs
  237. #
  238. self.dialogs = {}
  239. self.dialogs['attributes'] = None
  240. self.dialogs['category'] = None
  241. self.dialogs['barscale'] = None
  242. self.dialogs['legend'] = None
  243. self.decorationDialog = None # decoration/overlays
  244. def AddToolbar(self, name):
  245. """
  246. Add defined toolbar to the window
  247. Currently known toolbars are:
  248. - map basic map toolbar
  249. - digit vector digitizer
  250. - georect georectifier
  251. """
  252. # default toolbar
  253. if name == "map":
  254. self.toolbars['map'] = toolbars.MapToolbar(self, self.Map)
  255. self._mgr.AddPane(self.toolbars['map'].toolbar,
  256. wx.aui.AuiPaneInfo().
  257. Name("maptoolbar").Caption(_("Map Toolbar")).
  258. ToolbarPane().Top().
  259. LeftDockable(False).RightDockable(False).
  260. BottomDockable(False).TopDockable(True).
  261. CloseButton(False).Layer(2).
  262. BestSize((self.toolbars['map'].GetToolbar().GetSize())))
  263. # vector digitizer
  264. elif name == "vdigit":
  265. from vdigit import haveVDigit
  266. if not haveVDigit:
  267. from vdigit import errorMsg
  268. msg = _("Unable to start vector digitizer.\nThe VDigit python extension "
  269. "was not found or loaded properly.\n"
  270. "Switching back to 2D display mode.\n\nDetails: %s" % errorMsg)
  271. self.toolbars['map'].combo.SetValue (_("2D view"))
  272. wx.MessageBox(parent=self,
  273. message=msg,
  274. caption=_("Error"),
  275. style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  276. return
  277. if self._layerManager:
  278. log = self._layerManager.goutput
  279. else:
  280. log = None
  281. self.toolbars['vdigit'] = toolbars.VDigitToolbar(parent=self, map=self.Map,
  282. layerTree=self.tree,
  283. log=log)
  284. for toolRow in range(0, self.toolbars['vdigit'].numOfRows):
  285. self._mgr.AddPane(self.toolbars['vdigit'].toolbar[toolRow],
  286. wx.aui.AuiPaneInfo().
  287. Name("vdigittoolbar" + str(toolRow)).Caption(_("Vector digitizer toolbar")).
  288. ToolbarPane().Top().Row(toolRow + 1).
  289. LeftDockable(False).RightDockable(False).
  290. BottomDockable(False).TopDockable(True).
  291. CloseButton(False).Layer(2).
  292. BestSize((self.toolbars['vdigit'].GetToolbar().GetSize())))
  293. # change mouse to draw digitized line
  294. self.MapWindow.mouse['box'] = "point"
  295. self.MapWindow.zoomtype = 0
  296. self.MapWindow.pen = wx.Pen(colour='red', width=2, style=wx.SOLID)
  297. self.MapWindow.polypen = wx.Pen(colour='green', width=2, style=wx.SOLID)
  298. # georectifier
  299. elif name == "georect":
  300. self.toolbars['georect'] = toolbars.GRToolbar(self, self.Map)
  301. self._mgr.AddPane(self.toolbars['georect'].toolbar,
  302. wx.aui.AuiPaneInfo().
  303. Name("georecttoolbar").Caption(_("Georectification toolbar")).
  304. ToolbarPane().Top().
  305. LeftDockable(False).RightDockable(False).
  306. BottomDockable(False).TopDockable(True).
  307. CloseButton(False).Layer(2))
  308. # nviz
  309. elif name == "nviz":
  310. import nviz
  311. # check for GLCanvas and OpenGL
  312. msg = None
  313. if not nviz.haveGLCanvas:
  314. msg = _("Unable to switch to 3D display mode.\nThe GLCanvas class has not been "
  315. "included with this build "
  316. "of wxPython!\nSwitching back to "
  317. "2D display mode.\n\nDetails: %s" % nviz.errorMsg)
  318. if not nviz.haveNviz:
  319. msg = _("Unable to switch to 3D display mode.\nThe Nviz python extension "
  320. "was not found or loaded properly.\n"
  321. "Switching back to 2D display mode.\n\nDetails: %s" % nviz.errorMsg)
  322. if msg:
  323. self.toolbars['map'].combo.SetValue (_("2D view"))
  324. wx.MessageBox(parent=self,
  325. message=msg,
  326. caption=_("Error"),
  327. style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  328. return
  329. #
  330. # add Nviz toolbar and disable 2D display mode tools
  331. #
  332. self.toolbars['nviz'] = toolbars.NvizToolbar(self, self.Map)
  333. self.toolbars['map'].Enable2D(False)
  334. #
  335. # update layer tree (-> enable 3d-rasters)
  336. #
  337. if self.tree:
  338. self.tree.EnableItemType(type='3d-raster', enable=True)
  339. #
  340. # update status bar
  341. #
  342. self.statusbarWin['toggle'].Enable(False)
  343. #
  344. # erase map window
  345. #
  346. self.MapWindow.EraseMap()
  347. self.statusbar.SetStatusText(_("Please wait, loading data..."), 0)
  348. #
  349. # create GL window & NVIZ toolbar
  350. #
  351. if not self.MapWindow3D:
  352. self.MapWindow3D = nviz.GLWindow(self, id=wx.ID_ANY,
  353. Map=self.Map, tree=self.tree, lmgr=self._layerManager)
  354. # -> show after paint
  355. self.nvizToolWin = nviz.NvizToolWindow(self, id=wx.ID_ANY,
  356. mapWindow=self.MapWindow3D)
  357. self.MapWindow3D.OnPaint(None) # -> LoadData
  358. self.MapWindow3D.Show()
  359. self.MapWindow3D.UpdateView(None)
  360. self.nvizToolWin.Show()
  361. #
  362. # switch from MapWindow to MapWindowGL
  363. # add nviz toolbar
  364. #
  365. self._mgr.DetachPane(self.MapWindow2D)
  366. self.MapWindow2D.Hide()
  367. self._mgr.AddPane(self.MapWindow3D, wx.aui.AuiPaneInfo().CentrePane().
  368. Dockable(False).BestSize((-1,-1)).
  369. CloseButton(False).DestroyOnClose(True).
  370. Layer(0))
  371. self._mgr.AddPane(self.toolbars['nviz'].toolbar,
  372. wx.aui.AuiPaneInfo().
  373. Name("nviztoolbar").Caption(_("Nviz toolbar")).
  374. ToolbarPane().Top().Row(1).
  375. LeftDockable(False).RightDockable(False).
  376. BottomDockable(False).TopDockable(True).
  377. CloseButton(False).Layer(2))
  378. self.MapWindow = self.MapWindow3D
  379. self.SetStatusText("", 0)
  380. self._mgr.Update()
  381. def RemoveToolbar (self, name):
  382. """
  383. Removes toolbar from the window
  384. TODO: Only hide, activate by calling AddToolbar()
  385. """
  386. # cannot hide main toolbar
  387. if name == "map":
  388. return
  389. elif name == "vdigit":
  390. # TODO: not destroy only hide
  391. for toolRow in range(0, self.toolbars['vdigit'].numOfRows):
  392. self._mgr.DetachPane (self.toolbars['vdigit'].toolbar[toolRow])
  393. self.toolbars['vdigit'].toolbar[toolRow].Destroy()
  394. else:
  395. self._mgr.DetachPane (self.toolbars[name].toolbar)
  396. self.toolbars[name].toolbar.Destroy()
  397. self.toolbars[name] = None
  398. if name == 'nviz':
  399. # hide nviz tools
  400. self.nvizToolWin.Hide()
  401. # unload data
  402. # self.MapWindow3D.Reset()
  403. # switch from MapWindowGL to MapWindow
  404. self._mgr.DetachPane(self.MapWindow3D)
  405. self.MapWindow3D.Hide()
  406. self.MapWindow2D.Show()
  407. self._mgr.AddPane(self.MapWindow2D, wx.aui.AuiPaneInfo().CentrePane().
  408. Dockable(False).BestSize((-1,-1)).
  409. CloseButton(False).DestroyOnClose(True).
  410. Layer(0))
  411. self.MapWindow = self.MapWindow2D
  412. #
  413. # update layer tree (-> disable 3d-rasters)
  414. #
  415. if self.tree:
  416. self.tree.EnableItemType(type='3d-raster', enable=False)
  417. self.MapWindow.UpdateMap()
  418. self.toolbars['map'].combo.SetValue (_("2D view"))
  419. self.toolbars['map'].Enable2D(True)
  420. self.statusbarWin['toggle'].Enable(True)
  421. self._mgr.Update()
  422. def __InitDisplay(self):
  423. """
  424. Initialize map display, set dimensions and map region
  425. """
  426. self.width, self.height = self.GetClientSize()
  427. Debug.msg(2, "MapFrame.__InitDisplay():")
  428. self.Map.ChangeMapSize(self.GetClientSize())
  429. self.Map.region = self.Map.GetRegion() # g.region -upgc
  430. # self.Map.SetRegion() # adjust region to match display window
  431. def OnUpdateProgress(self, event):
  432. """
  433. Update progress bar info
  434. """
  435. self.statusbarWin['progress'].SetValue(event.value)
  436. event.Skip()
  437. def OnFocus(self, event):
  438. """
  439. Change choicebook page to match display.
  440. Or set display for georectifying
  441. """
  442. if self._layerManager and \
  443. self._layerManager.georectifying:
  444. # in georectifying session; display used to get get geographic
  445. # coordinates for GCPs
  446. self.OnPointer(event)
  447. else:
  448. # change bookcontrol page to page associated with display
  449. if self.page:
  450. pgnum = self.layerbook.GetPageIndex(self.page)
  451. if pgnum > -1:
  452. self.layerbook.SetSelection(pgnum)
  453. event.Skip()
  454. def OnMotion(self, event):
  455. """
  456. Mouse moved
  457. Track mouse motion and update status bar
  458. """
  459. # update statusbar if required
  460. if self.statusbarWin['toggle'].GetSelection() == 0: # Coordinates
  461. e, n = self.MapWindow.Pixel2Cell(event.GetPositionTuple())
  462. if self.toolbars['vdigit'] and \
  463. self.toolbars['vdigit'].GetAction() == 'addLine' and \
  464. self.toolbars['vdigit'].GetAction('type') in ('line', 'boundary') and \
  465. len(self.MapWindow.polycoords) > 0:
  466. # for linear feature show segment and total length
  467. distance_seg = self.MapWindow.Distance(self.MapWindow.polycoords[-1],
  468. (e, n), screen=False)[0]
  469. distance_tot = distance_seg
  470. for idx in range(1, len(self.MapWindow.polycoords)):
  471. distance_tot += self.MapWindow.Distance(self.MapWindow.polycoords[idx-1],
  472. self.MapWindow.polycoords[idx],
  473. screen=False )[0]
  474. self.statusbar.SetStatusText("%.2f, %.2f (seg: %.2f; tot: %.2f)" % \
  475. (e, n, distance_seg, distance_tot), 0)
  476. else:
  477. if UserSettings.Get(group='display', key='projection', subkey='enabled') and \
  478. UserSettings.Get(group='display', key='projection', subkey='proj4'):
  479. proj, coord = utils.ReprojectCoordinates(coord = (e, n),
  480. projOut = UserSettings.Get(group='display',
  481. key='projection',
  482. subkey='proj4'))
  483. if coord:
  484. if proj in ('ll', 'latlong', 'longlat'):
  485. self.statusbar.SetStatusText("%s, %s" % (coord[0], coord[1]), 0)
  486. else:
  487. self.statusbar.SetStatusText("%.2f, %.2f" % (coord[0], coord[1]), 0)
  488. else:
  489. self.statusbar.SetStatusText(_("Error in projection"), 0)
  490. else:
  491. if self.Map.projinfo['proj'] == 'll':
  492. self.statusbar.SetStatusText("%s" % utils.Deg2DMS(e, n), 0)
  493. else:
  494. self.statusbar.SetStatusText("%.2f, %.2f" % (e, n), 0)
  495. event.Skip()
  496. def OnDraw(self, event):
  497. """
  498. Re-display current map composition
  499. """
  500. self.MapWindow.UpdateMap(render=False)
  501. def OnRender(self, event):
  502. """
  503. Re-render map composition (each map layer)
  504. """
  505. # delete tmp map layers (queries)
  506. qlayer = self.Map.GetListOfLayers(l_name=globalvar.QUERYLAYER)
  507. for layer in qlayer:
  508. self.Map.DeleteLayer(layer)
  509. # delete tmp lines
  510. if self.MapWindow.mouse["use"] in ("measure",
  511. "profile"):
  512. self.MapWindow.polycoords = []
  513. self.MapWindow.ClearLines()
  514. # deselect features in vdigit
  515. if self.toolbars['vdigit'] and self.digit:
  516. self.digit.driver.SetSelected([])
  517. self.MapWindow.UpdateMap(render=True, renderVector=True)
  518. else:
  519. self.MapWindow.UpdateMap(render=True)
  520. # update statusbar
  521. self.StatusbarUpdate()
  522. def OnPointer(self, event):
  523. """
  524. Pointer button clicked
  525. """
  526. if self.toolbars['map']:
  527. if event:
  528. self.toolbars['map'].OnTool(event)
  529. self.toolbars['map'].action['desc'] = ''
  530. self.MapWindow.mouse['use'] = "pointer"
  531. self.MapWindow.mouse['box'] = "point"
  532. # change the cursor
  533. if self.toolbars['vdigit']:
  534. # digitization tool activated
  535. self.MapWindow.SetCursor(self.cursors["cross"])
  536. # reset mouse['box'] if needed
  537. if self.toolbars['vdigit'].GetAction() in ['addLine']:
  538. if self.toolbars['vdigit'].GetAction('type') in ['point', 'centroid']:
  539. self.MapWindow.mouse['box'] = 'point'
  540. else: # line, boundary
  541. self.MapWindow.mouse['box'] = 'line'
  542. elif self.toolbars['vdigit'].GetAction() in ['addVertex', 'removeVertex', 'splitLine',
  543. 'editLine', 'displayCats', 'displayAttrs',
  544. 'copyCats']:
  545. self.MapWindow.mouse['box'] = 'point'
  546. else: # moveLine, deleteLine
  547. self.MapWindow.mouse['box'] = 'box'
  548. elif self._layerManager and self._layerManager.georectifying:
  549. self.MapWindow.SetCursor(self.cursors["cross"])
  550. else:
  551. self.MapWindow.SetCursor(self.cursors["default"])
  552. def OnZoomIn(self, event):
  553. """
  554. Zoom in the map.
  555. Set mouse cursor, zoombox attributes, and zoom direction
  556. """
  557. if self.toolbars['map']:
  558. self.toolbars['map'].OnTool(event)
  559. self.toolbars['map'].action['desc'] = ''
  560. self.MapWindow.mouse['use'] = "zoom"
  561. self.MapWindow.mouse['box'] = "box"
  562. self.MapWindow.zoomtype = 1
  563. self.MapWindow.pen = wx.Pen(colour='Red', width=2, style=wx.SHORT_DASH)
  564. # change the cursor
  565. self.MapWindow.SetCursor(self.cursors["cross"])
  566. def OnZoomOut(self, event):
  567. """
  568. Zoom out the map.
  569. Set mouse cursor, zoombox attributes, and zoom direction
  570. """
  571. if self.toolbars['map']:
  572. self.toolbars['map'].OnTool(event)
  573. self.toolbars['map'].action['desc'] = ''
  574. self.MapWindow.mouse['use'] = "zoom"
  575. self.MapWindow.mouse['box'] = "box"
  576. self.MapWindow.zoomtype = -1
  577. self.MapWindow.pen = wx.Pen(colour='Red', width=2, style=wx.SHORT_DASH)
  578. # change the cursor
  579. self.MapWindow.SetCursor(self.cursors["cross"])
  580. def OnZoomBack(self, event):
  581. """
  582. Zoom last (previously stored position)
  583. """
  584. self.MapWindow.ZoomBack()
  585. def OnPan(self, event):
  586. """
  587. Panning, set mouse to drag
  588. """
  589. if self.toolbars['map']:
  590. self.toolbars['map'].OnTool(event)
  591. self.toolbars['map'].action['desc'] = ''
  592. self.MapWindow.mouse['use'] = "pan"
  593. self.MapWindow.mouse['box'] = "pan"
  594. self.MapWindow.zoomtype = 0
  595. # change the cursor
  596. self.MapWindow.SetCursor(self.cursors["hand"])
  597. def OnErase(self, event):
  598. """
  599. Erase the canvas
  600. """
  601. self.MapWindow.EraseMap()
  602. def OnZoomRegion(self, event):
  603. """
  604. Zoom to region
  605. """
  606. self.Map.getRegion()
  607. self.Map.getResolution()
  608. self.UpdateMap()
  609. # event.Skip()
  610. def OnAlignRegion(self, event):
  611. """
  612. Align region
  613. """
  614. if not self.Map.alignRegion:
  615. self.Map.alignRegion = True
  616. else:
  617. self.Map.alignRegion = False
  618. # event.Skip()
  619. def OnToggleRender(self, event):
  620. """
  621. Enable/disable auto-rendering
  622. """
  623. if self.statusbarWin['render'].GetValue():
  624. self.OnRender(None)
  625. def OnToggleShowRegion(self, event):
  626. """
  627. Show/Hide extent in map canvas
  628. """
  629. if self.statusbarWin['region'].GetValue():
  630. # show extent
  631. self.MapWindow.regionCoords = []
  632. else:
  633. del self.MapWindow.regionCoords
  634. # redraw map if auto-rendering is enabled
  635. if self.statusbarWin['render'].GetValue():
  636. self.OnRender(None)
  637. def OnToggleResolution(self, event):
  638. """
  639. Use resolution of computation region settings
  640. for redering image instead of display resolution
  641. """
  642. # redraw map if auto-rendering is enabled
  643. if self.statusbarWin['render'].GetValue():
  644. self.OnRender(None)
  645. def OnToggleStatus(self, event):
  646. """
  647. Toggle status text
  648. """
  649. self.StatusbarUpdate()
  650. def OnChangeMapScale(self, event):
  651. """
  652. Map scale changed by user
  653. """
  654. scale = event.GetString()
  655. try:
  656. if scale[:2] != '1:':
  657. raise ValueError
  658. value = int(scale[2:])
  659. except ValueError:
  660. self.statusbarWin['mapscale'].SetValue('1:%ld' % int(self.mapScaleValue))
  661. return
  662. dEW = value * (self.Map.region['cols'] / self.ppm[0])
  663. dNS = value * (self.Map.region['rows'] / self.ppm[1])
  664. self.Map.region['n'] = self.Map.region['center_northing'] + dNS / 2.
  665. self.Map.region['s'] = self.Map.region['center_northing'] - dNS / 2.
  666. self.Map.region['w'] = self.Map.region['center_easting'] - dEW / 2.
  667. self.Map.region['e'] = self.Map.region['center_easting'] + dEW / 2.
  668. # add to zoom history
  669. self.MapWindow.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  670. self.Map.region['e'], self.Map.region['w'])
  671. # redraw a map
  672. self.MapWindow.UpdateMap()
  673. self.statusbarWin['mapscale'].SetFocus()
  674. def OnGoTo(self, event):
  675. """
  676. Go to position
  677. """
  678. try:
  679. e, n = map(float, self.statusbarWin['goto'].GetValue().split(','))
  680. except ValueError:
  681. region = self.Map.GetCurrentRegion()
  682. self.statusbarWin['goto'].SetValue("%.2f, %.2f" % (region['center_easting'],
  683. region['center_northing']))
  684. return
  685. region = self.Map.GetCurrentRegion()
  686. region['center_northing'] = n
  687. region['center_easting'] = e
  688. dn = (region['nsres'] * region['rows']) / 2.
  689. region['n'] = region['center_northing'] + dn
  690. region['s'] = region['center_northing'] - dn
  691. de = (region['ewres'] * region['cols']) / 2.
  692. region['e'] = region['center_easting'] + de
  693. region['w'] = region['center_easting'] - de
  694. self.Map.AdjustRegion()
  695. # add to zoom history
  696. self.MapWindow.ZoomHistory(region['n'], region['s'],
  697. region['e'], region['w'])
  698. # redraw a map
  699. self.MapWindow.UpdateMap()
  700. self.statusbarWin['goto'].SetFocus()
  701. def StatusbarUpdate(self):
  702. """!Update statusbar content"""
  703. self.statusbarWin['region'].Hide()
  704. self.statusbarWin['resolution'].Hide()
  705. self.statusbarWin['mapscale'].Hide()
  706. self.statusbarWin['goto'].Hide()
  707. self.mapScaleValue = self.ppm = None
  708. if self.statusbarWin['toggle'].GetSelection() == 0: # Coordinates
  709. self.statusbar.SetStatusText("", 0)
  710. # enable long help
  711. self.StatusbarEnableLongHelp()
  712. elif self.statusbarWin['toggle'].GetSelection() == 1: # Extent
  713. if UserSettings.Get(group='display', key='projection', subkey='enabled') and \
  714. UserSettings.Get(group='display', key='projection', subkey='proj4'):
  715. projOut = UserSettings.Get(group='display',
  716. key='projection',
  717. subkey='proj4')
  718. proj, coord1 = utils.ReprojectCoordinates(coord = (self.Map.region["w"], self.Map.region["s"]),
  719. projOut = projOut)
  720. proj, coord2 = utils.ReprojectCoordinates(coord = (self.Map.region["e"], self.Map.region["n"]),
  721. projOut = projOut)
  722. if coord1 and coord2:
  723. if proj in ('ll', 'latlong', 'longlat'):
  724. self.statusbar.SetStatusText("%s - %s, %s - %s" %
  725. (coord1[0], coord2[0],
  726. coord1[1], coord2[1]))
  727. else:
  728. self.statusbar.SetStatusText("%.2f - %.2f, %.2f - %.2f" %
  729. (float(coord1[0]), float(coord2[0]),
  730. float(coord1[1]), float(coord2[1])))
  731. else:
  732. self.statusbar.SetStatusText(_("Error in projection"), 0)
  733. else:
  734. self.statusbar.SetStatusText("%.2f - %.2f, %.2f - %.2f" %
  735. (self.Map.region["w"], self.Map.region["e"],
  736. self.Map.region["s"], self.Map.region["n"]), 0)
  737. # enable long help
  738. self.StatusbarEnableLongHelp()
  739. elif self.statusbarWin['toggle'].GetSelection() == 2: # Comp. region
  740. compregion = self.Map.GetRegion()
  741. if UserSettings.Get(group='display', key='projection', subkey='enabled') and \
  742. UserSettings.Get(group='display', key='projection', subkey='proj4'):
  743. projOut = UserSettings.Get(group='display',
  744. key='projection',
  745. subkey='proj4')
  746. proj, coord1 = utils.ReprojectCoordinates(coord = (compregion["w"], compregion["s"]),
  747. projOut = projOut)
  748. proj, coord2 = utils.ReprojectCoordinates(coord = (compregion["e"], compregion["n"]),
  749. projOut = projOut)
  750. proj, coord3 = utils.ReprojectCoordinates(coord = (compregion["ewres"], compregion["nsres"]),
  751. projOut = projOut)
  752. if coord1 and coord2 and coord3:
  753. if proj in ('ll', 'latlong', 'longlat'):
  754. self.statusbar.SetStatusText("%s - %s, %s - %s (%s, %s)" %
  755. (coord1[0], coord2[0],
  756. coord1[1], coord2[1],
  757. coord3[0], coord3[1]))
  758. else:
  759. self.statusbar.SetStatusText("%.2f - %.2f, %.2f - %.2f (%.2f, %.2f)" %
  760. (float(coord1[0]), float(coord2[0]),
  761. float(coord1[1]), float(coord2[1]),
  762. float(coord3[0]), float(coord3[1])))
  763. else:
  764. self.statusbar.SetStatusText(_("Error in projection"), 0)
  765. else:
  766. self.statusbar.SetStatusText("%.2f - %.2f, %.2f - %.2f (%.2f, %.2f)" %
  767. (compregion["w"], compregion["e"],
  768. compregion["s"], compregion["n"],
  769. compregion["ewres"], compregion["nsres"]), 0)
  770. # enable long help
  771. self.StatusbarEnableLongHelp()
  772. elif self.statusbarWin['toggle'].GetSelection() == 3: # Show comp. extent
  773. self.statusbar.SetStatusText("", 0)
  774. self.statusbarWin['region'].Show()
  775. # disable long help
  776. self.StatusbarEnableLongHelp(False)
  777. elif self.statusbarWin['toggle'].GetSelection() == 4: # Display mode
  778. self.statusbar.SetStatusText("", 0)
  779. self.statusbarWin['resolution'].Show()
  780. # disable long help
  781. self.StatusbarEnableLongHelp(False)
  782. elif self.statusbarWin['toggle'].GetSelection() == 5: # Display geometry
  783. self.statusbar.SetStatusText("rows=%d; cols=%d; nsres=%.2f; ewres=%.2f" %
  784. (self.Map.region["rows"], self.Map.region["cols"],
  785. self.Map.region["nsres"], self.Map.region["ewres"]), 0)
  786. # enable long help
  787. self.StatusbarEnableLongHelp()
  788. elif self.statusbarWin['toggle'].GetSelection() == 6: # Map scale
  789. # TODO: need to be fixed...
  790. ### screen X region problem
  791. ### user should specify ppm
  792. dc = wx.ScreenDC()
  793. dpSizePx = wx.DisplaySize() # display size in pixels
  794. dpSizeMM = wx.DisplaySizeMM() # display size in mm (system)
  795. dpSizeIn = (dpSizeMM[0] / 25.4, dpSizeMM[1] / 25.4) # inches
  796. sysPpi = dc.GetPPI()
  797. comPpi = (dpSizePx[0] / dpSizeIn[0],
  798. dpSizePx[1] / dpSizeIn[1])
  799. ppi = comPpi # pixel per inch
  800. self.ppm = ((ppi[0] / 2.54) * 100, # pixel per meter
  801. (ppi[1] / 2.54) * 100)
  802. Debug.msg(4, "MapFrame.StatusbarUpdate(mapscale): size: px=%d,%d mm=%f,%f "
  803. "in=%f,%f ppi: sys=%d,%d com=%d,%d; ppm=%f,%f" % \
  804. (dpSizePx[0], dpSizePx[1], dpSizeMM[0], dpSizeMM[1],
  805. dpSizeIn[0], dpSizeIn[1],
  806. sysPpi[0], sysPpi[1], comPpi[0], comPpi[1],
  807. self.ppm[0], self.ppm[1]))
  808. region = self.Map.region
  809. heightCm = region['rows'] / self.ppm[1] * 100
  810. widthCm = region['cols'] / self.ppm[0] * 100
  811. Debug.msg(4, "MapFrame.StatusbarUpdate(mapscale): width_cm=%f, height_cm=%f" %
  812. (widthCm, heightCm))
  813. xscale = (region['e'] - region['w']) / (region['cols'] / self.ppm[0])
  814. yscale = (region['n'] - region['s']) / (region['rows'] / self.ppm[1])
  815. scale = (xscale + yscale) / 2.
  816. Debug.msg(3, "MapFrame.StatusbarUpdate(mapscale): xscale=%f, yscale=%f -> scale=%f" % \
  817. (xscale, yscale, scale))
  818. self.statusbar.SetStatusText("")
  819. try:
  820. self.statusbarWin['mapscale'].SetValue("1:%ld" % (scale + 0.5))
  821. except TypeError:
  822. pass
  823. self.mapScaleValue = scale
  824. self.statusbarWin['mapscale'].Show()
  825. # disable long help
  826. self.StatusbarEnableLongHelp(False)
  827. elif self.statusbarWin['toggle'].GetSelection() == 7: # go to
  828. self.statusbar.SetStatusText("")
  829. region = self.Map.GetCurrentRegion()
  830. if UserSettings.Get(group='display', key='projection', subkey='enabled') and \
  831. UserSettings.Get(group='display', key='projection', subkey='proj4'):
  832. proj, coord = utils.ReprojectCoordinates(coord = (region['center_easting'],
  833. region['center_northing']),
  834. projOut = UserSettings.Get(group='display',
  835. key='projection',
  836. subkey='proj4'))
  837. if coord:
  838. if proj in ('ll', 'latlong', 'longlat'):
  839. self.statusbarWin['goto'].SetValue("%s, %s" % (coord[0],
  840. coord[1]))
  841. else:
  842. self.statusbarWin['goto'].SetValue("%.2f, %.2f" % (coord[0],
  843. coord[1]))
  844. else:
  845. self.statusbarWin['goto'].SetValue("%.2f, %.2f" % (region['center_easting'],
  846. region['center_northing']))
  847. self.statusbarWin['goto'].Show()
  848. # disable long help
  849. self.StatusbarEnableLongHelp(False)
  850. else:
  851. self.statusbar.SetStatusText("", 1)
  852. def StatusbarEnableLongHelp(self, enable=True):
  853. """!Enable/disable toolbars long help"""
  854. for toolbar in self.toolbars.itervalues():
  855. if toolbar:
  856. toolbar.EnableLongHelp(enable)
  857. def StatusbarReposition(self):
  858. """!Reposition checkbox in statusbar"""
  859. # reposition checkbox
  860. widgets = [(0, self.statusbarWin['region']),
  861. (0, self.statusbarWin['resolution']),
  862. (0, self.statusbarWin['mapscale']),
  863. (0, self.statusbarWin['progress']),
  864. (1, self.statusbarWin['toggle']),
  865. (2, self.statusbarWin['mask']),
  866. (3, self.statusbarWin['render'])]
  867. for idx, win in widgets:
  868. rect = self.statusbar.GetFieldRect(idx)
  869. if idx == 0: # show region / mapscale / process bar
  870. # -> size
  871. wWin, hWin = win.GetBestSize()
  872. if win == self.statusbarWin['progress']:
  873. wWin = rect.width - 6
  874. # -> position
  875. # if win == self.statusbarWin['region']:
  876. # x, y = rect.x + rect.width - wWin, rect.y - 1
  877. # align left
  878. # else:
  879. x, y = rect.x + 3, rect.y - 1
  880. w, h = wWin, rect.height + 2
  881. else: # choice || auto-rendering
  882. x, y = rect.x, rect.y - 1
  883. w, h = rect.width, rect.height + 2
  884. if idx == 2: # mask
  885. x += 5
  886. y += 4
  887. elif idx == 3: # render
  888. x += 5
  889. win.SetPosition((x, y))
  890. win.SetSize((w, h))
  891. def SaveToFile(self, event):
  892. """
  893. Save image to file
  894. """
  895. lext = []
  896. for h in self.MapWindow.img.GetHandlers():
  897. lext.append(h.GetExtension())
  898. filetype = "BMP file (*.bmp)|*.bmp|"
  899. if 'gif' in lext:
  900. filetype += "GIF file (*.gif)|*.gif|"
  901. if 'jpg' in lext:
  902. filetype += "JPG file (*.jpg)|*.jpg|"
  903. if 'pcx' in lext:
  904. filetype += "PCX file (*.pcx)|*.pcx|"
  905. if 'png' in lext:
  906. filetype += "PNG file (*.png)|*.png|"
  907. if 'pnm' in lext:
  908. filetype += "PNM file (*.pnm)|*.pnm|"
  909. if 'tif' in lext:
  910. filetype += "TIF file (*.tif)|*.tif|"
  911. if 'xpm' in lext:
  912. filetype += "XPM file (*.xpm)|*.xpm"
  913. dlg = wx.FileDialog(self, _("Choose a file name to save the image (no need to add extension)"),
  914. defaultDir = "",
  915. defaultFile = "",
  916. wildcard = filetype,
  917. style=wx.SAVE|wx.FD_OVERWRITE_PROMPT)
  918. if dlg.ShowModal() == wx.ID_OK:
  919. path = dlg.GetPath()
  920. if path == None: return
  921. base = os.path.splitext(dlg.GetPath())[0]
  922. ext = os.path.splitext(dlg.GetPath())[1]
  923. if dlg.GetFilterIndex() == 0:
  924. type = wx.BITMAP_TYPE_BMP
  925. if ext != '.bmp': path = base+'.bmp'
  926. if dlg.GetFilterIndex() == 1:
  927. type = wx.BITMAP_TYPE_GIF
  928. if ext != '.gif': path = base+'.gif'
  929. elif dlg.GetFilterIndex() == 2:
  930. type = wx.BITMAP_TYPE_JPEG
  931. if ext != '.jpg': path = base+'.jpg'
  932. elif dlg.GetFilterIndex() == 3:
  933. type = wx.BITMAP_TYPE_GIF
  934. if ext != '.pcx': path = base+'.pcx'
  935. elif dlg.GetFilterIndex() == 4:
  936. type = wx.BITMAP_TYPE_PNG
  937. if ext != '.png': path = base+'.png'
  938. elif dlg.GetFilterIndex() == 5:
  939. type = wx.BITMAP_TYPE_PNM
  940. if ext != '.pnm': path = base+'.pnm'
  941. elif dlg.GetFilterIndex() == 6:
  942. type = wx.BITMAP_TYPE_TIF
  943. if ext != '.tif': path = base+'.tif'
  944. elif dlg.GetFilterIndex() == 7:
  945. type = wx.BITMAP_TYPE_XPM
  946. if ext != '.xpm': path = base+'.xpm'
  947. self.MapWindow.SaveToFile(path, type)
  948. dlg.Destroy()
  949. def PrintMenu(self, event):
  950. """
  951. Print options and output menu for map display
  952. """
  953. point = wx.GetMousePosition()
  954. printmenu = wx.Menu()
  955. # Add items to the menu
  956. setup = wx.MenuItem(printmenu, wx.ID_ANY, _('Page setup'))
  957. printmenu.AppendItem(setup)
  958. self.Bind(wx.EVT_MENU, self.printopt.OnPageSetup, setup)
  959. preview = wx.MenuItem(printmenu, wx.ID_ANY, _('Print preview'))
  960. printmenu.AppendItem(preview)
  961. self.Bind(wx.EVT_MENU, self.printopt.OnPrintPreview, preview)
  962. doprint = wx.MenuItem(printmenu, wx.ID_ANY, _('Print display'))
  963. printmenu.AppendItem(doprint)
  964. self.Bind(wx.EVT_MENU, self.printopt.OnDoPrint, doprint)
  965. # Popup the menu. If an item is selected then its handler
  966. # will be called before PopupMenu returns.
  967. self.PopupMenu(printmenu)
  968. printmenu.Destroy()
  969. def OnCloseWindow(self, event):
  970. """
  971. Window closed.
  972. Also close associated layer tree page
  973. """
  974. pgnum = None
  975. self.Map.Clean()
  976. # close edited map and 3D tools properly
  977. if self.toolbars['vdigit']:
  978. maplayer = self.toolbars['vdigit'].GetLayer()
  979. if maplayer:
  980. self.toolbars['vdigit'].OnExit()
  981. self.imgVectorMap = None
  982. if self.toolbars['nviz']:
  983. self.toolbars['nviz'].OnExit()
  984. if not self._layerManager:
  985. self.Destroy()
  986. elif self.page:
  987. pgnum = self.layerbook.GetPageIndex(self.page)
  988. if pgnum > -1:
  989. self.layerbook.DeletePage(pgnum)
  990. def GetRender(self):
  991. """
  992. Returns the current instance of render.Map()
  993. """
  994. return self.Map
  995. def OnQueryDisplay(self, event):
  996. """
  997. Query currrent raster/vector map layers (display mode)
  998. """
  999. if self.toolbars['map'].GetAction() == 'displayAttrb': # select previous action
  1000. self.toolbars['map'].SelectDefault(event)
  1001. return
  1002. self.toolbars['map'].action['desc'] = 'displayAttrb'
  1003. # switch GIS Manager to output console to show query results
  1004. self._layerManager.notebook.SetSelection(1)
  1005. self.MapWindow.mouse['use'] = "query"
  1006. self.MapWindow.mouse['box'] = "point"
  1007. self.MapWindow.zoomtype = 0
  1008. # change the cursor
  1009. self.MapWindow.SetCursor(self.cursors["cross"])
  1010. def OnQueryModify(self, event):
  1011. """
  1012. Query vector map layer (edit mode)
  1013. """
  1014. if self.toolbars['map'].GetAction() == 'modifyAttrb': # select previous action
  1015. self.toolbars['map'].SelectDefault(event)
  1016. return
  1017. self.toolbars['map'].action['desc'] = 'modifyAttrb'
  1018. self.MapWindow.mouse['use'] = "queryVector"
  1019. self.MapWindow.mouse['box'] = "point"
  1020. self.MapWindow.pen = wx.Pen(colour='Red', width=2, style=wx.SHORT_DASH)
  1021. self.MapWindow.zoomtype = 0
  1022. # change the cursor
  1023. self.MapWindow.SetCursor(self.cursors["cross"])
  1024. def QueryMap(self, x, y):
  1025. """!Query map layer features
  1026. Currently only raster and vector map layers are supported.
  1027. @param x,y coordinates
  1028. """
  1029. #set query snap distance for v.what at mapunit equivalent of 10 pixels
  1030. qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) / self.Map.width)
  1031. east, north = self.MapWindow.Pixel2Cell((x, y))
  1032. num = 0
  1033. for layer in self.tree.GetSelections():
  1034. type = self.tree.GetPyData(layer)[0]['maplayer'].GetType()
  1035. if type in ('raster', 'rgb', 'his',
  1036. 'vector', 'thememap', 'themechart'):
  1037. num += 1
  1038. if num < 1:
  1039. dlg = wx.MessageDialog(parent=self,
  1040. message=_('No raster or vector map layer selected for querying.'),
  1041. caption=_('No map layer selected'),
  1042. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  1043. dlg.ShowModal()
  1044. dlg.Destroy()
  1045. return
  1046. mapname = None
  1047. raststr = ''
  1048. vectstr = ''
  1049. rcmd = ['r.what', '--q']
  1050. vcmd = ['v.what', '--q']
  1051. for layer in self.tree.GetSelections():
  1052. type = self.tree.GetPyData(layer)[0]['maplayer'].GetType()
  1053. dcmd = self.tree.GetPyData(layer)[0]['cmd']
  1054. name = utils.GetLayerNameFromCmd(dcmd)
  1055. if name == '':
  1056. continue
  1057. if type in ('raster', 'rgb', 'his'):
  1058. raststr += "%s," % name
  1059. elif type in ('vector', 'thememap', 'themechart'):
  1060. vectstr += "%s," % name
  1061. # use display region settings instead of computation region settings
  1062. tmpreg = os.getenv("GRASS_REGION")
  1063. os.environ["GRASS_REGION"] = self.Map.SetRegion(windres=False)
  1064. # build query commands for any selected rasters and vectors
  1065. if raststr != '':
  1066. rcmd.append('-f')
  1067. rcmd.append('input=%s' % raststr.rstrip(','))
  1068. rcmd.append('east_north=%f,%f' % (float(east), float(north)))
  1069. if vectstr != '':
  1070. # check for vector maps open to be edited
  1071. digitToolbar = self.toolbars['vdigit']
  1072. if digitToolbar:
  1073. map = digitToolbar.GetLayer().GetName()
  1074. vect = []
  1075. for vector in vectstr.split(','):
  1076. if map == vector:
  1077. self._layerManager.goutput.WriteWarning("Vector map <%s> "
  1078. "opened for editing - skipped." % map)
  1079. continue
  1080. vect.append(vector)
  1081. vectstr = ','.join(vect)
  1082. if len(vectstr) <= 1:
  1083. self._layerManager.goutput.WriteCmdLog("Nothing to query.")
  1084. return
  1085. vcmd.append('-a')
  1086. vcmd.append('map=%s' % vectstr.rstrip(','))
  1087. vcmd.append('east_north=%f,%f' % (float(east), float(north)))
  1088. vcmd.append('distance=%f' % float(qdist))
  1089. # parse query command(s)
  1090. if self._layerManager:
  1091. if raststr:
  1092. self._layerManager.goutput.RunCmd(rcmd,
  1093. compReg=False)
  1094. if vectstr:
  1095. self._layerManager.goutput.RunCmd(vcmd)
  1096. else:
  1097. if raststr:
  1098. gcmd.RunCommand(rcmd)
  1099. if vectstr:
  1100. gcmd.RunCommand(vcmd)
  1101. # restore GRASS_REGION
  1102. if tmpreg:
  1103. os.environ["GRASS_REGION"] = tmpreg
  1104. def QueryVector(self, x, y):
  1105. """
  1106. Query vector map layer features
  1107. Attribute data of selected vector object are displayed in GUI dialog.
  1108. Data can be modified (On Submit)
  1109. """
  1110. if not self.tree.layer_selected or \
  1111. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] != 'vector':
  1112. wx.MessageBox(parent=self,
  1113. message=_("No vector map selected for querying."),
  1114. caption=_("Vector querying"),
  1115. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  1116. return
  1117. if self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].GetMapset() != \
  1118. grass.gisenv()['MAPSET']:
  1119. wx.MessageBox(parent=self,
  1120. message=_("Only vector map from the current mapset can be modified."),
  1121. caption=_("Vector querying"),
  1122. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  1123. return
  1124. posWindow = self.ClientToScreen((x + self.MapWindow.dialogOffset,
  1125. y + self.MapWindow.dialogOffset))
  1126. qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) /
  1127. self.Map.width)
  1128. east, north = self.MapWindow.Pixel2Cell((x, y))
  1129. mapName = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name
  1130. if self.dialogs['attributes'] is None:
  1131. self.dialogs['attributes'] = \
  1132. dbm_dialogs.DisplayAttributesDialog(parent=self.MapWindow,
  1133. map=mapName,
  1134. query=((east, north), qdist),
  1135. pos=posWindow,
  1136. action="update")
  1137. else:
  1138. # selection changed?
  1139. if not self.dialogs['attributes'].mapDBInfo or \
  1140. self.dialogs['attributes'].mapDBInfo.map != mapName:
  1141. self.dialogs['attributes'].UpdateDialog(map=mapName, query=((east, north), qdist))
  1142. else:
  1143. self.dialogs['attributes'].UpdateDialog(query=((east, north), qdist))
  1144. cats = self.dialogs['attributes'].GetCats()
  1145. try:
  1146. qlayer = self.Map.GetListOfLayers(l_name=globalvar.QUERYLAYER)[0]
  1147. except IndexError:
  1148. qlayer = None
  1149. if self.dialogs['attributes'].mapDBInfo and cats:
  1150. # highlight feature & re-draw map
  1151. if qlayer:
  1152. qlayer.SetCmd(self.AddTmpVectorMapLayer(mapName, cats,
  1153. useId=False,
  1154. addLayer=False))
  1155. else:
  1156. qlayer = self.AddTmpVectorMapLayer(mapName, cats, useId=False)
  1157. # set opacity based on queried layer
  1158. opacity = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].GetOpacity(float=True)
  1159. qlayer.SetOpacity(opacity)
  1160. self.MapWindow.UpdateMap(render=False, renderVector=False)
  1161. if not self.dialogs['attributes'].IsShown():
  1162. self.dialogs['attributes'].Show()
  1163. else:
  1164. if qlayer:
  1165. self.Map.DeleteLayer(qlayer)
  1166. self.MapWindow.UpdateMap(render=False, renderVector=False)
  1167. if self.dialogs['attributes'].IsShown():
  1168. self.dialogs['attributes'].Hide()
  1169. def OnQuery(self, event):
  1170. """!Query tools menu"""
  1171. if self.toolbars['map']:
  1172. self.toolbars['map'].OnTool(event)
  1173. action = self.toolbars['map'].GetAction()
  1174. point = wx.GetMousePosition()
  1175. toolsmenu = wx.Menu()
  1176. # Add items to the menu
  1177. display = wx.MenuItem(parentMenu=toolsmenu, id=wx.ID_ANY,
  1178. text=_("Query raster/vector map(s) (display mode)"),
  1179. kind=wx.ITEM_CHECK)
  1180. toolsmenu.AppendItem(display)
  1181. self.Bind(wx.EVT_MENU, self.OnQueryDisplay, display)
  1182. numLayers = 0
  1183. for layer in self.tree.GetSelections():
  1184. type = self.tree.GetPyData(layer)[0]['maplayer'].GetType()
  1185. if type in ('raster', 'rgb', 'his',
  1186. 'vector', 'thememap', 'themechart'):
  1187. numLayers += 1
  1188. if numLayers < 1:
  1189. display.Enable(False)
  1190. if action == "displayAttrb":
  1191. display.Check(True)
  1192. modify = wx.MenuItem(parentMenu=toolsmenu, id=wx.ID_ANY,
  1193. text=_("Query vector map (edit mode)"),
  1194. kind=wx.ITEM_CHECK)
  1195. toolsmenu.AppendItem(modify)
  1196. self.Bind(wx.EVT_MENU, self.OnQueryModify, modify)
  1197. digitToolbar = self.toolbars['vdigit']
  1198. if self.tree.layer_selected:
  1199. layer_selected = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer']
  1200. if layer_selected.GetType() != 'vector' or \
  1201. (digitToolbar and \
  1202. digitToolbar.GetLayer() == layer_selected):
  1203. modify.Enable(False)
  1204. else:
  1205. if action == "modifyAttrb":
  1206. modify.Check(True)
  1207. self.PopupMenu(toolsmenu)
  1208. toolsmenu.Destroy()
  1209. def AddTmpVectorMapLayer(self, name, cats, useId=False, addLayer=True):
  1210. """
  1211. Add temporal vector map layer to map composition
  1212. @param name name of map layer
  1213. @param useId use feature id instead of category
  1214. """
  1215. # color settings from ATM
  1216. color = UserSettings.Get(group='atm', key='highlight', subkey='color')
  1217. colorStr = str(color[0]) + ":" + \
  1218. str(color[1]) + ":" + \
  1219. str(color[2])
  1220. pattern = ["d.vect",
  1221. "map=%s" % name,
  1222. "color=%s" % colorStr,
  1223. "fcolor=%s" % colorStr,
  1224. "width=%d" % UserSettings.Get(group='atm', key='highlight', subkey='width')]
  1225. if useId:
  1226. cmd = pattern
  1227. cmd.append('-i')
  1228. cmd.append('cats=%s' % str(cats))
  1229. else:
  1230. cmd = []
  1231. for layer in cats.keys():
  1232. cmd.append(copy.copy(pattern))
  1233. lcats = cats[layer]
  1234. cmd[-1].append("layer=%d" % layer)
  1235. cmd[-1].append("cats=%s" % utils.ListOfCatsToRange(lcats))
  1236. # if self.icon:
  1237. # cmd.append("icon=%s" % (self.icon))
  1238. # if self.pointsize:
  1239. # cmd.append("size=%s" % (self.pointsize))
  1240. if addLayer:
  1241. if useId:
  1242. return self.Map.AddLayer(type='vector', name=globalvar.QUERYLAYER, command=cmd,
  1243. l_active=True, l_hidden=True, l_opacity=1.0)
  1244. else:
  1245. return self.Map.AddLayer(type='command', name=globalvar.QUERYLAYER, command=cmd,
  1246. l_active=True, l_hidden=True, l_opacity=1.0)
  1247. else:
  1248. return cmd
  1249. def OnAnalyze(self, event):
  1250. """
  1251. Analysis tools menu
  1252. """
  1253. point = wx.GetMousePosition()
  1254. toolsmenu = wx.Menu()
  1255. # Add items to the menu
  1256. measure = wx.MenuItem(toolsmenu, wx.ID_ANY, Icons["measure"].GetLabel())
  1257. measure.SetBitmap(Icons["measure"].GetBitmap(self.iconsize))
  1258. toolsmenu.AppendItem(measure)
  1259. self.Bind(wx.EVT_MENU, self.OnMeasure, measure)
  1260. profile = wx.MenuItem(toolsmenu, wx.ID_ANY, Icons["profile"].GetLabel())
  1261. profile.SetBitmap(Icons["profile"].GetBitmap(self.iconsize))
  1262. toolsmenu.AppendItem(profile)
  1263. self.Bind(wx.EVT_MENU, self.Profile, profile)
  1264. histogram = wx.MenuItem(toolsmenu, wx.ID_ANY, Icons["histogram"].GetLabel())
  1265. histogram.SetBitmap(Icons["histogram"].GetBitmap(self.iconsize))
  1266. toolsmenu.AppendItem(histogram)
  1267. self.Bind(wx.EVT_MENU, self.Histogram, histogram)
  1268. # Popup the menu. If an item is selected then its handler
  1269. # will be called before PopupMenu returns.
  1270. self.PopupMenu(toolsmenu)
  1271. toolsmenu.Destroy()
  1272. def OnMeasure(self, event):
  1273. """
  1274. Init measurement routine that calculates
  1275. map distance along transect drawn on
  1276. map display
  1277. """
  1278. self.totaldist = 0.0 # total measured distance
  1279. # switch GIS Manager to output console to show measure results
  1280. self._layerManager.notebook.SetSelection(1)
  1281. # change mouse to draw line for measurement
  1282. self.MapWindow.mouse['use'] = "measure"
  1283. self.MapWindow.mouse['box'] = "line"
  1284. self.MapWindow.zoomtype = 0
  1285. self.MapWindow.pen = wx.Pen(colour='red', width=2, style=wx.SHORT_DASH)
  1286. self.MapWindow.polypen = wx.Pen(colour='green', width=2, style=wx.SHORT_DASH)
  1287. # change the cursor
  1288. self.MapWindow.SetCursor(self.cursors["pencil"])
  1289. # initiating output
  1290. style = self._layerManager.goutput.cmd_output.StyleWarning
  1291. self._layerManager.goutput.WriteLog(_('Click and drag with left mouse button '
  1292. 'to measure.%s'
  1293. 'Double click with left button to clear.') % \
  1294. (os.linesep), style)
  1295. if self.Map.projinfo['proj'] != 'xy':
  1296. units = self.Map.projinfo['units']
  1297. style = self._layerManager.goutput.cmd_output.StyleCommand
  1298. self._layerManager.goutput.WriteLog(_('Measuring distance') + ' ('
  1299. + units + '):',
  1300. style)
  1301. else:
  1302. self._layerManager.goutput.WriteLog(_('Measuring distance:'),
  1303. style)
  1304. def MeasureDist(self, beginpt, endpt):
  1305. """
  1306. Calculate map distance from screen distance
  1307. and print to output window
  1308. """
  1309. if self._layerManager.notebook.GetSelection() != 1:
  1310. self._layerManager.notebook.SetSelection(1)
  1311. dist, (north, east) = self.MapWindow.Distance(beginpt, endpt)
  1312. dist = round(dist, 3)
  1313. d, dunits = self.FormatDist(dist)
  1314. self.totaldist += dist
  1315. td, tdunits = self.FormatDist(self.totaldist)
  1316. strdist = str(d)
  1317. strtotdist = str(td)
  1318. if self.Map.projinfo['proj'] == 'xy' or 'degree' not in self.Map.projinfo['unit']:
  1319. angle = int(math.degrees(math.atan2(north,east)) + 0.5)
  1320. angle = 180 - angle
  1321. if angle < 0:
  1322. angle = 360+angle
  1323. mstring = 'segment = %s %s\ttotal distance = %s %s\tbearing = %d deg' \
  1324. % (strdist,dunits,strtotdist,tdunits,angle)
  1325. else:
  1326. mstring = 'segment = %s %s\ttotal distance = %s %s' \
  1327. % (strdist,dunits,strtotdist,tdunits)
  1328. self._layerManager.goutput.WriteLog(mstring)
  1329. return dist
  1330. def Profile(self, event):
  1331. """
  1332. Init profile canvas and tools
  1333. """
  1334. raster = []
  1335. if self.tree.layer_selected and \
  1336. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] == 'raster':
  1337. raster.append(self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name)
  1338. self.profile = profile.ProfileFrame(self,
  1339. id=wx.ID_ANY, pos=wx.DefaultPosition, size=(700,300),
  1340. style=wx.DEFAULT_FRAME_STYLE, rasterList=raster)
  1341. self.profile.Show()
  1342. # Open raster select dialog to make sure that a raster (and the desired raster)
  1343. # is selected to be profiled
  1344. self.profile.OnSelectRaster(None)
  1345. def FormatDist(self, dist):
  1346. """!Format length numbers and units in a nice way,
  1347. as a function of length. From code by Hamish Bowman
  1348. Grass Development Team 2006"""
  1349. mapunits = self.Map.projinfo['units']
  1350. if mapunits == 'metres': mapunits = 'meters'
  1351. outunits = mapunits
  1352. dist = float(dist)
  1353. divisor = 1.0
  1354. # figure out which units to use
  1355. if mapunits == 'meters':
  1356. if dist > 2500.0:
  1357. outunits = 'km'
  1358. divisor = 1000.0
  1359. else: outunits = 'm'
  1360. elif mapunits == 'feet':
  1361. # nano-bug: we match any "feet", but US Survey feet is really
  1362. # 5279.9894 per statute mile, or 10.6' per 1000 miles. As >1000
  1363. # miles the tick markers are rounded to the nearest 10th of a
  1364. # mile (528'), the difference in foot flavours is ignored.
  1365. if dist > 5280.0:
  1366. outunits = 'miles'
  1367. divisor = 5280.0
  1368. else:
  1369. outunits = 'ft'
  1370. elif 'degree' in mapunits:
  1371. if dist < 1:
  1372. outunits = 'min'
  1373. divisor = (1/60.0)
  1374. else:
  1375. outunits = 'deg'
  1376. # format numbers in a nice way
  1377. if (dist/divisor) >= 2500.0:
  1378. outdist = round(dist/divisor)
  1379. elif (dist/divisor) >= 1000.0:
  1380. outdist = round(dist/divisor,1)
  1381. elif (dist/divisor) > 0.0:
  1382. outdist = round(dist/divisor,int(math.ceil(3-math.log10(dist/divisor))))
  1383. else:
  1384. outdist = float(dist/divisor)
  1385. return (outdist, outunits)
  1386. def Histogram(self, event):
  1387. """
  1388. Init histogram display canvas and tools
  1389. """
  1390. self.histogram = histogram.HistFrame(self,
  1391. id=wx.ID_ANY, size=globalvar.HIST_WINDOW_SIZE,
  1392. style=wx.DEFAULT_FRAME_STYLE)
  1393. #show new display
  1394. self.histogram.Show()
  1395. self.histogram.Refresh()
  1396. self.histogram.Update()
  1397. def OnDecoration(self, event):
  1398. """
  1399. Decorations overlay menu
  1400. """
  1401. point = wx.GetMousePosition()
  1402. decmenu = wx.Menu()
  1403. # Add items to the menu
  1404. AddScale = wx.MenuItem(decmenu, wx.ID_ANY, Icons["addbarscale"].GetLabel())
  1405. AddScale.SetBitmap(Icons["addbarscale"].GetBitmap(self.iconsize))
  1406. decmenu.AppendItem(AddScale)
  1407. self.Bind(wx.EVT_MENU, self.OnAddBarscale, AddScale)
  1408. AddLegend = wx.MenuItem(decmenu, wx.ID_ANY, Icons["addlegend"].GetLabel())
  1409. AddLegend.SetBitmap(Icons["addlegend"].GetBitmap(self.iconsize))
  1410. decmenu.AppendItem(AddLegend)
  1411. self.Bind(wx.EVT_MENU, self.OnAddLegend, AddLegend)
  1412. AddText = wx.MenuItem(decmenu, wx.ID_ANY, Icons["addtext"].GetLabel())
  1413. AddText.SetBitmap(Icons["addtext"].GetBitmap(self.iconsize))
  1414. decmenu.AppendItem(AddText)
  1415. self.Bind(wx.EVT_MENU, self.OnAddText, AddText)
  1416. # Popup the menu. If an item is selected then its handler
  1417. # will be called before PopupMenu returns.
  1418. self.PopupMenu(decmenu)
  1419. decmenu.Destroy()
  1420. def OnAddBarscale(self, event):
  1421. """
  1422. Handler for scale/arrow map decoration menu selection.
  1423. """
  1424. if self.dialogs['barscale']:
  1425. return
  1426. id = 0 # unique index for overlay layer
  1427. # If location is latlon, only display north arrow (scale won't work)
  1428. # proj = self.Map.projinfo['proj']
  1429. # if proj == 'll':
  1430. # barcmd = 'd.barscale -n'
  1431. # else:
  1432. # barcmd = 'd.barscale'
  1433. # decoration overlay control dialog
  1434. self.dialogs['barscale'] = \
  1435. gdialogs.DecorationDialog(parent=self, title=_('Scale and North arrow'),
  1436. size=(350, 200),
  1437. style=wx.DEFAULT_DIALOG_STYLE | wx.CENTRE,
  1438. cmd=['d.barscale', 'at=0,5'],
  1439. ovlId=id,
  1440. name='barscale',
  1441. checktxt = _("Show/hide scale and North arrow"),
  1442. ctrltxt = _("scale object"))
  1443. self.dialogs['barscale'].CentreOnParent()
  1444. ### dialog cannot be show as modal - in the result d.barscale is not selectable
  1445. ### self.dialogs['barscale'].ShowModal()
  1446. self.dialogs['barscale'].Show()
  1447. self.MapWindow.mouse['use'] = 'pointer'
  1448. def OnAddLegend(self, event):
  1449. """
  1450. Handler for legend map decoration menu selection.
  1451. """
  1452. if self.dialogs['legend']:
  1453. return
  1454. id = 1 # index for overlay layer in render
  1455. cmd = ['d.legend']
  1456. if self.tree.layer_selected and \
  1457. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] == 'raster':
  1458. cmd.append('map=%s' % self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name)
  1459. # Decoration overlay control dialog
  1460. self.dialogs['legend'] = \
  1461. gdialogs.DecorationDialog(parent=self, title=('Legend'),
  1462. size=(350, 200),
  1463. style=wx.DEFAULT_DIALOG_STYLE | wx.CENTRE,
  1464. cmd=cmd,
  1465. ovlId=id,
  1466. name='legend',
  1467. checktxt = _("Show/hide legend"),
  1468. ctrltxt = _("legend object"))
  1469. self.dialogs['legend'].CentreOnParent()
  1470. ### dialog cannot be show as modal - in the result d.legend is not selectable
  1471. ### self.dialogs['legend'].ShowModal()
  1472. self.dialogs['legend'].Show()
  1473. self.MapWindow.mouse['use'] = 'pointer'
  1474. def OnAddText(self, event):
  1475. """
  1476. Handler for text decoration menu selection.
  1477. """
  1478. if self.MapWindow.dragid > -1:
  1479. id = self.MapWindow.dragid
  1480. else:
  1481. # index for overlay layer in render
  1482. if len(self.MapWindow.textdict.keys()) > 0:
  1483. id = self.MapWindow.textdict.keys()[-1] + 1
  1484. else:
  1485. id = 101
  1486. self.dialogs['text'] = gdialogs.TextLayerDialog(parent=self, ovlId=id,
  1487. title=_('Add text layer'),
  1488. size=(400, 200))
  1489. self.dialogs['text'].CenterOnParent()
  1490. # If OK button pressed in decoration control dialog
  1491. if self.dialogs['text'].ShowModal() == wx.ID_OK:
  1492. text = self.dialogs['text'].GetValues()['text']
  1493. active = self.dialogs['text'].GetValues()['active']
  1494. coords, w, h = self.MapWindow.TextBounds(self.dialogs['text'].GetValues())
  1495. # delete object if it has no text or is not active
  1496. if text == '' or active == False:
  1497. try:
  1498. self.MapWindow.pdc.ClearId(id)
  1499. self.MapWindow.pdc.RemoveId(id)
  1500. del self.MapWindow.textdict[id]
  1501. except:
  1502. pass
  1503. return
  1504. self.MapWindow.pdc.ClearId(id)
  1505. self.MapWindow.pdc.SetId(id)
  1506. self.MapWindow.textdict[id] = self.dialogs['text'].GetValues()
  1507. self.MapWindow.Draw(self.MapWindow.pdcDec, img=self.MapWindow.textdict[id],
  1508. drawid=id, pdctype='text', coords=coords)
  1509. self.MapWindow.UpdateMap(render=False, renderVector=False)
  1510. self.MapWindow.mouse['use'] = 'pointer'
  1511. def GetOptData(self, dcmd, type, params, propwin):
  1512. """
  1513. Callback method for decoration overlay command generated by
  1514. dialog created in menuform.py
  1515. """
  1516. # Reset comand and rendering options in render.Map. Always render decoration.
  1517. # Showing/hiding handled by PseudoDC
  1518. self.Map.ChangeOverlay(ovltype=type, type='overlay', name='', command=dcmd,
  1519. l_active=True, l_render=False)
  1520. self.params[type] = params
  1521. self.propwin[type] = propwin
  1522. def OnZoomMenu(self, event):
  1523. """
  1524. Zoom menu
  1525. """
  1526. point = wx.GetMousePosition()
  1527. zoommenu = wx.Menu()
  1528. # Add items to the menu
  1529. zoommap = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to selected map(s)'))
  1530. zoommenu.AppendItem(zoommap)
  1531. self.Bind(wx.EVT_MENU, self.MapWindow.OnZoomToMap, zoommap)
  1532. zoomwind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to computational region (set with g.region)'))
  1533. zoommenu.AppendItem(zoomwind)
  1534. self.Bind(wx.EVT_MENU, self.MapWindow.ZoomToWind, zoomwind)
  1535. zoomdefault = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to default region'))
  1536. zoommenu.AppendItem(zoomdefault)
  1537. self.Bind(wx.EVT_MENU, self.MapWindow.ZoomToDefault, zoomdefault)
  1538. zoomsaved = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to saved region'))
  1539. zoommenu.AppendItem(zoomsaved)
  1540. self.Bind(wx.EVT_MENU, self.MapWindow.ZoomToSaved, zoomsaved)
  1541. savewind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Set computational region from display'))
  1542. zoommenu.AppendItem(savewind)
  1543. self.Bind(wx.EVT_MENU, self.MapWindow.DisplayToWind, savewind)
  1544. savezoom = wx.MenuItem(zoommenu, wx.ID_ANY, _('Save display geometry to named region'))
  1545. zoommenu.AppendItem(savezoom)
  1546. self.Bind(wx.EVT_MENU, self.MapWindow.SaveDisplayRegion, savezoom)
  1547. # Popup the menu. If an item is selected then its handler
  1548. # will be called before PopupMenu returns.
  1549. self.PopupMenu(zoommenu)
  1550. zoommenu.Destroy()
  1551. def SetProperties(self, render=False, mode=0, showCompExtent=False,
  1552. constrainRes=False):
  1553. """!Set properies of map display window"""
  1554. self.statusbarWin['render'].SetValue(render)
  1555. self.statusbarWin['toggle'].SetSelection(mode)
  1556. self.StatusbarUpdate()
  1557. self.statusbarWin['region'].SetValue(showCompExtent)
  1558. self.statusbarWin['resolution'].SetValue(constrainRes)
  1559. if showCompExtent:
  1560. self.MapWindow.regionCoords = []
  1561. def IsStandalone(self):
  1562. """!Check if Map display is standalone"""
  1563. if self._layerManager:
  1564. return False
  1565. return True
  1566. def GetLayerManager(self):
  1567. """!Get reference to Layer Manager
  1568. @return window reference
  1569. @return None (if standalone)
  1570. """
  1571. return self._layerManager
  1572. # end of class MapFrame
  1573. class MapApp(wx.App):
  1574. """
  1575. MapApp class
  1576. """
  1577. def OnInit(self):
  1578. wx.InitAllImageHandlers()
  1579. if __name__ == "__main__":
  1580. Map = render.Map() # instance of Map class to render GRASS display output to PPM file
  1581. else:
  1582. Map = None
  1583. self.mapFrm = MapFrame(parent=None, id=wx.ID_ANY, Map=Map,
  1584. size=globalvar.MAP_WINDOW_SIZE)
  1585. #self.SetTopWindow(Map)
  1586. self.mapFrm.Show()
  1587. if __name__ == "__main__":
  1588. # redraw map, if new command appears
  1589. self.redraw = False
  1590. status = Command(self, Map, cmdfilename)
  1591. status.start()
  1592. self.timer = wx.PyTimer(self.watcher)
  1593. # check each 0.1s
  1594. self.timer.Start(100)
  1595. return 1
  1596. def OnExit(self):
  1597. if __name__ == "__main__":
  1598. # stop the timer
  1599. self.timer.Stop()
  1600. # terminate thread (a bit ugly)
  1601. os.system("""!echo "quit" >> %s""" % (cmdfilename))
  1602. def watcher(self):
  1603. """!Redraw, if new layer appears"""
  1604. if self.redraw:
  1605. self.mapFrm.OnDraw(None)
  1606. self.redraw = False
  1607. return
  1608. # end of class MapApp
  1609. if __name__ == "__main__":
  1610. ###### SET command variable
  1611. if len(sys.argv) != 3:
  1612. print __doc__
  1613. sys.exit()
  1614. title = sys.argv[1]
  1615. cmdfilename = sys.argv[2]
  1616. import gettext
  1617. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode=True)
  1618. print >> sys.stderr, "\nStarting monitor <%s>...\n" % (title)
  1619. gm_map = MapApp(0)
  1620. # set title
  1621. gm_map.mapFrm.SetTitle(_("GRASS GIS Map Display: " +
  1622. title +
  1623. " - Location: " + grass.gisenv()["LOCATION_NAME"]))
  1624. gm_map.MainLoop()
  1625. os.remove(cmdfilename)
  1626. os.system("""!g.gisenv set="GRASS_PYCMDFILE" """)
  1627. print >> sys.stderr, "\nStopping monitor <%s>...\n" % (title)
  1628. sys.exit(0)