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