mapdisp.py 84 KB

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