mapdisp.py 84 KB

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