mapdisp.py 85 KB

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