mapdisp.py 87 KB

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