gcpmapdisp.py 93 KB

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