mapdisp.py 64 KB

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