mapdisp.py 85 KB

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