mapdisp.py 85 KB

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