mapdisp.py 84 KB

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