mapdisp.py 87 KB

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