mapdisp.py 78 KB

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