mapdisp.py 86 KB

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