mapdisp.py 86 KB

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