mapdisp.py 86 KB

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