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