mapdisp.py 82 KB

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