mapdisp.py 84 KB

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