mapdisp.py 85 KB

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