mapdisp.py 87 KB

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