mapdisp.py 86 KB

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