mapdisp.py 85 KB

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