mapdisp.py 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763
  1. """!
  2. @package mapdisp.py
  3. @brief Map display with toolbar for various display management
  4. functions, and additional toolbars (vector digitizer, 3d view).
  5. Can be used either from Layer Manager or as d.mon backend.
  6. Classes:
  7. - MapFrameBase
  8. - MapFrame
  9. - MapApp
  10. Usage:
  11. python mapdisp.py monitor-identifier /path/to/map/file /path/to/command/file /path/to/env/file
  12. (C) 2006-2011 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. @author Vaclav Petras <wenzeslaus gmail.com> (MapFrameBase)
  20. @author Anna Kratochvilova <kratochanna gmail.com> (MapFrameBase)
  21. """
  22. import os
  23. import sys
  24. import glob
  25. import math
  26. import tempfile
  27. import copy
  28. import globalvar
  29. import wx
  30. import wx.aui
  31. sys.path.append(os.path.join(globalvar.ETCWXDIR, "icons"))
  32. sys.path.append(os.path.join(globalvar.ETCDIR, "python"))
  33. import render
  34. import toolbars
  35. import menuform
  36. import gselect
  37. import disp_print
  38. import gcmd
  39. import dbm
  40. import dbm_dialogs
  41. import globalvar
  42. import utils
  43. import gdialogs
  44. import mapdisp_statusbar as sb
  45. from debug import Debug
  46. from icon import Icons
  47. from preferences import globalSettings as UserSettings
  48. from mapdisp_window import BufferedWindow
  49. from histogram import HistFrame
  50. from wxplot import HistFrame as HistFramePyPlot, ProfileFrame, ScatterFrame
  51. from grass.script import core as grass
  52. # for standalone app
  53. monFile = { 'cmd' : None,
  54. 'map' : None,
  55. 'env' : None,
  56. }
  57. monName = None
  58. monSize = list(globalvar.MAP_WINDOW_SIZE)
  59. haveCtypes = False
  60. class MapFrameBase(wx.Frame):
  61. """!Base class for map display window
  62. Derived class must use statusbarManager or override
  63. GetProperty, SetProperty and HasProperty methods.
  64. If derived class enables and disables auto-rendering,
  65. it should override IsAutoRendered method.
  66. """
  67. def __init__(self, parent = None, id = wx.ID_ANY, title = None,
  68. style = wx.DEFAULT_FRAME_STYLE, toolbars = None,
  69. Map = None, auimgr = None, name = None, **kwargs):
  70. """!
  71. @param toolbars array of activated toolbars, e.g. ['map', 'digit']
  72. @param Map instance of render.Map
  73. @param auimgs AUI manager
  74. @param name frame name
  75. @param kwargs wx.Frame attributes
  76. """
  77. self.Map = Map # instance of render.Map
  78. self.parent = parent
  79. wx.Frame.__init__(self, parent, id, title, style = style, name = name, **kwargs)
  80. # available cursors
  81. self.cursors = {
  82. # default: cross
  83. # "default" : wx.StockCursor(wx.CURSOR_DEFAULT),
  84. "default" : wx.StockCursor(wx.CURSOR_ARROW),
  85. "cross" : wx.StockCursor(wx.CURSOR_CROSS),
  86. "hand" : wx.StockCursor(wx.CURSOR_HAND),
  87. "pencil" : wx.StockCursor(wx.CURSOR_PENCIL),
  88. "sizenwse": wx.StockCursor(wx.CURSOR_SIZENWSE)
  89. }
  90. #
  91. # set the size & system icon
  92. #
  93. self.SetClientSize(self.GetSize())
  94. self.iconsize = (16, 16)
  95. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_map.ico'), wx.BITMAP_TYPE_ICO))
  96. #
  97. # Fancy gui
  98. #
  99. self._mgr = wx.aui.AuiManager(self)
  100. def _initMap(self, map):
  101. """!Initialize map display, set dimensions and map region
  102. """
  103. if not grass.find_program('g.region', ['--help']):
  104. sys.exit(_("GRASS module '%s' not found. Unable to start map "
  105. "display window.") % 'g.region')
  106. self.width, self.height = self.GetClientSize()
  107. Debug.msg(2, "MapFrame._initMap():")
  108. map.ChangeMapSize(self.GetClientSize())
  109. map.region = map.GetRegion() # g.region -upgc
  110. # self.Map.SetRegion() # adjust region to match display window
  111. def SetProperty(self, name, value):
  112. """!Sets property"""
  113. self.statusbarManager.SetProperty(name, value)
  114. def GetProperty(self, name):
  115. """!Returns property"""
  116. return self.statusbarManager.GetProperty(name)
  117. def HasProperty(self, name):
  118. """!Checks whether object has property"""
  119. return self.statusbarManager.HasProperty(name)
  120. def GetPPM(self):
  121. """! Get pixel per meter
  122. @todo now computed every time, is it necessary?
  123. @todo enable user to specify ppm (and store it in UserSettings)
  124. """
  125. # TODO: need to be fixed...
  126. ### screen X region problem
  127. ### user should specify ppm
  128. dc = wx.ScreenDC()
  129. dpSizePx = wx.DisplaySize() # display size in pixels
  130. dpSizeMM = wx.DisplaySizeMM() # display size in mm (system)
  131. dpSizeIn = (dpSizeMM[0] / 25.4, dpSizeMM[1] / 25.4) # inches
  132. sysPpi = dc.GetPPI()
  133. comPpi = (dpSizePx[0] / dpSizeIn[0],
  134. dpSizePx[1] / dpSizeIn[1])
  135. ppi = comPpi # pixel per inch
  136. ppm = ((ppi[0] / 2.54) * 100, # pixel per meter
  137. (ppi[1] / 2.54) * 100)
  138. Debug.msg(4, "MapFrameBase.GetPPM(): size: px=%d,%d mm=%f,%f "
  139. "in=%f,%f ppi: sys=%d,%d com=%d,%d; ppm=%f,%f" % \
  140. (dpSizePx[0], dpSizePx[1], dpSizeMM[0], dpSizeMM[1],
  141. dpSizeIn[0], dpSizeIn[1],
  142. sysPpi[0], sysPpi[1], comPpi[0], comPpi[1],
  143. ppm[0], ppm[1]))
  144. return ppm
  145. def SetMapScale(self, value, map = None):
  146. """! Set current map scale
  147. @param value scale value (n if scale is 1:n)
  148. @param map Map instance (if none self.Map is used)
  149. """
  150. if not map:
  151. map = self.Map
  152. region = self.Map.region
  153. dEW = value * (region['cols'] / self.GetPPM()[0])
  154. dNS = value * (region['rows'] / self.GetPPM()[1])
  155. region['n'] = region['center_northing'] + dNS / 2.
  156. region['s'] = region['center_northing'] - dNS / 2.
  157. region['w'] = region['center_easting'] - dEW / 2.
  158. region['e'] = region['center_easting'] + dEW / 2.
  159. # add to zoom history
  160. self.GetWindow().ZoomHistory(region['n'], region['s'],
  161. region['e'], region['w'])
  162. def GetMapScale(self, map = None):
  163. """! Get current map scale
  164. @param map Map instance (if none self.Map is used)
  165. """
  166. if not map:
  167. map = self.Map
  168. region = map.region
  169. ppm = self.GetPPM()
  170. heightCm = region['rows'] / ppm[1] * 100
  171. widthCm = region['cols'] / ppm[0] * 100
  172. Debug.msg(4, "MapFrame.GetMapScale(): width_cm=%f, height_cm=%f" %
  173. (widthCm, heightCm))
  174. xscale = (region['e'] - region['w']) / (region['cols'] / ppm[0])
  175. yscale = (region['n'] - region['s']) / (region['rows'] / ppm[1])
  176. scale = (xscale + yscale) / 2.
  177. Debug.msg(3, "MapFrame.GetMapScale(): xscale=%f, yscale=%f -> scale=%f" % \
  178. (xscale, yscale, scale))
  179. return scale
  180. def GetProgressBar(self):
  181. """!Returns progress bar
  182. Progress bar can be used by other classes.
  183. """
  184. return self.statusbarManager.GetProgressBar()
  185. def GetRender(self):
  186. """!Returns current instance of render.Map()
  187. @todo make this method obsolate (name GetMap is better)
  188. """
  189. return self.Map
  190. def GetMap(self):
  191. """!Returns current Map instance
  192. """
  193. return self.Map
  194. def GetWindow(self):
  195. """!Get map window"""
  196. return self.MapWindow
  197. def GetMapToolbar(self):
  198. """!Returns toolbar with zooming tools"""
  199. raise NotImplementedError()
  200. def StatusbarUpdate(self):
  201. """!Update statusbar content"""
  202. self.statusbarManager.Update()
  203. def IsAutoRendered(self):
  204. """!Check if auto-rendering is enabled"""
  205. return self.GetProperty('render')
  206. def CoordinatesChanged(self):
  207. """!Shows current coordinates on statusbar.
  208. Used in BufferedWindow to report change of map coordinates (under mouse cursor).
  209. """
  210. self.statusbarManager.ShowItem('coordinates')
  211. def StatusbarReposition(self):
  212. """!Reposition items in statusbar"""
  213. self.statusbarManager.Reposition()
  214. def StatusbarEnableLongHelp(self, enable = True):
  215. """!Enable/disable toolbars long help"""
  216. for toolbar in self.toolbars.itervalues():
  217. if toolbar:
  218. toolbar.EnableLongHelp(enable)
  219. def IsStandalone(self):
  220. """!Check if Map display is standalone"""
  221. raise NotImplementedError("IsStandalone")
  222. class MapFrame(MapFrameBase):
  223. """!Main frame for map display window. Drawing takes place in
  224. child double buffered drawing window.
  225. """
  226. def __init__(self, parent = None, title = _("GRASS GIS - Map display"),
  227. toolbars = ["map"], tree = None, notebook = None, lmgr = None,
  228. page = None, Map = None, auimgr = None, name = 'MapWindow', **kwargs):
  229. """!Main map display window with toolbars, statusbar and
  230. BufferedWindow (map canvas)
  231. @param toolbars array of activated toolbars, e.g. ['map', 'digit']
  232. @param tree reference to layer tree
  233. @param notebook control book ID in Layer Manager
  234. @param lmgr Layer Manager
  235. @param page notebook page with layer tree
  236. @param Map instance of render.Map
  237. @param auimgs AUI manager
  238. @param name frame name
  239. @param kwargs wx.Frame attributes
  240. """
  241. MapFrameBase.__init__(self, parent = parent, title = title, toolbars = toolbars,
  242. Map = Map, auimgr = auimgr, name = name, **kwargs)
  243. self._layerManager = lmgr # Layer Manager object
  244. self.tree = tree # Layer Manager layer tree object
  245. self.page = page # Notebook page holding the layer tree
  246. self.layerbook = notebook # Layer Manager layer tree notebook
  247. #
  248. # Add toolbars
  249. #
  250. self.toolbars = { 'map' : None,
  251. 'vdigit' : None,
  252. 'gcpdisp' : None,
  253. 'gcpman' : None,
  254. 'nviz' : None }
  255. for toolb in toolbars:
  256. self.AddToolbar(toolb)
  257. #
  258. # Add statusbar
  259. #
  260. # items for choice
  261. self.statusbarItems = [sb.SbCoordinates,
  262. sb.SbRegionExtent,
  263. sb.SbCompRegionExtent,
  264. sb.SbShowRegion,
  265. sb.SbAlignExtent,
  266. sb.SbResolution,
  267. sb.SbDisplayGeometry,
  268. sb.SbMapScale,
  269. sb.SbGoTo,
  270. sb.SbProjection]
  271. self.statusbarItemsHiddenInNviz = (sb.SbAlignExtent,
  272. sb.SbDisplayGeometry,
  273. sb.SbShowRegion,
  274. sb.SbResolution,
  275. sb.SbMapScale)
  276. # create statusbar and its manager
  277. statusbar = self.CreateStatusBar(number = 4, style = 0)
  278. statusbar.SetStatusWidths([-5, -2, -1, -1])
  279. self.statusbarManager = sb.SbManager(mapframe = self, statusbar = statusbar)
  280. # fill statusbar manager
  281. self.statusbarManager.AddStatusbarItemsByClass(self.statusbarItems, mapframe = self, statusbar = statusbar)
  282. self.statusbarManager.AddStatusbarItem(sb.SbMask(self, statusbar = statusbar, position = 2))
  283. self.statusbarManager.AddStatusbarItem(sb.SbRender(self, statusbar = statusbar, position = 3))
  284. self.statusbarManager.Update()
  285. #
  286. # Init map display (buffered DC & set default cursor)
  287. #
  288. self.MapWindow2D = BufferedWindow(self, id = wx.ID_ANY,
  289. Map = self.Map, tree = self.tree, lmgr = self._layerManager)
  290. # default is 2D display mode
  291. self.MapWindow = self.MapWindow2D
  292. self.MapWindow.SetCursor(self.cursors["default"])
  293. # used by vector digitizer
  294. self.MapWindowVDigit = None
  295. # used by Nviz (3D display mode)
  296. self.MapWindow3D = None
  297. #
  298. # initialize region values
  299. #
  300. self._initMap(map = self.Map)
  301. #
  302. # Bind various events
  303. #
  304. self.Bind(wx.EVT_ACTIVATE, self.OnFocus)
  305. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  306. self.Bind(render.EVT_UPDATE_PRGBAR, self.OnUpdateProgress)
  307. #
  308. # Update fancy gui style
  309. #
  310. self._mgr.AddPane(self.MapWindow, wx.aui.AuiPaneInfo().CentrePane().
  311. Dockable(False).BestSize((-1,-1)).Name('2d').
  312. CloseButton(False).DestroyOnClose(True).
  313. Layer(0))
  314. self._mgr.Update()
  315. #
  316. # Init print module and classes
  317. #
  318. self.printopt = disp_print.PrintOptions(self, self.MapWindow)
  319. #
  320. # Init zoom history
  321. #
  322. self.MapWindow.ZoomHistory(self.Map.region['n'],
  323. self.Map.region['s'],
  324. self.Map.region['e'],
  325. self.Map.region['w'])
  326. #
  327. # Re-use dialogs
  328. #
  329. self.dialogs = {}
  330. self.dialogs['attributes'] = None
  331. self.dialogs['category'] = None
  332. self.dialogs['barscale'] = None
  333. self.dialogs['legend'] = None
  334. self.decorationDialog = None # decoration/overlays
  335. def _addToolbarVDigit(self):
  336. """!Add vector digitizer toolbar
  337. """
  338. from vdigit import haveVDigit
  339. if not haveVDigit:
  340. from vdigit import errorMsg
  341. msg = _("Unable to start wxGUI vector digitizer.\nDo you want to start "
  342. "TCL/TK digitizer (v.digit) instead?\n\n"
  343. "Details: %s" % errorMsg)
  344. self.toolbars['map'].combo.SetValue(_("2D view"))
  345. dlg = wx.MessageDialog(parent = self,
  346. message = msg,
  347. caption=_("Vector digitizer failed"),
  348. style = wx.YES_NO | wx.CENTRE)
  349. if dlg.ShowModal() == wx.ID_YES:
  350. mapName = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].GetName()
  351. self._layerManager.goutput.RunCmd(['v.digit', 'map=%s' % mapName],
  352. switchPage = False)
  353. dlg.Destroy()
  354. self.toolbars['map'].combo.SetValue(_("2D view"))
  355. return
  356. if self._layerManager:
  357. log = self._layerManager.goutput
  358. else:
  359. log = None
  360. if not self.MapWindowVDigit:
  361. from mapdisp_vdigit import VDigitWindow
  362. self.MapWindowVDigit = VDigitWindow(self, id = wx.ID_ANY,
  363. Map = self.Map, tree = self.tree,
  364. lmgr = self._layerManager)
  365. self.MapWindowVDigit.Show()
  366. self._mgr.AddPane(self.MapWindowVDigit, wx.aui.AuiPaneInfo().CentrePane().
  367. Dockable(False).BestSize((-1,-1)).Name('vdigit').
  368. CloseButton(False).DestroyOnClose(True).
  369. Layer(0))
  370. self.MapWindow = self.MapWindowVDigit
  371. if self._mgr.GetPane('2d').IsShown():
  372. self._mgr.GetPane('2d').Hide()
  373. elif self._mgr.GetPane('3d').IsShown():
  374. self._mgr.GetPane('3d').Hide()
  375. self._mgr.GetPane('vdigit').Show()
  376. self.toolbars['vdigit'] = toolbars.VDigitToolbar(parent = self, mapcontent = self.Map,
  377. layerTree = self.tree,
  378. log = log)
  379. self.MapWindowVDigit.SetToolbar(self.toolbars['vdigit'])
  380. self._mgr.AddPane(self.toolbars['vdigit'],
  381. wx.aui.AuiPaneInfo().
  382. Name("vdigittoolbar").Caption(_("Vector Digitizer Toolbar")).
  383. ToolbarPane().Top().Row(1).
  384. LeftDockable(False).RightDockable(False).
  385. BottomDockable(False).TopDockable(True).
  386. CloseButton(False).Layer(2).
  387. BestSize((self.toolbars['vdigit'].GetBestSize())))
  388. # change mouse to draw digitized line
  389. self.MapWindow.mouse['box'] = "point"
  390. self.MapWindow.zoomtype = 0
  391. self.MapWindow.pen = wx.Pen(colour = 'red', width = 2, style = wx.SOLID)
  392. self.MapWindow.polypen = wx.Pen(colour = 'green', width = 2, style = wx.SOLID)
  393. def AddNviz(self):
  394. """!Add 3D view mode window
  395. """
  396. import nviz
  397. # check for GLCanvas and OpenGL
  398. if not nviz.haveNviz:
  399. self.toolbars['map'].combo.SetValue(_("2D view"))
  400. gcmd.GError(parent = self,
  401. message = _("Unable to switch to 3D display mode.\nThe Nviz python extension "
  402. "was not found or loaded properly.\n"
  403. "Switching back to 2D display mode.\n\nDetails: %s" % nviz.errorMsg))
  404. return
  405. # disable 3D mode for other displays
  406. for page in range(0, self._layerManager.gm_cb.GetPageCount()):
  407. if self._layerManager.gm_cb.GetPage(page) != self._layerManager.curr_page:
  408. if '3D' in self._layerManager.gm_cb.GetPage(page).maptree.mapdisplay.toolbars['map'].combo.GetString(1):
  409. self._layerManager.gm_cb.GetPage(page).maptree.mapdisplay.toolbars['map'].combo.Delete(1)
  410. self.toolbars['map'].Enable2D(False)
  411. # add rotate tool to map toolbar
  412. self.toolbars['map'].InsertTool((('rotate', Icons['nviz']['rotate'],
  413. self.OnRotate, wx.ITEM_CHECK,7),)) # 7 is position
  414. self.toolbars['map'].ChangeToolsDesc(mode2d = False)
  415. # update status bar
  416. self.statusbarManager.HideStatusbarChoiceItemsByClass(self.statusbarItemsHiddenInNviz)
  417. self.statusbarManager.SetMode(0)
  418. # erase map window
  419. self.MapWindow.EraseMap()
  420. self._layerManager.goutput.WriteCmdLog(_("Starting 3D view mode..."),
  421. switchPage = False)
  422. self.SetStatusText(_("Please wait, loading data..."), 0)
  423. # create GL window
  424. if not self.MapWindow3D:
  425. self.MapWindow3D = nviz.GLWindow(self, id = wx.ID_ANY,
  426. Map = self.Map, tree = self.tree, lmgr = self._layerManager)
  427. self.MapWindow = self.MapWindow3D
  428. self.MapWindow.SetCursor(self.cursors["default"])
  429. # add Nviz notebookpage
  430. self._layerManager.AddNvizTools()
  431. # switch from MapWindow to MapWindowGL
  432. self._mgr.GetPane('2d').Hide()
  433. self._mgr.AddPane(self.MapWindow3D, wx.aui.AuiPaneInfo().CentrePane().
  434. Dockable(False).BestSize((-1,-1)).Name('3d').
  435. CloseButton(False).DestroyOnClose(True).
  436. Layer(0))
  437. self.MapWindow3D.OnPaint(None) # -> LoadData
  438. self.MapWindow3D.Show()
  439. self.MapWindow3D.ResetViewHistory()
  440. self.MapWindow3D.UpdateView(None)
  441. else:
  442. self.MapWindow = self.MapWindow3D
  443. os.environ['GRASS_REGION'] = self.Map.SetRegion(windres = True)
  444. self.MapWindow3D.GetDisplay().Init()
  445. del os.environ['GRASS_REGION']
  446. # switch from MapWindow to MapWindowGL
  447. self._mgr.GetPane('2d').Hide()
  448. self._mgr.GetPane('3d').Show()
  449. # add Nviz notebookpage
  450. self._layerManager.AddNvizTools()
  451. self.MapWindow3D.ResetViewHistory()
  452. for page in ('view', 'light', 'fringe', 'constant', 'cplane'):
  453. self._layerManager.nviz.UpdatePage(page)
  454. self.SetStatusText("", 0)
  455. self._mgr.Update()
  456. def RemoveNviz(self):
  457. """!Restore 2D view"""
  458. self.toolbars['map'].RemoveTool(self.toolbars['map'].rotate)
  459. # update status bar
  460. self.statusbarManager.ShowStatusbarChoiceItemsByClass(self.statusbarItemsHiddenInNviz)
  461. self.statusbarManager.SetMode(UserSettings.Get(group = 'display',
  462. key = 'statusbarMode',
  463. subkey = 'selection'))
  464. self.SetStatusText(_("Please wait, unloading data..."), 0)
  465. self._layerManager.goutput.WriteCmdLog(_("Switching back to 2D view mode..."),
  466. switchPage = False)
  467. self.MapWindow3D.UnloadDataLayers(force = True)
  468. # switch from MapWindowGL to MapWindow
  469. self._mgr.GetPane('2d').Show()
  470. self._mgr.GetPane('3d').Hide()
  471. self.MapWindow = self.MapWindow2D
  472. # remove nviz notebook page
  473. self._layerManager.RemoveNvizTools()
  474. self.MapWindow.UpdateMap()
  475. self._mgr.Update()
  476. def AddToolbar(self, name):
  477. """!Add defined toolbar to the window
  478. Currently known toolbars are:
  479. - 'map' - basic map toolbar
  480. - 'vdigit' - vector digitizer
  481. - 'gcpdisp' - GCP Manager Display
  482. """
  483. # default toolbar
  484. if name == "map":
  485. self.toolbars['map'] = toolbars.MapToolbar(self, self.Map)
  486. self._mgr.AddPane(self.toolbars['map'],
  487. wx.aui.AuiPaneInfo().
  488. Name("maptoolbar").Caption(_("Map Toolbar")).
  489. ToolbarPane().Top().Name('mapToolbar').
  490. LeftDockable(False).RightDockable(False).
  491. BottomDockable(False).TopDockable(True).
  492. CloseButton(False).Layer(2).
  493. BestSize((self.toolbars['map'].GetBestSize())))
  494. # vector digitizer
  495. elif name == "vdigit":
  496. self._addToolbarVDigit()
  497. self._mgr.Update()
  498. def RemoveToolbar (self, name):
  499. """!Removes defined toolbar from the window
  500. @todo Only hide, activate by calling AddToolbar()
  501. """
  502. # cannot hide main toolbar
  503. if name == "map":
  504. return
  505. self._mgr.DetachPane(self.toolbars[name])
  506. self.toolbars[name].Destroy()
  507. self.toolbars[name] = None
  508. if name == 'vdigit':
  509. self._mgr.GetPane('vdigit').Hide()
  510. self._mgr.GetPane('2d').Show()
  511. self.MapWindow = self.MapWindow2D
  512. self.toolbars['map'].combo.SetValue(_("2D view"))
  513. self.toolbars['map'].Enable2D(True)
  514. self._mgr.Update()
  515. def IsPaneShown(self, name):
  516. """!Check if pane (toolbar, mapWindow ...) of given name is currently shown"""
  517. if self._mgr.GetPane(name).IsOk():
  518. return self._mgr.GetPane(name).IsShown()
  519. return False
  520. def OnUpdateProgress(self, event):
  521. """!Update progress bar info
  522. """
  523. self.GetProgressBar().SetValue(event.value)
  524. event.Skip()
  525. def OnFocus(self, event):
  526. """!Change choicebook page to match display.
  527. """
  528. # change bookcontrol page to page associated with display
  529. if self.page:
  530. pgnum = self.layerbook.GetPageIndex(self.page)
  531. if pgnum > -1:
  532. self.layerbook.SetSelection(pgnum)
  533. self._layerManager.curr_page = self.layerbook.GetCurrentPage()
  534. event.Skip()
  535. def OnDraw(self, event):
  536. """!Re-display current map composition
  537. """
  538. self.MapWindow.UpdateMap(render = False)
  539. def OnRender(self, event):
  540. """!Re-render map composition (each map layer)
  541. """
  542. # delete tmp map layers (queries)
  543. qlayer = self.Map.GetListOfLayers(l_name = globalvar.QUERYLAYER)
  544. for layer in qlayer:
  545. self.Map.DeleteLayer(layer)
  546. # delete tmp lines
  547. if self.MapWindow.mouse["use"] in ("measure",
  548. "profile"):
  549. self.MapWindow.polycoords = []
  550. self.MapWindow.ClearLines()
  551. # deselect features in vdigit
  552. if self.toolbars['vdigit']:
  553. self.MapWindow.digit.GetDisplay().SetSelected([])
  554. self.MapWindow.UpdateMap(render = True, renderVector = True)
  555. else:
  556. self.MapWindow.UpdateMap(render = True)
  557. # update statusbar
  558. self.StatusbarUpdate()
  559. def OnPointer(self, event):
  560. """!Pointer button clicked
  561. """
  562. if self.toolbars['map']:
  563. if event:
  564. self.toolbars['map'].OnTool(event)
  565. self.toolbars['map'].action['desc'] = ''
  566. self.MapWindow.mouse['use'] = "pointer"
  567. self.MapWindow.mouse['box'] = "point"
  568. # change the cursor
  569. if self.toolbars['vdigit']:
  570. # digitization tool activated
  571. self.MapWindow.SetCursor(self.cursors["cross"])
  572. # reset mouse['box'] if needed
  573. if self.toolbars['vdigit'].GetAction() in ['addLine']:
  574. if self.toolbars['vdigit'].GetAction('type') in ['point', 'centroid']:
  575. self.MapWindow.mouse['box'] = 'point'
  576. else: # line, boundary
  577. self.MapWindow.mouse['box'] = 'line'
  578. elif self.toolbars['vdigit'].GetAction() in ['addVertex', 'removeVertex', 'splitLine',
  579. 'editLine', 'displayCats', 'queryMap',
  580. 'copyCats']:
  581. self.MapWindow.mouse['box'] = 'point'
  582. else: # moveLine, deleteLine
  583. self.MapWindow.mouse['box'] = 'box'
  584. else:
  585. self.MapWindow.SetCursor(self.cursors["default"])
  586. def OnZoomIn(self, event):
  587. """!Zoom in the map.
  588. Set mouse cursor, zoombox attributes, and zoom direction
  589. """
  590. if self.toolbars['map']:
  591. self.toolbars['map'].OnTool(event)
  592. self.toolbars['map'].action['desc'] = ''
  593. self.MapWindow.mouse['use'] = "zoom"
  594. self.MapWindow.mouse['box'] = "box"
  595. self.MapWindow.zoomtype = 1
  596. self.MapWindow.pen = wx.Pen(colour = 'Red', width = 2, style = wx.SHORT_DASH)
  597. # change the cursor
  598. self.MapWindow.SetCursor(self.cursors["cross"])
  599. def OnZoomOut(self, event):
  600. """!Zoom out the map.
  601. Set mouse cursor, zoombox attributes, and zoom direction
  602. """
  603. if self.toolbars['map']:
  604. self.toolbars['map'].OnTool(event)
  605. self.toolbars['map'].action['desc'] = ''
  606. self.MapWindow.mouse['use'] = "zoom"
  607. self.MapWindow.mouse['box'] = "box"
  608. self.MapWindow.zoomtype = -1
  609. self.MapWindow.pen = wx.Pen(colour = 'Red', width = 2, style = wx.SHORT_DASH)
  610. # change the cursor
  611. self.MapWindow.SetCursor(self.cursors["cross"])
  612. def OnZoomBack(self, event):
  613. """!Zoom last (previously stored position)
  614. """
  615. self.MapWindow.ZoomBack()
  616. def OnPan(self, event):
  617. """!Panning, set mouse to drag
  618. """
  619. if self.toolbars['map']:
  620. self.toolbars['map'].OnTool(event)
  621. self.toolbars['map'].action['desc'] = ''
  622. self.MapWindow.mouse['use'] = "pan"
  623. self.MapWindow.mouse['box'] = "pan"
  624. self.MapWindow.zoomtype = 0
  625. # change the cursor
  626. self.MapWindow.SetCursor(self.cursors["hand"])
  627. def OnRotate(self, event):
  628. """!Rotate 3D view
  629. """
  630. if self.toolbars['map']:
  631. self.toolbars['map'].OnTool(event)
  632. self.toolbars['map'].action['desc'] = ''
  633. self.MapWindow.mouse['use'] = "rotate"
  634. # change the cursor
  635. self.MapWindow.SetCursor(self.cursors["hand"])
  636. def OnErase(self, event):
  637. """!Erase the canvas
  638. """
  639. self.MapWindow.EraseMap()
  640. def OnZoomRegion(self, event):
  641. """!Zoom to region
  642. """
  643. self.Map.getRegion()
  644. self.Map.getResolution()
  645. self.UpdateMap()
  646. # event.Skip()
  647. def OnAlignRegion(self, event):
  648. """!Align region
  649. """
  650. if not self.Map.alignRegion:
  651. self.Map.alignRegion = True
  652. else:
  653. self.Map.alignRegion = False
  654. # event.Skip()
  655. def SaveToFile(self, event):
  656. """!Save map to image
  657. """
  658. if self.IsPaneShown('3d'):
  659. filetype = "PPM file (*.ppm)|*.ppm|TIF file (*.tif)|*.tif"
  660. ltype = [{ 'ext' : 'ppm', 'type' : 'ppm' },
  661. { 'ext' : 'tif', 'type' : 'tif' }]
  662. else:
  663. img = self.MapWindow.img
  664. if not img:
  665. gcmd.GMessage(parent = self,
  666. message = _("Nothing to render (empty map). Operation canceled."))
  667. return
  668. filetype, ltype = gdialogs.GetImageHandlers(img)
  669. # get size
  670. dlg = gdialogs.ImageSizeDialog(self)
  671. dlg.CentreOnParent()
  672. if dlg.ShowModal() != wx.ID_OK:
  673. dlg.Destroy()
  674. return
  675. width, height = dlg.GetValues()
  676. dlg.Destroy()
  677. # get filename
  678. dlg = wx.FileDialog(parent = self,
  679. message = _("Choose a file name to save the image "
  680. "(no need to add extension)"),
  681. wildcard = filetype,
  682. style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  683. if dlg.ShowModal() == wx.ID_OK:
  684. path = dlg.GetPath()
  685. if not path:
  686. dlg.Destroy()
  687. return
  688. base, ext = os.path.splitext(path)
  689. fileType = ltype[dlg.GetFilterIndex()]['type']
  690. extType = ltype[dlg.GetFilterIndex()]['ext']
  691. if ext != extType:
  692. path = base + '.' + extType
  693. self.MapWindow.SaveToFile(path, fileType,
  694. width, height)
  695. dlg.Destroy()
  696. def PrintMenu(self, event):
  697. """
  698. Print options and output menu for map display
  699. """
  700. point = wx.GetMousePosition()
  701. printmenu = wx.Menu()
  702. # Add items to the menu
  703. setup = wx.MenuItem(printmenu, wx.ID_ANY, _('Page setup'))
  704. printmenu.AppendItem(setup)
  705. self.Bind(wx.EVT_MENU, self.printopt.OnPageSetup, setup)
  706. preview = wx.MenuItem(printmenu, wx.ID_ANY, _('Print preview'))
  707. printmenu.AppendItem(preview)
  708. self.Bind(wx.EVT_MENU, self.printopt.OnPrintPreview, preview)
  709. doprint = wx.MenuItem(printmenu, wx.ID_ANY, _('Print display'))
  710. printmenu.AppendItem(doprint)
  711. self.Bind(wx.EVT_MENU, self.printopt.OnDoPrint, doprint)
  712. # Popup the menu. If an item is selected then its handler
  713. # will be called before PopupMenu returns.
  714. self.PopupMenu(printmenu)
  715. printmenu.Destroy()
  716. def OnCloseWindow(self, event):
  717. """!Window closed.
  718. Also close associated layer tree page
  719. """
  720. pgnum = None
  721. self.Map.Clean()
  722. # close edited map and 3D tools properly
  723. if self.toolbars['vdigit']:
  724. maplayer = self.toolbars['vdigit'].GetLayer()
  725. if maplayer:
  726. self.toolbars['vdigit'].OnExit()
  727. if self.IsPaneShown('3d'):
  728. self.RemoveNviz()
  729. if not self._layerManager:
  730. self.Destroy()
  731. elif self.page:
  732. pgnum = self.layerbook.GetPageIndex(self.page)
  733. if pgnum > -1:
  734. self.layerbook.DeletePage(pgnum)
  735. def QueryMap(self, x, y):
  736. """!Query raster or vector map layers by r/v.what
  737. @param x,y coordinates
  738. """
  739. # set query snap distance for v.what at map unit equivalent of 10 pixels
  740. qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) / self.Map.width)
  741. east, north = self.MapWindow.Pixel2Cell((x, y))
  742. if not self.IsStandalone():
  743. num = 0
  744. for layer in self.tree.GetSelections():
  745. ltype = self.tree.GetPyData(layer)[0]['maplayer'].GetType()
  746. if ltype in ('raster', 'rgb', 'his',
  747. 'vector', 'thememap', 'themechart'):
  748. num += 1
  749. if num < 1:
  750. gcmd.GMessage(parent = self,
  751. message = _('No raster or vector map layer selected for querying.'))
  752. return
  753. rast = list()
  754. vect = list()
  755. rcmd = ['r.what', '--v']
  756. vcmd = ['v.what', '--v']
  757. if self.IsStandalone():
  758. pass
  759. else:
  760. for layer in self.tree.GetSelections():
  761. ltype = self.tree.GetPyData(layer)[0]['maplayer'].GetType()
  762. dcmd = self.tree.GetPyData(layer)[0]['cmd']
  763. name, found = utils.GetLayerNameFromCmd(dcmd)
  764. if not found:
  765. continue
  766. if ltype == 'raster':
  767. rast.append(name)
  768. elif ltype in ('rgb', 'his'):
  769. for iname in name.split('\n'):
  770. rast.append(iname)
  771. elif ltype in ('vector', 'thememap', 'themechart'):
  772. vect.append(name)
  773. # rasters are not queried this way in 3D, we don't want them now
  774. if self.IsPaneShown('3d'):
  775. rast = list()
  776. # use display region settings instead of computation region settings
  777. self.tmpreg = os.getenv("GRASS_REGION")
  778. os.environ["GRASS_REGION"] = self.Map.SetRegion(windres = False)
  779. # build query commands for any selected rasters and vectors
  780. if rast:
  781. rcmd.append('-f')
  782. rcmd.append('-n')
  783. rcmd.append('input=%s' % ','.join(rast))
  784. rcmd.append('east_north=%f,%f' % (float(east), float(north)))
  785. if vect:
  786. # check for vector maps open to be edited
  787. digitToolbar = self.toolbars['vdigit']
  788. if digitToolbar:
  789. lmap = digitToolbar.GetLayer().GetName()
  790. for name in vect:
  791. if lmap == name:
  792. self._layerManager.goutput.WriteWarning(_("Vector map <%s> "
  793. "opened for editing - skipped.") % map)
  794. vect.remove(name)
  795. if len(vect) < 1:
  796. self._layerManager.goutput.WriteCmdLog(_("Nothing to query."))
  797. return
  798. vcmd.append('-a')
  799. vcmd.append('map=%s' % ','.join(vect))
  800. vcmd.append('layer=%s' % ','.join(['-1'] * len(vect)))
  801. vcmd.append('east_north=%f,%f' % (float(east), float(north)))
  802. vcmd.append('distance=%f' % float(qdist))
  803. Debug.msg(1, "QueryMap(): raster=%s vector=%s" % (','.join(rast),
  804. ','.join(vect)))
  805. # parse query command(s)
  806. if not self.IsStandalone():
  807. if rast:
  808. self._layerManager.goutput.RunCmd(rcmd,
  809. compReg = False,
  810. onDone = self._QueryMapDone)
  811. if vect:
  812. self._layerManager.goutput.RunCmd(vcmd,
  813. onDone = self._QueryMapDone)
  814. else:
  815. if rast:
  816. gcmd.RunCommand(rcmd)
  817. if vect:
  818. gcmd.RunCommand(vcmd)
  819. def _QueryMapDone(self, cmd, returncode):
  820. """!Restore settings after querying (restore GRASS_REGION)
  821. @param returncode command return code
  822. """
  823. if hasattr(self, "tmpreg"):
  824. if self.tmpreg:
  825. os.environ["GRASS_REGION"] = self.tmpreg
  826. elif 'GRASS_REGION' in os.environ:
  827. del os.environ["GRASS_REGION"]
  828. elif 'GRASS_REGION' in os.environ:
  829. del os.environ["GRASS_REGION"]
  830. if hasattr(self, "tmpreg"):
  831. del self.tmpreg
  832. def QueryVector(self, x, y):
  833. """!Query vector map layer features
  834. Attribute data of selected vector object are displayed in GUI dialog.
  835. Data can be modified (On Submit)
  836. """
  837. if not self.tree.layer_selected or \
  838. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] != 'vector':
  839. gcmd.GMessage(parent = self,
  840. message = _("No map layer selected for querying."))
  841. return
  842. posWindow = self.ClientToScreen((x + self.MapWindow.dialogOffset,
  843. y + self.MapWindow.dialogOffset))
  844. qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) /
  845. self.Map.width)
  846. east, north = self.MapWindow.Pixel2Cell((x, y))
  847. mapName = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name
  848. if self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].GetMapset() != \
  849. grass.gisenv()['MAPSET']:
  850. mode = 'display'
  851. else:
  852. mode = 'update'
  853. if self.dialogs['attributes'] is None:
  854. dlg = dbm_dialogs.DisplayAttributesDialog(parent = self.MapWindow,
  855. map = mapName,
  856. query = ((east, north), qdist),
  857. pos = posWindow,
  858. action = mode)
  859. self.dialogs['attributes'] = dlg
  860. else:
  861. # selection changed?
  862. if not self.dialogs['attributes'].mapDBInfo or \
  863. self.dialogs['attributes'].mapDBInfo.map != mapName:
  864. self.dialogs['attributes'].UpdateDialog(map = mapName, query = ((east, north), qdist),
  865. action = mode)
  866. else:
  867. self.dialogs['attributes'].UpdateDialog(query = ((east, north), qdist),
  868. action = mode)
  869. if not self.dialogs['attributes'].IsFound():
  870. self._layerManager.goutput.WriteLog(_('Nothing found.'))
  871. cats = self.dialogs['attributes'].GetCats()
  872. qlayer = None
  873. if not self.IsPaneShown('3d'):
  874. try:
  875. qlayer = self.Map.GetListOfLayers(l_name = globalvar.QUERYLAYER)[0]
  876. except IndexError:
  877. pass
  878. if self.dialogs['attributes'].mapDBInfo and cats:
  879. if not self.IsPaneShown('3d'):
  880. # highlight feature & re-draw map
  881. if qlayer:
  882. qlayer.SetCmd(self.AddTmpVectorMapLayer(mapName, cats,
  883. useId = False,
  884. addLayer = False))
  885. else:
  886. qlayer = self.AddTmpVectorMapLayer(mapName, cats, useId = False)
  887. # set opacity based on queried layer
  888. opacity = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].GetOpacity(float = True)
  889. qlayer.SetOpacity(opacity)
  890. self.MapWindow.UpdateMap(render = False, renderVector = False)
  891. if not self.dialogs['attributes'].IsShown():
  892. self.dialogs['attributes'].Show()
  893. else:
  894. if qlayer:
  895. self.Map.DeleteLayer(qlayer)
  896. self.MapWindow.UpdateMap(render = False, renderVector = False)
  897. if self.dialogs['attributes'].IsShown():
  898. self.dialogs['attributes'].Hide()
  899. def OnQuery(self, event):
  900. """!Query tools menu"""
  901. if self.toolbars['map']:
  902. self.toolbars['map'].OnTool(event)
  903. action = self.toolbars['map'].GetAction()
  904. self.toolbars['map'].action['desc'] = 'queryMap'
  905. self.MapWindow.mouse['use'] = "query"
  906. if not self.IsStandalone():
  907. # switch to output console to show query results
  908. self._layerManager.notebook.SetSelectionByName('output')
  909. self.MapWindow.mouse['box'] = "point"
  910. self.MapWindow.zoomtype = 0
  911. # change the cursor
  912. self.MapWindow.SetCursor(self.cursors["cross"])
  913. def AddTmpVectorMapLayer(self, name, cats, useId = False, addLayer = True):
  914. """!Add temporal vector map layer to map composition
  915. @param name name of map layer
  916. @param useId use feature id instead of category
  917. """
  918. # color settings from ATM
  919. color = UserSettings.Get(group = 'atm', key = 'highlight', subkey = 'color')
  920. colorStr = str(color[0]) + ":" + \
  921. str(color[1]) + ":" + \
  922. str(color[2])
  923. # icon used in vector display and its size
  924. icon = ''
  925. size = 0
  926. vparam = self.tree.GetPyData(self.tree.layer_selected)[0]['cmd']
  927. for p in vparam:
  928. if '=' in p:
  929. parg,pval = p.split('=')
  930. if parg == 'icon': icon = pval
  931. elif parg == 'size': size = int(pval)
  932. pattern = ["d.vect",
  933. "map=%s" % name,
  934. "color=%s" % colorStr,
  935. "fcolor=%s" % colorStr,
  936. "width=%d" % UserSettings.Get(group = 'atm', key = 'highlight', subkey = 'width')]
  937. if icon != '':
  938. pattern.append('icon=%s' % icon)
  939. if size > 0:
  940. pattern.append('size=%i' % size)
  941. if useId:
  942. cmd = pattern
  943. cmd.append('-i')
  944. cmd.append('cats=%s' % str(cats))
  945. else:
  946. cmd = []
  947. for layer in cats.keys():
  948. cmd.append(copy.copy(pattern))
  949. lcats = cats[layer]
  950. cmd[-1].append("layer=%d" % layer)
  951. cmd[-1].append("cats=%s" % utils.ListOfCatsToRange(lcats))
  952. if addLayer:
  953. if useId:
  954. return self.Map.AddLayer(type = 'vector', name = globalvar.QUERYLAYER, command = cmd,
  955. l_active = True, l_hidden = True, l_opacity = 1.0)
  956. else:
  957. return self.Map.AddLayer(type = 'command', name = globalvar.QUERYLAYER, command = cmd,
  958. l_active = True, l_hidden = True, l_opacity = 1.0)
  959. else:
  960. return cmd
  961. def OnAnalyze(self, event):
  962. """!Analysis tools menu
  963. """
  964. point = wx.GetMousePosition()
  965. toolsmenu = wx.Menu()
  966. icons = Icons['displayWindow']
  967. # Add items to the menu
  968. measure = wx.MenuItem(toolsmenu, wx.ID_ANY, icons["measure"].GetLabel())
  969. measure.SetBitmap(icons["measure"].GetBitmap(self.iconsize))
  970. toolsmenu.AppendItem(measure)
  971. self.Bind(wx.EVT_MENU, self.OnMeasure, measure)
  972. profile = wx.MenuItem(toolsmenu, wx.ID_ANY, icons["profile"].GetLabel())
  973. profile.SetBitmap(icons["profile"].GetBitmap(self.iconsize))
  974. toolsmenu.AppendItem(profile)
  975. self.Bind(wx.EVT_MENU, self.OnProfile, profile)
  976. scatterplot = wx.MenuItem(toolsmenu, wx.ID_ANY, _("Create bivariate scatterplot of raster maps"))
  977. scatterplot.SetBitmap(icons["profile"].GetBitmap(self.iconsize))
  978. toolsmenu.AppendItem(scatterplot)
  979. self.Bind(wx.EVT_MENU, self.OnScatterplot, scatterplot)
  980. histogram2 = wx.MenuItem(toolsmenu, wx.ID_ANY, icons["histogram"].GetLabel())
  981. histogram2.SetBitmap(icons["histogram"].GetBitmap(self.iconsize))
  982. toolsmenu.AppendItem(histogram2)
  983. self.Bind(wx.EVT_MENU, self.OnHistogramPyPlot, histogram2)
  984. histogram = wx.MenuItem(toolsmenu, wx.ID_ANY, _("Create histogram with d.histogram"))
  985. histogram.SetBitmap(icons["histogram"].GetBitmap(self.iconsize))
  986. toolsmenu.AppendItem(histogram)
  987. self.Bind(wx.EVT_MENU, self.OnHistogram, histogram)
  988. # Popup the menu. If an item is selected then its handler
  989. # will be called before PopupMenu returns.
  990. self.PopupMenu(toolsmenu)
  991. toolsmenu.Destroy()
  992. def OnMeasure(self, event):
  993. """!Init measurement routine that calculates map distance
  994. along transect drawn on map display
  995. """
  996. self.totaldist = 0.0 # total measured distance
  997. # switch Layer Manager to output console to show measure results
  998. self._layerManager.notebook.SetSelectionByName('output')
  999. # change mouse to draw line for measurement
  1000. self.MapWindow.mouse['use'] = "measure"
  1001. self.MapWindow.mouse['box'] = "line"
  1002. self.MapWindow.zoomtype = 0
  1003. self.MapWindow.pen = wx.Pen(colour = 'red', width = 2, style = wx.SHORT_DASH)
  1004. self.MapWindow.polypen = wx.Pen(colour = 'green', width = 2, style = wx.SHORT_DASH)
  1005. # change the cursor
  1006. self.MapWindow.SetCursor(self.cursors["pencil"])
  1007. # initiating output
  1008. style = self._layerManager.goutput.cmd_output.StyleWarning
  1009. self._layerManager.goutput.WriteLog(_('Click and drag with left mouse button '
  1010. 'to measure.%s'
  1011. 'Double click with left button to clear.') % \
  1012. (os.linesep), style)
  1013. if self.Map.projinfo['proj'] != 'xy':
  1014. units = self.Map.projinfo['units']
  1015. self._layerManager.goutput.WriteCmdLog(_('Measuring distance') + ' ('
  1016. + units + '):')
  1017. else:
  1018. self._layerManager.goutput.WriteCmdLog(_('Measuring distance:'))
  1019. if self.Map.projinfo['proj'] == 'll':
  1020. try:
  1021. import grass.lib.gis as gislib
  1022. global haveCtypes
  1023. haveCtypes = True
  1024. gislib.G_begin_distance_calculations()
  1025. except ImportError, e:
  1026. self._layerManager.goutput.WriteWarning(_('Geodesic distance is not yet '
  1027. 'supported by this tool.\n'
  1028. 'Reason: %s' % e))
  1029. def MeasureDist(self, beginpt, endpt):
  1030. """!Calculate map distance from screen distance
  1031. and print to output window
  1032. """
  1033. self._layerManager.notebook.SetSelectionByName('output')
  1034. dist, (north, east) = self.MapWindow.Distance(beginpt, endpt)
  1035. dist = round(dist, 3)
  1036. d, dunits = self.FormatDist(dist)
  1037. self.totaldist += dist
  1038. td, tdunits = self.FormatDist(self.totaldist)
  1039. strdist = str(d)
  1040. strtotdist = str(td)
  1041. if self.Map.projinfo['proj'] == 'xy' or 'degree' not in self.Map.projinfo['unit']:
  1042. angle = int(math.degrees(math.atan2(north,east)) + 0.5)
  1043. angle = 180 - angle
  1044. if angle < 0:
  1045. angle = 360 + angle
  1046. mstring = '%s = %s %s\n%s = %s %s\n%s = %d %s\n%s' \
  1047. % (_('segment'), strdist, dunits,
  1048. _('total distance'), strtotdist, tdunits,
  1049. _('bearing'), angle, _('deg'),
  1050. '-' * 60)
  1051. else:
  1052. mstring = '%s = %s %s\n%s = %s %s\n%s' \
  1053. % (_('segment'), strdist, dunits,
  1054. _('total distance'), strtotdist, tdunits,
  1055. '-' * 60)
  1056. self._layerManager.goutput.WriteLog(mstring)
  1057. return dist
  1058. def OnProfile(self, event):
  1059. """!Init profile canvas and tools
  1060. """
  1061. raster = []
  1062. if self.tree.layer_selected and \
  1063. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] == 'raster':
  1064. raster.append(self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name)
  1065. self.profile = ProfileFrame(self,
  1066. id = wx.ID_ANY, pos = wx.DefaultPosition, size = (700,300),
  1067. style = wx.DEFAULT_FRAME_STYLE,
  1068. rasterList = raster)
  1069. self.profile.Show()
  1070. # Open raster select dialog to make sure that a raster (and the desired raster)
  1071. # is selected to be profiled
  1072. self.profile.OnSelectRaster(None)
  1073. def FormatDist(self, dist):
  1074. """!Format length numbers and units in a nice way,
  1075. as a function of length. From code by Hamish Bowman
  1076. Grass Development Team 2006"""
  1077. mapunits = self.Map.projinfo['units']
  1078. if mapunits == 'metres':
  1079. mapunits = 'meters'
  1080. outunits = mapunits
  1081. dist = float(dist)
  1082. divisor = 1.0
  1083. # figure out which units to use
  1084. if mapunits == 'meters':
  1085. if dist > 2500.0:
  1086. outunits = 'km'
  1087. divisor = 1000.0
  1088. else: outunits = 'm'
  1089. elif mapunits == 'feet':
  1090. # nano-bug: we match any "feet", but US Survey feet is really
  1091. # 5279.9894 per statute mile, or 10.6' per 1000 miles. As >1000
  1092. # miles the tick markers are rounded to the nearest 10th of a
  1093. # mile (528'), the difference in foot flavours is ignored.
  1094. if dist > 5280.0:
  1095. outunits = 'miles'
  1096. divisor = 5280.0
  1097. else:
  1098. outunits = 'ft'
  1099. elif 'degree' in mapunits and \
  1100. not haveCtypes:
  1101. if dist < 1:
  1102. outunits = 'min'
  1103. divisor = (1/60.0)
  1104. else:
  1105. outunits = 'deg'
  1106. else:
  1107. outunits = 'meters'
  1108. # format numbers in a nice way
  1109. if (dist/divisor) >= 2500.0:
  1110. outdist = round(dist/divisor)
  1111. elif (dist/divisor) >= 1000.0:
  1112. outdist = round(dist/divisor,1)
  1113. elif (dist/divisor) > 0.0:
  1114. outdist = round(dist/divisor,int(math.ceil(3-math.log10(dist/divisor))))
  1115. else:
  1116. outdist = float(dist/divisor)
  1117. return (outdist, outunits)
  1118. def OnHistogramPyPlot(self, event):
  1119. """!Init PyPlot histogram display canvas and tools
  1120. """
  1121. raster = []
  1122. for layer in self.tree.GetSelections():
  1123. if self.tree.GetPyData(layer)[0]['maplayer'].GetType() != 'raster':
  1124. continue
  1125. raster.append(self.tree.GetPyData(layer)[0]['maplayer'].GetName())
  1126. self.histogramPyPlot = HistFramePyPlot(self, id = wx.ID_ANY,
  1127. pos = wx.DefaultPosition, size = (700,300),
  1128. style = wx.DEFAULT_FRAME_STYLE,
  1129. rasterList = raster)
  1130. self.histogramPyPlot.Show()
  1131. # Open raster select dialog to make sure that a raster (and the desired raster)
  1132. # is selected to be histogrammed
  1133. self.histogramPyPlot.OnSelectRaster(None)
  1134. def OnScatterplot(self, event):
  1135. """!Init PyPlot scatterplot display canvas and tools
  1136. """
  1137. raster = []
  1138. for layer in self.tree.GetSelections():
  1139. if self.tree.GetPyData(layer)[0]['maplayer'].GetType() != 'raster':
  1140. continue
  1141. raster.append(self.tree.GetPyData(layer)[0]['maplayer'].GetName())
  1142. self.scatterplot = ScatterFrame(self, id = wx.ID_ANY,
  1143. pos = wx.DefaultPosition, size = (700,300),
  1144. style = wx.DEFAULT_FRAME_STYLE,
  1145. rasterList = raster)
  1146. self.scatterplot.Show()
  1147. # Open raster select dialog to make sure that at least 2 rasters (and the desired rasters)
  1148. # are selected to be plotted
  1149. self.scatterplot.OnSelectRaster(None)
  1150. def OnHistogram(self, event):
  1151. """!Init histogram display canvas and tools
  1152. """
  1153. self.histogram = HistFrame(parent = self, id = wx.ID_ANY, size = globalvar.HIST_WINDOW_SIZE,
  1154. style = wx.DEFAULT_FRAME_STYLE)
  1155. # show new display
  1156. self.histogram.Show()
  1157. self.histogram.Refresh()
  1158. self.histogram.Update()
  1159. def OnDecoration(self, event):
  1160. """!Decorations overlay menu
  1161. """
  1162. point = wx.GetMousePosition()
  1163. decmenu = wx.Menu()
  1164. icons = Icons['displayWindow']
  1165. # Add items to the menu
  1166. AddScale = wx.MenuItem(decmenu, wx.ID_ANY, icons["addBarscale"].GetLabel())
  1167. AddScale.SetBitmap(icons["addBarscale"].GetBitmap(self.iconsize))
  1168. decmenu.AppendItem(AddScale)
  1169. self.Bind(wx.EVT_MENU, self.OnAddBarscale, AddScale)
  1170. # temporary
  1171. if self.IsPaneShown('3d'):
  1172. AddScale.Enable(False)
  1173. AddArrow = wx.MenuItem(decmenu, wx.ID_ANY, _("Add north arrow"))
  1174. AddArrow.SetBitmap(icons["addBarscale"].GetBitmap(self.iconsize))
  1175. decmenu.AppendItem(AddArrow)
  1176. self.Bind(wx.EVT_MENU, self.OnAddArrow, AddArrow)
  1177. AddLegend = wx.MenuItem(decmenu, wx.ID_ANY, icons["addLegend"].GetLabel())
  1178. AddLegend.SetBitmap(icons["addLegend"].GetBitmap(self.iconsize))
  1179. decmenu.AppendItem(AddLegend)
  1180. self.Bind(wx.EVT_MENU, self.OnAddLegend, AddLegend)
  1181. AddText = wx.MenuItem(decmenu, wx.ID_ANY, icons["addText"].GetLabel())
  1182. AddText.SetBitmap(icons["addText"].GetBitmap(self.iconsize))
  1183. decmenu.AppendItem(AddText)
  1184. self.Bind(wx.EVT_MENU, self.OnAddText, AddText)
  1185. # Popup the menu. If an item is selected then its handler
  1186. # will be called before PopupMenu returns.
  1187. self.PopupMenu(decmenu)
  1188. decmenu.Destroy()
  1189. def OnAddBarscale(self, event):
  1190. """!Handler for scale/arrow map decoration menu selection.
  1191. """
  1192. if self.dialogs['barscale']:
  1193. return
  1194. id = 0 # unique index for overlay layer
  1195. # If location is latlon, only display north arrow (scale won't work)
  1196. # proj = self.Map.projinfo['proj']
  1197. # if proj == 'll':
  1198. # barcmd = 'd.barscale -n'
  1199. # else:
  1200. # barcmd = 'd.barscale'
  1201. # decoration overlay control dialog
  1202. self.dialogs['barscale'] = \
  1203. gdialogs.DecorationDialog(parent = self, title = _('Scale and North arrow'),
  1204. size = (350, 200),
  1205. style = wx.DEFAULT_DIALOG_STYLE | wx.CENTRE,
  1206. cmd = ['d.barscale', 'at=0,95'],
  1207. ovlId = id,
  1208. name = 'barscale',
  1209. checktxt = _("Show/hide scale and North arrow"),
  1210. ctrltxt = _("scale object"))
  1211. self.dialogs['barscale'].CentreOnParent()
  1212. ### dialog cannot be show as modal - in the result d.barscale is not selectable
  1213. ### self.dialogs['barscale'].ShowModal()
  1214. self.dialogs['barscale'].Show()
  1215. self.MapWindow.mouse['use'] = 'pointer'
  1216. def OnAddLegend(self, event):
  1217. """!Handler for legend map decoration menu selection.
  1218. """
  1219. if self.dialogs['legend']:
  1220. return
  1221. id = 1 # index for overlay layer in render
  1222. cmd = ['d.legend', 'at=5,50,2,5']
  1223. if self.tree.layer_selected and \
  1224. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] == 'raster':
  1225. cmd.append('map=%s' % self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name)
  1226. # Decoration overlay control dialog
  1227. self.dialogs['legend'] = \
  1228. gdialogs.DecorationDialog(parent = self, title = ('Legend'),
  1229. size = (350, 200),
  1230. style = wx.DEFAULT_DIALOG_STYLE | wx.CENTRE,
  1231. cmd = cmd,
  1232. ovlId = id,
  1233. name = 'legend',
  1234. checktxt = _("Show/hide legend"),
  1235. ctrltxt = _("legend object"))
  1236. self.dialogs['legend'].CentreOnParent()
  1237. ### dialog cannot be show as modal - in the result d.legend is not selectable
  1238. ### self.dialogs['legend'].ShowModal()
  1239. self.dialogs['legend'].Show()
  1240. self.MapWindow.mouse['use'] = 'pointer'
  1241. def OnAddText(self, event):
  1242. """!Handler for text decoration menu selection.
  1243. """
  1244. if self.MapWindow.dragid > -1:
  1245. id = self.MapWindow.dragid
  1246. self.MapWindow.dragid = -1
  1247. else:
  1248. # index for overlay layer in render
  1249. if len(self.MapWindow.textdict.keys()) > 0:
  1250. id = max(self.MapWindow.textdict.keys()) + 1
  1251. else:
  1252. id = 101
  1253. self.dialogs['text'] = gdialogs.TextLayerDialog(parent = self, ovlId = id,
  1254. title = _('Add text layer'),
  1255. size = (400, 200))
  1256. self.dialogs['text'].CenterOnParent()
  1257. # If OK button pressed in decoration control dialog
  1258. if self.dialogs['text'].ShowModal() == wx.ID_OK:
  1259. text = self.dialogs['text'].GetValues()['text']
  1260. active = self.dialogs['text'].GetValues()['active']
  1261. # delete object if it has no text or is not active
  1262. if text == '' or active == False:
  1263. try:
  1264. self.MapWindow2D.pdc.ClearId(id)
  1265. self.MapWindow2D.pdc.RemoveId(id)
  1266. del self.MapWindow.textdict[id]
  1267. if self.IsPaneShown('3d'):
  1268. self.MapWindow3D.UpdateOverlays()
  1269. self.MapWindow.UpdateMap()
  1270. else:
  1271. self.MapWindow2D.UpdateMap(render = False, renderVector = False)
  1272. except:
  1273. pass
  1274. return
  1275. self.MapWindow.textdict[id] = self.dialogs['text'].GetValues()
  1276. if self.IsPaneShown('3d'):
  1277. self.MapWindow3D.UpdateOverlays()
  1278. self.MapWindow3D.UpdateMap()
  1279. else:
  1280. self.MapWindow2D.pdc.ClearId(id)
  1281. self.MapWindow2D.pdc.SetId(id)
  1282. self.MapWindow2D.UpdateMap(render = False, renderVector = False)
  1283. self.MapWindow.mouse['use'] = 'pointer'
  1284. def OnAddArrow(self, event):
  1285. """!Handler for north arrow menu selection.
  1286. Opens Appearance page of nviz notebook.
  1287. """
  1288. self._layerManager.nviz.SetPage('decoration')
  1289. self.MapWindow3D.SetDrawArrow((70, 70))
  1290. def GetOptData(self, dcmd, type, params, propwin):
  1291. """!Callback method for decoration overlay command generated by
  1292. dialog created in menuform.py
  1293. """
  1294. # Reset comand and rendering options in render.Map. Always render decoration.
  1295. # Showing/hiding handled by PseudoDC
  1296. self.Map.ChangeOverlay(ovltype = type, type = 'overlay', name = '', command = dcmd,
  1297. l_active = True, l_render = False)
  1298. self.params[type] = params
  1299. self.propwin[type] = propwin
  1300. def OnZoomToMap(self, event):
  1301. """!Set display extents to match selected raster (including
  1302. NULLs) or vector map.
  1303. """
  1304. self.MapWindow.ZoomToMap()
  1305. def OnZoomToRaster(self, event):
  1306. """!Set display extents to match selected raster map (ignore NULLs)
  1307. """
  1308. self.MapWindow.ZoomToMap(ignoreNulls = True)
  1309. def OnZoomToWind(self, event):
  1310. """!Set display geometry to match computational region
  1311. settings (set with g.region)
  1312. """
  1313. self.MapWindow.ZoomToWind()
  1314. def OnZoomToDefault(self, event):
  1315. """!Set display geometry to match default region settings
  1316. """
  1317. self.MapWindow.ZoomToDefault()
  1318. def OnZoomToSaved(self, event):
  1319. """!Set display geometry to match extents in
  1320. saved region file
  1321. """
  1322. self.MapWindow.ZoomToSaved()
  1323. def OnDisplayToWind(self, event):
  1324. """!Set computational region (WIND file) to match display
  1325. extents
  1326. """
  1327. self.MapWindow.DisplayToWind()
  1328. def SaveDisplayRegion(self, event):
  1329. """!Save display extents to named region file.
  1330. """
  1331. self.MapWindow.SaveDisplayRegion()
  1332. def OnZoomMenu(self, event):
  1333. """!Popup Zoom menu
  1334. """
  1335. point = wx.GetMousePosition()
  1336. zoommenu = wx.Menu()
  1337. # Add items to the menu
  1338. zoomwind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to computational region'))
  1339. zoommenu.AppendItem(zoomwind)
  1340. self.Bind(wx.EVT_MENU, self.OnZoomToWind, zoomwind)
  1341. zoomdefault = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to default region'))
  1342. zoommenu.AppendItem(zoomdefault)
  1343. self.Bind(wx.EVT_MENU, self.OnZoomToDefault, zoomdefault)
  1344. zoomsaved = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to saved region'))
  1345. zoommenu.AppendItem(zoomsaved)
  1346. self.Bind(wx.EVT_MENU, self.OnZoomToSaved, zoomsaved)
  1347. savewind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Set computational region from display extent'))
  1348. zoommenu.AppendItem(savewind)
  1349. self.Bind(wx.EVT_MENU, self.OnDisplayToWind, savewind)
  1350. savezoom = wx.MenuItem(zoommenu, wx.ID_ANY, _('Save display geometry to named region'))
  1351. zoommenu.AppendItem(savezoom)
  1352. self.Bind(wx.EVT_MENU, self.SaveDisplayRegion, savezoom)
  1353. # Popup the menu. If an item is selected then its handler
  1354. # will be called before PopupMenu returns.
  1355. self.PopupMenu(zoommenu)
  1356. zoommenu.Destroy()
  1357. def SetProperties(self, render = False, mode = 0, showCompExtent = False,
  1358. constrainRes = False, projection = False, alignExtent = True):
  1359. """!Set properies of map display window"""
  1360. self.SetProperty('render', render)
  1361. self.statusbarManager.SetMode(mode)
  1362. self.StatusbarUpdate()
  1363. self.SetProperty('region', showCompExtent)
  1364. self.SetProperty('alignExtent', alignExtent)
  1365. self.SetProperty('resolution', constrainRes)
  1366. self.SetProperty('projection', projection)
  1367. def IsStandalone(self):
  1368. """!Check if Map display is standalone"""
  1369. if self._layerManager:
  1370. return False
  1371. return True
  1372. def GetLayerManager(self):
  1373. """!Get reference to Layer Manager
  1374. @return window reference
  1375. @return None (if standalone)
  1376. """
  1377. return self._layerManager
  1378. def GetMapToolbar(self):
  1379. """!Returns toolbar with zooming tools"""
  1380. return self.toolbars['map']
  1381. class MapApp(wx.App):
  1382. def OnInit(self):
  1383. wx.InitAllImageHandlers()
  1384. if __name__ == "__main__":
  1385. self.cmdTimeStamp = os.path.getmtime(monFile['cmd'])
  1386. Map = render.Map(cmdfile = monFile['cmd'], mapfile = monFile['map'],
  1387. envfile = monFile['env'], monitor = monName)
  1388. else:
  1389. Map = None
  1390. self.mapFrm = MapFrame(parent = None, id = wx.ID_ANY, Map = Map,
  1391. size = monSize)
  1392. # self.SetTopWindow(Map)
  1393. self.mapFrm.Show()
  1394. if __name__ == "__main__":
  1395. self.timer = wx.PyTimer(self.watcher)
  1396. #check each 0.5s
  1397. global mtime
  1398. mtime = 500
  1399. self.timer.Start(mtime)
  1400. return True
  1401. def OnExit(self):
  1402. if __name__ == "__main__":
  1403. # stop the timer
  1404. # self.timer.Stop()
  1405. # terminate thread
  1406. for f in monFile.itervalues():
  1407. grass.try_remove(f)
  1408. def watcher(self):
  1409. """!Redraw, if new layer appears (check's timestamp of
  1410. cmdfile)
  1411. """
  1412. # todo: events
  1413. if os.path.getmtime(monFile['cmd']) > self.cmdTimeStamp:
  1414. self.timer.Stop()
  1415. self.cmdTimeStamp = os.path.getmtime(monFile['cmd'])
  1416. self.mapFrm.OnDraw(None)
  1417. self.timer.Start(mtime)
  1418. if __name__ == "__main__":
  1419. # set command variable
  1420. if len(sys.argv) < 5:
  1421. print __doc__
  1422. sys.exit(1)
  1423. monName = sys.argv[1]
  1424. monFile = { 'map' : sys.argv[2],
  1425. 'cmd' : sys.argv[3],
  1426. 'env' : sys.argv[4],
  1427. }
  1428. if len(sys.argv) >= 6:
  1429. try:
  1430. monSize[0] = int(sys.argv[5])
  1431. except ValueError:
  1432. pass
  1433. if len(sys.argv) == 7:
  1434. try:
  1435. monSize[1] = int(sys.argv[6])
  1436. except ValueError:
  1437. pass
  1438. import gettext
  1439. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  1440. grass.verbose(_("Starting map display <%s>...") % (monName))
  1441. gcmd.RunCommand('g.gisenv',
  1442. set = 'MONITOR_%s_PID=%d' % (monName, os.getpid()))
  1443. gm_map = MapApp(0)
  1444. # set title
  1445. gm_map.mapFrm.SetTitle(_("GRASS GIS Map Display: " +
  1446. monName +
  1447. " - Location: " + grass.gisenv()["LOCATION_NAME"]))
  1448. gm_map.MainLoop()
  1449. grass.verbose(_("Stopping map display <%s>...") % (monName))
  1450. # clean up GRASS env variables
  1451. env = grass.gisenv()
  1452. env_name = 'MONITOR_%s' % monName
  1453. for key in env.keys():
  1454. if key.find(env_name) == 0:
  1455. gcmd.RunCommand('g.gisenv',
  1456. set = '%s=' % key)
  1457. if key == 'MONITOR' and env[key] == monName:
  1458. gcmd.RunCommand('g.gisenv',
  1459. set = '%s=' % key)
  1460. sys.exit(0)