gcpmapdisp.py 94 KB

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