mapdisp.py 88 KB

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