mapdisp.py 81 KB

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