gcpmapdisp.py 97 KB

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