mapdisp.py 90 KB

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